LLVM 24.0.0git
Local.h
Go to the documentation of this file.
1//===- Local.h - Functions to perform local transformations -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This family of functions perform various local transformations to the
10// program.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_UTILS_LOCAL_H
15#define LLVM_TRANSFORMS_UTILS_LOCAL_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/IR/Dominators.h"
23#include <cstdint>
24
25namespace llvm {
26
27class DataLayout;
28class Value;
29class WeakTrackingVH;
30class WeakVH;
31template <typename PtrType> class SmallPtrSetImpl;
32template <typename T> class SmallVectorImpl;
33class AAResults;
34class AllocaInst;
35class AssumptionCache;
36class BasicBlock;
37class CallBase;
38class CallInst;
39class CondBrInst;
40class DIBuilder;
41class DomTreeUpdater;
42class Function;
43class Instruction;
44class InvokeInst;
45class LoadInst;
46class MDNode;
48class PHINode;
49class StoreInst;
52
53//===----------------------------------------------------------------------===//
54// Local constant propagation.
55//
56
57/// If a terminator instruction is predicated on a constant value, convert it
58/// into an unconditional branch to the constant destination.
59/// This is a nontrivial operation because the successors of this basic block
60/// must have their PHI nodes updated.
61/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
62/// conditions and indirectbr addresses this might make dead if
63/// DeleteDeadConditions is true.
65 bool DeleteDeadConditions = false,
66 const TargetLibraryInfo *TLI = nullptr,
67 DomTreeUpdater *DTU = nullptr);
68
69//===----------------------------------------------------------------------===//
70// Local dead code elimination.
71//
72
73/// Return true if the result produced by the instruction is not used, and the
74/// instruction will return. Certain side-effecting instructions are also
75/// considered dead if there are no uses of the instruction.
76LLVM_ABI bool
78 const TargetLibraryInfo *TLI = nullptr);
79
80/// Return true if the result produced by the instruction would have no side
81/// effects if it was not used. This is equivalent to checking whether
82/// isInstructionTriviallyDead would be true if the use count was 0.
83LLVM_ABI bool
85 const TargetLibraryInfo *TLI = nullptr);
86
87/// Return true if the result produced by the instruction has no side effects on
88/// any paths other than where it is used. This is less conservative than
89/// wouldInstructionBeTriviallyDead which is based on the assumption
90/// that the use count will be 0. An example usage of this API is for
91/// identifying instructions that can be sunk down to use(s).
93 Instruction *I, const TargetLibraryInfo *TLI = nullptr);
94
95/// If the specified value is a trivially dead instruction, delete it.
96/// If that makes any of its operands trivially dead, delete them too,
97/// recursively. Return true if any instructions were deleted.
99 Value *V, const TargetLibraryInfo *TLI = nullptr,
100 MemorySSAUpdater *MSSAU = nullptr,
101 std::function<void(Value *)> AboutToDeleteCallback =
102 std::function<void(Value *)>());
103
104/// Delete all of the instructions in `DeadInsts`, and all other instructions
105/// that deleting these in turn causes to be trivially dead.
106///
107/// The initial instructions in the provided vector must all have empty use
108/// lists and satisfy `isInstructionTriviallyDead`.
109///
110/// `DeadInsts` will be used as scratch storage for this routine and will be
111/// empty afterward.
114 const TargetLibraryInfo *TLI = nullptr, MemorySSAUpdater *MSSAU = nullptr,
115 std::function<void(Value *)> AboutToDeleteCallback =
116 std::function<void(Value *)>());
117
118/// Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow
119/// instructions that are not trivially dead. These will be ignored.
120/// Returns true if any changes were made, i.e. any instructions trivially dead
121/// were found and deleted.
124 const TargetLibraryInfo *TLI = nullptr, MemorySSAUpdater *MSSAU = nullptr,
125 std::function<void(Value *)> AboutToDeleteCallback =
126 std::function<void(Value *)>());
127
128/// If the specified value is an effectively dead PHI node, due to being a
129/// def-use chain of single-use nodes that either forms a cycle or is terminated
130/// by a trivially dead instruction, delete it. If that makes any of its
131/// operands trivially dead, delete them too, recursively. Return true if a
132/// change was made.
134 PHINode *PN, const TargetLibraryInfo *TLI = nullptr,
135 MemorySSAUpdater *MSSAU = nullptr,
136 SmallPtrSetImpl<PHINode *> *KnownNonDeadPHIs = nullptr);
137
138/// Scan the specified basic block and try to simplify any instructions in it
139/// and recursively delete dead instructions.
140///
141/// This returns true if it changed the code, note that it can delete
142/// instructions in other blocks as well in this block.
143LLVM_ABI bool
145 const TargetLibraryInfo *TLI = nullptr);
146
147/// Replace all the uses of an SSA value in @llvm.dbg intrinsics with
148/// undef. This is useful for signaling that a variable, e.g. has been
149/// found dead and hence it's unavailable at a given program point.
150/// Returns true if the dbg values have been changed.
152
153//===----------------------------------------------------------------------===//
154// Control Flow Graph Restructuring.
155//
156
157/// BB is a block with one predecessor and its predecessor is known to have one
158/// successor (BB!). Eliminate the edge between them, moving the instructions in
159/// the predecessor into BB. This deletes the predecessor block.
161 DomTreeUpdater *DTU = nullptr);
162
163/// BB is known to contain an unconditional branch, and contains no instructions
164/// other than PHI nodes, potential debug intrinsics and the branch. If
165/// possible, eliminate BB by rewriting all the predecessors to branch to the
166/// successor block and return true. If we can't transform, return false.
167LLVM_ABI bool
169 DomTreeUpdater *DTU = nullptr);
170
171/// Check for and eliminate duplicate PHI nodes in this block. This doesn't try
172/// to be clever about PHI nodes which differ only in the order of the incoming
173/// values, but instcombine orders them so it usually won't matter.
174///
175/// This overload removes the duplicate PHI nodes directly.
177
178/// Check for and eliminate duplicate PHI nodes in this block. This doesn't try
179/// to be clever about PHI nodes which differ only in the order of the incoming
180/// values, but instcombine orders them so it usually won't matter.
181///
182/// This overload collects the PHI nodes to be removed into the ToRemove set.
185
186/// This function is used to do simplification of a CFG. For example, it
187/// adjusts branches to branches to eliminate the extra hop, it eliminates
188/// unreachable basic blocks, and does other peephole optimization of the CFG.
189/// It returns true if a modification was made, possibly deleting the basic
190/// block that was pointed to. LoopHeaders is an optional input parameter
191/// providing the set of loop headers that SimplifyCFG should not eliminate.
194 DomTreeUpdater *DTU = nullptr,
195 const SimplifyCFGOptions &Options = {},
196 ArrayRef<WeakVH> LoopHeaders = {});
197
198/// This function is used to flatten a CFG. For example, it uses parallel-and
199/// and parallel-or mode to collapse if-conditions and merge if-regions with
200/// identical statements.
201LLVM_ABI bool FlattenCFG(BasicBlock *BB, AAResults *AA = nullptr);
202
203/// If this basic block is ONLY a setcc and a branch, and if a predecessor
204/// branches to us and one of our successors, fold the setcc into the
205/// predecessor and use logical operations to pick the right destination.
207 llvm::DomTreeUpdater *DTU = nullptr,
208 MemorySSAUpdater *MSSAU = nullptr,
209 const TargetTransformInfo *TTI = nullptr,
210 AssumptionCache *AC = nullptr,
211 unsigned BonusInstThreshold = 1);
212
213/// This function takes a virtual register computed by an Instruction and
214/// replaces it with a slot in the stack frame, allocated via alloca.
215/// This allows the CFG to be changed around without fear of invalidating the
216/// SSA information for the value. It returns the pointer to the alloca inserted
217/// to create a stack slot for X.
219 Instruction &X, bool VolatileLoads = false,
220 std::optional<BasicBlock::iterator> AllocaPoint = std::nullopt);
221
222/// This function takes a virtual register computed by a phi node and replaces
223/// it with a slot in the stack frame, allocated via alloca. The phi node is
224/// deleted and it returns the pointer to the alloca inserted.
226 PHINode *P, std::optional<BasicBlock::iterator> AllocaPoint = std::nullopt);
227
228/// If the specified pointer points to an object that we control, try to modify
229/// the object's alignment to PrefAlign. Returns a minimum known alignment of
230/// the value after the operation, which may be lower than PrefAlign.
231///
232/// Increating value alignment isn't often possible though. If alignment is
233/// important, a more reliable approach is to simply align all global variables
234/// and allocation instructions to their preferred alignment from the beginning.
236 const DataLayout &DL);
237
238/// Try to ensure that the alignment of \p V is at least \p PrefAlign bytes. If
239/// the owning object can be modified and has an alignment less than \p
240/// PrefAlign, it will be increased and \p PrefAlign returned. If the alignment
241/// cannot be increased, the known alignment of the value is returned.
242///
243/// It is not always possible to modify the alignment of the underlying object,
244/// so if alignment is important, a more reliable approach is to simply align
245/// all global variables and allocation instructions to their preferred
246/// alignment from the beginning.
248 const DataLayout &DL,
249 const Instruction *CxtI = nullptr,
250 AssumptionCache *AC = nullptr,
251 const DominatorTree *DT = nullptr);
252
253/// Try to infer an alignment for the specified pointer.
255 const Instruction *CxtI = nullptr,
256 AssumptionCache *AC = nullptr,
257 const DominatorTree *DT = nullptr) {
258 return getOrEnforceKnownAlignment(V, MaybeAlign(), DL, CxtI, AC, DT);
259}
260
261/// Create a call that matches the invoke \p II in terms of arguments,
262/// attributes, debug information, etc. The call is not placed in a block and it
263/// will not have a name. The invoke instruction is not removed, nor are the
264/// uses replaced by the new call.
265LLVM_ABI CallInst *createCallMatchingInvoke(InvokeInst *II);
266
267/// This function converts the specified invoke into a normal call.
268LLVM_ABI CallInst *changeToCall(InvokeInst *II, DomTreeUpdater *DTU = nullptr);
269
270///===---------------------------------------------------------------------===//
271/// Dbg Intrinsic utilities
272///
273
274/// Creates and inserts a dbg_value record intrinsic before a store
275/// that has an associated llvm.dbg.value intrinsic.
276LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI,
277 DIBuilder &Builder);
278
279/// Inserts a dbg.value record before a store to an alloca'd value
280/// that has an associated dbg.declare record.
281LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
282 StoreInst *SI,
283 DIBuilder &Builder);
284
285/// Inserts a dbg.value record before a load of an alloca'd value
286/// that has an associated dbg.declare record.
287LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
288 LoadInst *LI, DIBuilder &Builder);
289
290/// Inserts a dbg.value record after a phi that has an associated
291/// llvm.dbg.declare record.
292LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
293 PHINode *LI, DIBuilder &Builder);
294
295/// Lowers dbg.declare records into appropriate set of dbg.value records.
297
298/// Propagate dbg.value intrinsics through the newly inserted PHIs.
299LLVM_ABI void
300insertDebugValuesForPHIs(BasicBlock *BB,
301 SmallVectorImpl<PHINode *> &InsertedPHIs);
302
303/// Replaces dbg.declare record when the address it
304/// describes is replaced with a new value. If Deref is true, an
305/// additional DW_OP_deref is prepended to the expression. If Offset
306/// is non-zero, a constant displacement is added to the expression
307/// (between the optional Deref operations). Offset can be negative.
308LLVM_ABI bool replaceDbgDeclare(Value *Address, Value *NewAddress,
309 DIBuilder &Builder, uint8_t DIExprFlags,
310 int Offset);
311
312/// Replaces multiple dbg.value records when the alloca it describes
313/// is replaced with a new value. If Offset is non-zero, a constant displacement
314/// is added to the expression (after the mandatory Deref). Offset can be
315/// negative. New dbg.value records are inserted at the locations of
316/// the instructions they replace.
317LLVM_ABI void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
318 DIBuilder &Builder, int Offset = 0);
319
320/// Salvage debug records that use \p I before the instruction is deleted.
321/// Rewrite those uses in terms of its operands where we can, and encode the
322/// instruction's effect in the record's DIExpression. Deleting the instruction
323/// replaces any remaining debug-record uses with poison.
324LLVM_ABI void salvageDebugInfo(Instruction &I);
325
326/// Salvage only the records in \p DPInsns instead of finding every debug
327/// user of \p I. Every record must be a debug user of the instruction.
328///
329/// Process records in order. For a dbg.assign, salvage a matching address
330/// before its variable location since replacing a variable-location operand
331/// can also replace the address. Stop when a checked variable location cannot
332/// be salvaged. A matching address counts as processed even if salvage leaves
333/// it unchanged. If nothing was processed, call setKillLocation() on every
334/// supplied record.
335LLVM_ABI void
338
339/// Given an instruction \p I and DIExpression \p DIExpr operating on
340/// it, append the effects of \p I to the DIExpression operand list
341/// \p Ops, or return \p nullptr if it cannot be salvaged.
342/// \p CurrentLocOps is the number of SSA values referenced by the
343/// incoming \p Ops. \return the first non-constant operand
344/// implicitly referred to by Ops. If \p I references more than one
345/// non-constant operand, any additional operands are added to
346/// \p AdditionalValues.
347///
348/// \example
349////
350/// I = add %a, i32 1
351///
352/// Return = %a
353/// Ops = llvm::dwarf::DW_OP_lit1 llvm::dwarf::DW_OP_add
354///
355/// I = add %a, %b
356///
357/// Return = %a
358/// Ops = llvm::dwarf::DW_OP_LLVM_arg0 llvm::dwarf::DW_OP_add
359/// AdditionalValues = %b
360LLVM_ABI Value *
361salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps,
362 SmallVectorImpl<uint64_t> &Ops,
363 SmallVectorImpl<Value *> &AdditionalValues);
364
365/// Point debug users of \p From to \p To or salvage them. Use this function
366/// only when replacing all uses of \p From with \p To, with a guarantee that
367/// \p From is going to be deleted.
368///
369/// Follow these rules to prevent use-before-def of \p To:
370/// . If \p To is a linked Instruction, set \p DomPoint to \p To.
371/// . If \p To is an unlinked Instruction, set \p DomPoint to the Instruction
372/// \p To will be inserted after.
373/// . If \p To is not an Instruction (e.g a Constant), the choice of
374/// \p DomPoint is arbitrary. Pick \p From for simplicity.
375///
376/// If a debug user cannot be preserved without reordering variable updates or
377/// introducing a use-before-def, it is either salvaged (\ref salvageDebugInfo)
378/// or deleted. Returns true if any debug users were updated.
379LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To,
380 Instruction &DomPoint, DominatorTree &DT);
381
382/// If a terminator in an unreachable basic block has an operand of type
383/// Instruction, transform it into poison. Return true if any operands
384/// are changed to poison. Original Values prior to being changed to poison
385/// are returned in \p PoisonedValues.
386LLVM_ABI bool
387handleUnreachableTerminator(Instruction *I,
388 SmallVectorImpl<Value *> &PoisonedValues);
389
390/// Remove all instructions from a basic block other than its terminator
391/// and any present EH pad instructions. Returns the number of instructions
392/// that have been removed.
394
395/// Insert an unreachable instruction before the specified
396/// instruction, making it and the rest of the code in the block dead.
397LLVM_ABI unsigned changeToUnreachable(Instruction *I,
398 bool PreserveLCSSA = false,
399 DomTreeUpdater *DTU = nullptr,
400 MemorySSAUpdater *MSSAU = nullptr);
401
402/// Convert the CallInst to InvokeInst with the specified unwind edge basic
403/// block. This also splits the basic block where CI is located, because
404/// InvokeInst is a terminator instruction. Returns the newly split basic
405/// block.
406LLVM_ABI BasicBlock *
407changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge,
408 DomTreeUpdater *DTU = nullptr);
409
410/// Replace 'BB's terminator with one that does not have an unwind successor
411/// block. Rewrites `invoke` to `call`, etc. Updates any PHIs in unwind
412/// successor. Returns the instruction that replaced the original terminator,
413/// which might be a call in case the original terminator was an invoke.
414///
415/// \param BB Block whose terminator will be replaced. Its terminator must
416/// have an unwind successor.
417LLVM_ABI Instruction *removeUnwindEdge(BasicBlock *BB,
418 DomTreeUpdater *DTU = nullptr);
419
420/// Remove all blocks that can not be reached from the function's entry.
421/// When \p FoldInstsToUnreachable is true, it will also convert obviously
422/// unreachable instructions into unreachable (e.g, store to null).
423///
424/// Returns true if any basic block was removed or any instruction was folded.
426 DomTreeUpdater *DTU = nullptr,
427 MemorySSAUpdater *MSSAU = nullptr,
428 bool FoldInstsToUnreachable = true);
429
430/// Combine the metadata of two instructions so that K can replace J. This
431/// specifically handles the case of CSE-like transformations. Some
432/// metadata can only be kept if K dominates J. For this to be correct,
433/// K cannot be hoisted.
434///
435/// Unknown metadata is removed.
436LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J,
437 bool DoesKMove);
438
439/// Combine metadata of two instructions, where instruction J is a memory
440/// access that has been merged into K. This will intersect alias-analysis
441/// metadata, while preserving other known metadata.
442LLVM_ABI void combineAAMetadata(Instruction *K, const Instruction *J);
443
444/// Copy the metadata from the source instruction to the destination (the
445/// replacement for the source instruction).
446LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source);
447
448/// Patch the replacement so that it is not more restrictive than the value
449/// being replaced. It assumes that the replacement does not get moved from
450/// its original position.
451LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl);
452
453// Replace each use of 'From' with 'To', if that use does not belong to basic
454// block where 'From' is defined. Returns the number of replacements made.
455LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To);
456
457/// Replace each use of 'From' with 'To' if that use is dominated by
458/// the given edge. Returns the number of replacements made.
459LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To,
460 DominatorTree &DT,
461 const BasicBlockEdge &Edge);
462/// Replace each use of 'From' with 'To' if that use is dominated by
463/// the end of the given BasicBlock. Returns the number of replacements made.
464LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To,
465 DominatorTree &DT,
466 const BasicBlock *BB);
467/// Replace each use of 'From' with 'To' if that use is dominated by the
468/// given instruction. Returns the number of replacements made.
469LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To,
470 DominatorTree &DT,
471 const Instruction *I);
472/// Replace each use of 'From' with 'To' if that use is dominated by
473/// the given edge and the callback ShouldReplace returns true. Returns the
474/// number of replacements made.
476 Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge,
477 function_ref<bool(const Use &U, const Value *To)> ShouldReplace);
478/// Replace each use of 'From' with 'To' if that use is dominated by
479/// the end of the given BasicBlock and the callback ShouldReplace returns true.
480/// Returns the number of replacements made.
482 Value *From, Value *To, DominatorTree &DT, const BasicBlock *BB,
483 function_ref<bool(const Use &U, const Value *To)> ShouldReplace);
484/// Replace each use of 'From' with 'To' if that use is dominated by
485/// the given instruction and the callback ShouldReplace returns true. Returns
486/// the number of replacements made.
488 Value *From, Value *To, DominatorTree &DT, const Instruction *I,
489 function_ref<bool(const Use &U, const Value *To)> ShouldReplace);
490
491/// Return true if this call calls a gc leaf function.
492///
493/// A leaf function is a function that does not safepoint the thread during its
494/// execution. During a call or invoke to such a function, the callers stack
495/// does not have to be made parseable.
496///
497/// Most passes can and should ignore this information, and it is only used
498/// during lowering by the GC infrastructure.
499LLVM_ABI bool callsGCLeafFunction(const CallBase *Call,
500 const TargetLibraryInfo &TLI);
501
502/// Copy a nonnull metadata node to a new load instruction.
503///
504/// This handles mapping it to range metadata if the new load is an integer
505/// load instead of a pointer load.
506LLVM_ABI void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
507 LoadInst &NewLI);
508
509/// Copy a range metadata node to a new load instruction.
510///
511/// This handles mapping it to nonnull metadata if the new load is a pointer
512/// load instead of an integer load and the range doesn't cover null.
513LLVM_ABI void copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
514 MDNode *N, LoadInst &NewLI);
515
516/// Remove the debug intrinsic instructions for the given instruction.
517LLVM_ABI void dropDebugUsers(Instruction &I);
518
519/// Hoist all of the instructions in the \p IfBlock to the dominant block
520/// \p DomBlock, by moving its instructions to the insertion point \p InsertPt.
521///
522/// The moved instructions receive the insertion point debug location values
523/// (DILocations) and their debug intrinsic instructions are removed.
524LLVM_ABI void hoistAllInstructionsInto(BasicBlock *DomBlock,
525 Instruction *InsertPt, BasicBlock *BB);
526
527/// Given a constant, create a debug information expression.
528LLVM_ABI DIExpression *getExpressionForConstant(DIBuilder &DIB,
529 const Constant &C, Type &Ty);
530
531/// Remap the operands of the debug records attached to \p Inst, and the
532/// operands of \p Inst itself if it's a debug intrinsic.
533LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst);
534
535//===----------------------------------------------------------------------===//
536// Intrinsic pattern matching
537//
538
539/// Try to match a bswap or bitreverse idiom.
540///
541/// If an idiom is matched, an intrinsic call is inserted before \c I. Any added
542/// instructions are returned in \c InsertedInsts. They will all have been added
543/// to a basic block.
544///
545/// A bitreverse idiom normally requires around 2*BW nodes to be searched (where
546/// BW is the bitwidth of the integer type). A bswap idiom requires anywhere up
547/// to BW / 4 nodes to be searched, so is significantly faster.
548///
549/// This function returns true on a successful match or false otherwise.
550LLVM_ABI bool
551recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps,
552 bool MatchBitReversals,
553 SmallVectorImpl<Instruction *> &InsertedInsts);
554
555//===----------------------------------------------------------------------===//
556// Sanitizer utilities
557//
558
559/// Given a CallInst, check if it calls a string function known to CodeGen,
560/// and mark it with NoBuiltin if so. To be used by sanitizers that intend
561/// to intercept string functions and want to avoid converting them to target
562/// specific instructions.
563LLVM_ABI void
565 const TargetLibraryInfo *TLI);
566
567//===----------------------------------------------------------------------===//
568// Transform predicates
569//
570
571/// Given an instruction, is it legal to set operand OpIdx to a non-constant
572/// value?
573LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I,
574 unsigned OpIdx);
575
576//===----------------------------------------------------------------------===//
577// Value helper functions
578//
579
580/// Invert the given true/false value, possibly reusing an existing copy.
581LLVM_ABI Value *invertCondition(Value *Condition);
582
583//===----------------------------------------------------------------------===//
584// Assorted
585//
586
587/// If we can infer one attribute from another on the declaration of a
588/// function, explicitly materialize the maximal set in the IR.
590
591//===----------------------------------------------------------------------===//
592// Helpers to track and update flags on instructions.
593//
594
596 bool HasNUW = true;
597 bool HasNSW = true;
598 bool IsDisjoint = true;
599
600#ifndef NDEBUG
601 /// Opcode of merged instructions. All instructions passed to mergeFlags must
602 /// have the same opcode.
603 std::optional<unsigned> Opcode;
604#endif
605
606 // Note: At the moment, users are responsible to manage AllKnownNonNegative
607 // and AllKnownNonZero manually. AllKnownNonNegative can be true in a case
608 // where one of the operands is negative, but one the operators is not NSW.
609 // AllKnownNonNegative should not be used independently of HasNSW
611 bool AllKnownNonZero = true;
612
613 OverflowTracking() = default;
614
615 /// Merge in the no-wrap flags from \p I.
617
618 /// Apply the no-wrap flags to \p I if applicable.
620};
621
622} // end namespace llvm
623
624#endif // LLVM_TRANSFORMS_UTILS_LOCAL_H
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:215
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
#define P(N)
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
This class represents a function call, abstracting a target machine's calling convention.
Conditional Branch instruction.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
Invoke instruction.
An instruction for reading from memory.
Metadata node.
Definition Metadata.h:1069
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
An instruction for storing to memory.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
LLVM Value Representation.
Definition Value.h:75
Value handle that is nullable, but tries to track the Value.
A nullable Value handle that is nullable.
CallInst * Call
Abstract Attribute helper functions.
Definition Attributor.h:165
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
LLVM_ABI bool foldBranchToCommonDest(CondBrInst *BI, llvm::DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, const TargetTransformInfo *TTI=nullptr, AssumptionCache *AC=nullptr, unsigned BonusInstThreshold=1)
If this basic block is ONLY a setcc and a branch, and if a predecessor branches to us and one of our ...
LLVM_ABI unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB)
Remove all instructions from a basic block other than its terminator and any present EH pad instructi...
Definition Local.cpp:2525
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:535
LLVM_ABI BasicBlock * changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge, DomTreeUpdater *DTU=nullptr)
Convert the CallInst to InvokeInst with the specified unwind edge basic block.
Definition Local.cpp:2643
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:134
LLVM_ABI bool FlattenCFG(BasicBlock *BB, AAResults *AA=nullptr)
This function is used to flatten a CFG.
LLVM_ABI unsigned replaceDominatedUsesWithIf(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge, function_ref< bool(const Use &U, const Value *To)> ShouldReplace)
Replace each use of 'From' with 'To' if that use is dominated by the given edge and the callback Shou...
Definition Local.cpp:3299
LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
Definition Local.cpp:3263
LLVM_ABI void salvageDebugInfo(const MachineRegisterInfo &MRI, MachineInstr &MI)
Assuming the instruction MI is going to be deleted, attempt to salvage debug users of MI by writing t...
Definition Utils.cpp:1675
LLVM_ABI CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
Definition Local.cpp:2619
LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
Definition Local.cpp:3136
LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
Definition Local.cpp:1721
LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst)
Remap the operands of the debug records attached to Inst, and the operands of Inst itself if it's a d...
Definition Local.cpp:3499
LLVM_ABI bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition Local.cpp:736
LLVM_ABI void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode * > &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
Definition Local.cpp:1918
LLVM_ABI bool handleUnreachableTerminator(Instruction *I, SmallVectorImpl< Value * > &PoisonedValues)
If a terminator in an unreachable basic block has an operand of type Instruction, transform it into p...
Definition Local.cpp:2508
LLVM_ABI AllocaInst * DemoteRegToStack(Instruction &X, bool VolatileLoads=false, std::optional< BasicBlock::iterator > AllocaPoint=std::nullopt)
This function takes a virtual register computed by an Instruction and replaces it with a slot in the ...
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool FoldInstsToUnreachable=true)
Remove all blocks that can not be reached from the function's entry.
Definition Local.cpp:2923
Align getKnownAlignment(Value *V, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to infer an alignment for the specified pointer.
Definition Local.h:254
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:403
LLVM_ABI AllocaInst * DemotePHIToStack(PHINode *P, std::optional< BasicBlock::iterator > AllocaPoint=std::nullopt)
This function takes a virtual register computed by a phi node and replaces it with a slot in the stac...
LLVM_ABI bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes,...
Definition Local.cpp:1168
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition Local.cpp:3804
LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition Local.cpp:1579
LLVM_ABI bool wouldInstructionBeTriviallyDeadOnUnusedPaths(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction has no side effects on any paths other than whe...
Definition Local.cpp:410
LLVM_ABI bool LowerDbgDeclare(Function &F)
Lowers dbg.declare records into appropriate set of dbg.value records.
Definition Local.cpp:1831
LLVM_ABI DIExpression * getExpressionForConstant(DIBuilder &DIB, const Constant &C, Type &Ty)
Given a constant, create a debug information expression.
Definition Local.cpp:3457
LLVM_ABI CallInst * createCallMatchingInvoke(InvokeInst *II)
Create a call that matches the invoke II in terms of arguments, attributes, debug information,...
Definition Local.cpp:2593
LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
Inserts a dbg.value record before a store to an alloca'd value that has an associated dbg....
Definition Local.cpp:1675
LLVM_ABI Instruction * removeUnwindEdge(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Replace 'BB's terminator with one that does not have an unwind successor block.
Definition Local.cpp:2885
LLVM_ABI bool wouldInstructionBeTriviallyDead(const Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used.
Definition Local.cpp:422
LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
Definition Local.cpp:3199
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, SmallPtrSetImpl< PHINode * > *KnownNonDeadPHIs=nullptr)
If the specified value is an effectively dead PHI node, due to being a def-use chain of single-use no...
Definition Local.cpp:643
LLVM_ABI void salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableRecord * > DPInsns)
Salvage only the records in DPInsns instead of finding every debug user of I.
Definition Local.cpp:2075
LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge)
Replace each use of 'From' with 'To' if that use is dominated by the given edge.
Definition Local.cpp:3278
LLVM_ABI unsigned changeToUnreachable(Instruction *I, bool PreserveLCSSA=false, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Insert an unreachable instruction before the specified instruction, making it and the rest of the cod...
Definition Local.cpp:2553
LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition Local.cpp:2454
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition Local.cpp:2314
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3127
LLVM_ABI void dropDebugUsers(Instruction &I)
Remove the debug intrinsic instructions for the given instruction.
Definition Local.cpp:3404
TargetTransformInfo TTI
LLVM_ABI void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!...
Definition Local.cpp:776
LLVM_ABI cl::opt< bool > RequireAndPreserveDomTree
This function is used to do simplification of a CFG.
LLVM_ABI bool replaceDbgUsesWithUndef(Instruction *I)
Replace all the uses of an SSA value in @llvm.dbg intrinsics with undef.
Definition Local.cpp:612
LLVM_ABI void hoistAllInstructionsInto(BasicBlock *DomBlock, Instruction *InsertPt, BasicBlock *BB)
Hoist all of the instructions in the IfBlock to the dominant block DomBlock, by moving its instructio...
Definition Local.cpp:3411
LLVM_ABI void copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a range metadata node to a new load instruction.
Definition Local.cpp:3380
LLVM_ABI void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a nonnull metadata node to a new load instruction.
Definition Local.cpp:3355
LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I, unsigned OpIdx)
Given an instruction, is it legal to set operand OpIdx to a non-constant value?
Definition Local.cpp:3918
LLVM_ABI void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress, DIBuilder &Builder, int Offset=0)
Replaces multiple dbg.value records when the alloca it describes is replaced with a new value.
Definition Local.cpp:2021
LLVM_ABI Align tryEnforceAlignment(Value *V, Align PrefAlign, const DataLayout &DL)
If the specified pointer points to an object that we control, try to modify the object's alignment to...
Definition Local.cpp:1530
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructionsPermissive(SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow instructions that are not...
Definition Local.cpp:550
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI, DomTreeUpdater *DTU=nullptr, const SimplifyCFGOptions &Options={}, ArrayRef< WeakVH > LoopHeaders={})
LLVM_ABI void combineAAMetadata(Instruction *K, const Instruction *J)
Combine metadata of two instructions, where instruction J is a memory access that has been merged int...
Definition Local.cpp:3132
LLVM_ABI bool inferAttributesFromOthers(Function &F)
If we can infer one attribute from another on the declaration of a function, explicitly materialize t...
Definition Local.cpp:4041
LLVM_ABI Value * invertCondition(Value *Condition)
Invert the given true/false value, possibly reusing an existing copy.
Definition Local.cpp:4007
LLVM_ABI void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI, const TargetLibraryInfo *TLI)
Given a CallInst, check if it calls a string function known to CodeGen, and mark it with NoBuiltin if...
Definition Local.cpp:3908
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
Definition Local.cpp:1522
LLVM_ABI bool callsGCLeafFunction(const CallBase *Call, const TargetLibraryInfo &TLI)
Return true if this call calls a gc leaf function.
Definition Local.cpp:3326
LLVM_ABI bool replaceDbgDeclare(Value *Address, Value *NewAddress, DIBuilder &Builder, uint8_t DIExprFlags, int Offset)
Replaces dbg.declare record when the address it describes is replaced with a new value.
Definition Local.cpp:1981
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:106
std::optional< unsigned > Opcode
Opcode of merged instructions.
Definition Local.h:603
LLVM_ABI void mergeFlags(Instruction &I)
Merge in the no-wrap flags from I.
Definition Local.cpp:4071
LLVM_ABI void applyFlags(Instruction &I)
Apply the no-wrap flags to I if applicable.
Definition Local.cpp:4087