LLVM 22.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 T> class SmallVectorImpl;
32class AAResults;
33class AllocaInst;
34class AssumptionCache;
35class BasicBlock;
36class BranchInst;
37class CallBase;
38class CallInst;
39class DIBuilder;
40class DomTreeUpdater;
41class Function;
42class Instruction;
43class InvokeInst;
44class LoadInst;
45class MDNode;
46class MemorySSAUpdater;
47class PHINode;
48class StoreInst;
49class TargetLibraryInfo;
50class TargetTransformInfo;
51
52//===----------------------------------------------------------------------===//
53// Local constant propagation.
54//
55
56/// If a terminator instruction is predicated on a constant value, convert it
57/// into an unconditional branch to the constant destination.
58/// This is a nontrivial operation because the successors of this basic block
59/// must have their PHI nodes updated.
60/// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
61/// conditions and indirectbr addresses this might make dead if
62/// DeleteDeadConditions is true.
63LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB,
64 bool DeleteDeadConditions = false,
65 const TargetLibraryInfo *TLI = nullptr,
66 DomTreeUpdater *DTU = nullptr);
67
68//===----------------------------------------------------------------------===//
69// Local dead code elimination.
70//
71
72/// Return true if the result produced by the instruction is not used, and the
73/// instruction will return. Certain side-effecting instructions are also
74/// considered dead if there are no uses of the instruction.
75LLVM_ABI bool
76isInstructionTriviallyDead(Instruction *I,
77 const TargetLibraryInfo *TLI = nullptr);
78
79/// Return true if the result produced by the instruction would have no side
80/// effects if it was not used. This is equivalent to checking whether
81/// isInstructionTriviallyDead would be true if the use count was 0.
82LLVM_ABI bool
83wouldInstructionBeTriviallyDead(const Instruction *I,
84 const TargetLibraryInfo *TLI = nullptr);
85
86/// Return true if the result produced by the instruction has no side effects on
87/// any paths other than where it is used. This is less conservative than
88/// wouldInstructionBeTriviallyDead which is based on the assumption
89/// that the use count will be 0. An example usage of this API is for
90/// identifying instructions that can be sunk down to use(s).
92 Instruction *I, const TargetLibraryInfo *TLI = nullptr);
93
94/// If the specified value is a trivially dead instruction, delete it.
95/// If that makes any of its operands trivially dead, delete them too,
96/// recursively. Return true if any instructions were deleted.
98 Value *V, const TargetLibraryInfo *TLI = nullptr,
99 MemorySSAUpdater *MSSAU = nullptr,
100 std::function<void(Value *)> AboutToDeleteCallback =
101 std::function<void(Value *)>());
102
103/// Delete all of the instructions in `DeadInsts`, and all other instructions
104/// that deleting these in turn causes to be trivially dead.
105///
106/// The initial instructions in the provided vector must all have empty use
107/// lists and satisfy `isInstructionTriviallyDead`.
108///
109/// `DeadInsts` will be used as scratch storage for this routine and will be
110/// empty afterward.
112 SmallVectorImpl<WeakTrackingVH> &DeadInsts,
113 const TargetLibraryInfo *TLI = nullptr, MemorySSAUpdater *MSSAU = nullptr,
114 std::function<void(Value *)> AboutToDeleteCallback =
115 std::function<void(Value *)>());
116
117/// Same functionality as RecursivelyDeleteTriviallyDeadInstructions, but allow
118/// instructions that are not trivially dead. These will be ignored.
119/// Returns true if any changes were made, i.e. any instructions trivially dead
120/// were found and deleted.
122 SmallVectorImpl<WeakTrackingVH> &DeadInsts,
123 const TargetLibraryInfo *TLI = nullptr, MemorySSAUpdater *MSSAU = nullptr,
124 std::function<void(Value *)> AboutToDeleteCallback =
125 std::function<void(Value *)>());
126
127/// If the specified value is an effectively dead PHI node, due to being a
128/// def-use chain of single-use nodes that either forms a cycle or is terminated
129/// by a trivially dead instruction, delete it. If that makes any of its
130/// operands trivially dead, delete them too, recursively. Return true if a
131/// change was made.
132LLVM_ABI bool
134 const TargetLibraryInfo *TLI = nullptr,
135 MemorySSAUpdater *MSSAU = nullptr);
136
137/// Scan the specified basic block and try to simplify any instructions in it
138/// and recursively delete dead instructions.
139///
140/// This returns true if it changed the code, note that it can delete
141/// instructions in other blocks as well in this block.
142LLVM_ABI bool
143SimplifyInstructionsInBlock(BasicBlock *BB,
144 const TargetLibraryInfo *TLI = nullptr);
145
146/// Replace all the uses of an SSA value in @llvm.dbg intrinsics with
147/// undef. This is useful for signaling that a variable, e.g. has been
148/// found dead and hence it's unavailable at a given program point.
149/// Returns true if the dbg values have been changed.
150LLVM_ABI bool replaceDbgUsesWithUndef(Instruction *I);
151
152//===----------------------------------------------------------------------===//
153// Control Flow Graph Restructuring.
154//
155
156/// BB is a block with one predecessor and its predecessor is known to have one
157/// successor (BB!). Eliminate the edge between them, moving the instructions in
158/// the predecessor into BB. This deletes the predecessor block.
159LLVM_ABI void MergeBasicBlockIntoOnlyPred(BasicBlock *BB,
160 DomTreeUpdater *DTU = nullptr);
161
162/// BB is known to contain an unconditional branch, and contains no instructions
163/// other than PHI nodes, potential debug intrinsics and the branch. If
164/// possible, eliminate BB by rewriting all the predecessors to branch to the
165/// successor block and return true. If we can't transform, return false.
166LLVM_ABI bool
168 DomTreeUpdater *DTU = nullptr);
169
170/// Check for and eliminate duplicate PHI nodes in this block. This doesn't try
171/// to be clever about PHI nodes which differ only in the order of the incoming
172/// values, but instcombine orders them so it usually won't matter.
173///
174/// This overload removes the duplicate PHI nodes directly.
175LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB);
176
177/// Check for and eliminate duplicate PHI nodes in this block. This doesn't try
178/// to be clever about PHI nodes which differ only in the order of the incoming
179/// values, but instcombine orders them so it usually won't matter.
180///
181/// This overload collects the PHI nodes to be removed into the ToRemove set.
182LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB,
183 SmallPtrSetImpl<PHINode *> &ToRemove);
184
185/// This function is used to do simplification of a CFG. For example, it
186/// adjusts branches to branches to eliminate the extra hop, it eliminates
187/// unreachable basic blocks, and does other peephole optimization of the CFG.
188/// It returns true if a modification was made, possibly deleting the basic
189/// block that was pointed to. LoopHeaders is an optional input parameter
190/// providing the set of loop headers that SimplifyCFG should not eliminate.
192LLVM_ABI bool simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
193 DomTreeUpdater *DTU = nullptr,
194 const SimplifyCFGOptions &Options = {},
195 ArrayRef<WeakVH> LoopHeaders = {});
196
197/// This function is used to flatten a CFG. For example, it uses parallel-and
198/// and parallel-or mode to collapse if-conditions and merge if-regions with
199/// identical statements.
200LLVM_ABI bool FlattenCFG(BasicBlock *BB, AAResults *AA = nullptr);
201
202/// If this basic block is ONLY a setcc and a branch, and if a predecessor
203/// branches to us and one of our successors, fold the setcc into the
204/// predecessor and use logical operations to pick the right destination.
205LLVM_ABI bool foldBranchToCommonDest(BranchInst *BI,
206 llvm::DomTreeUpdater *DTU = nullptr,
207 MemorySSAUpdater *MSSAU = nullptr,
208 const TargetTransformInfo *TTI = nullptr,
209 unsigned BonusInstThreshold = 1);
210
211/// This function takes a virtual register computed by an Instruction and
212/// replaces it with a slot in the stack frame, allocated via alloca.
213/// This allows the CFG to be changed around without fear of invalidating the
214/// SSA information for the value. It returns the pointer to the alloca inserted
215/// to create a stack slot for X.
216LLVM_ABI AllocaInst *DemoteRegToStack(
217 Instruction &X, bool VolatileLoads = false,
218 std::optional<BasicBlock::iterator> AllocaPoint = std::nullopt);
219
220/// This function takes a virtual register computed by a phi node and replaces
221/// it with a slot in the stack frame, allocated via alloca. The phi node is
222/// deleted and it returns the pointer to the alloca inserted.
223LLVM_ABI AllocaInst *DemotePHIToStack(
224 PHINode *P, std::optional<BasicBlock::iterator> AllocaPoint = std::nullopt);
225
226/// If the specified pointer points to an object that we control, try to modify
227/// the object's alignment to PrefAlign. Returns a minimum known alignment of
228/// the value after the operation, which may be lower than PrefAlign.
229///
230/// Increating value alignment isn't often possible though. If alignment is
231/// important, a more reliable approach is to simply align all global variables
232/// and allocation instructions to their preferred alignment from the beginning.
233LLVM_ABI Align tryEnforceAlignment(Value *V, Align PrefAlign,
234 const DataLayout &DL);
235
236/// Try to ensure that the alignment of \p V is at least \p PrefAlign bytes. If
237/// the owning object can be modified and has an alignment less than \p
238/// PrefAlign, it will be increased and \p PrefAlign returned. If the alignment
239/// cannot be increased, the known alignment of the value is returned.
240///
241/// It is not always possible to modify the alignment of the underlying object,
242/// so if alignment is important, a more reliable approach is to simply align
243/// all global variables and allocation instructions to their preferred
244/// alignment from the beginning.
245LLVM_ABI Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign,
246 const DataLayout &DL,
247 const Instruction *CxtI = nullptr,
248 AssumptionCache *AC = nullptr,
249 const DominatorTree *DT = nullptr);
250
251/// Try to infer an alignment for the specified pointer.
253 const Instruction *CxtI = nullptr,
254 AssumptionCache *AC = nullptr,
255 const DominatorTree *DT = nullptr) {
256 return getOrEnforceKnownAlignment(V, MaybeAlign(), DL, CxtI, AC, DT);
257}
258
259/// Create a call that matches the invoke \p II in terms of arguments,
260/// attributes, debug information, etc. The call is not placed in a block and it
261/// will not have a name. The invoke instruction is not removed, nor are the
262/// uses replaced by the new call.
263LLVM_ABI CallInst *createCallMatchingInvoke(InvokeInst *II);
264
265/// This function converts the specified invoke into a normal call.
266LLVM_ABI CallInst *changeToCall(InvokeInst *II, DomTreeUpdater *DTU = nullptr);
267
268///===---------------------------------------------------------------------===//
269/// Dbg Intrinsic utilities
270///
271
272/// Creates and inserts a dbg_value record intrinsic before a store
273/// that has an associated llvm.dbg.value intrinsic.
274LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI,
275 DIBuilder &Builder);
276
277/// Inserts a dbg.value record before a store to an alloca'd value
278/// that has an associated dbg.declare record.
279LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
280 StoreInst *SI,
281 DIBuilder &Builder);
282
283/// Inserts a dbg.value record before a load of an alloca'd value
284/// that has an associated dbg.declare record.
285LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
286 LoadInst *LI, DIBuilder &Builder);
287
288/// Inserts a dbg.value record after a phi that has an associated
289/// llvm.dbg.declare record.
290LLVM_ABI void ConvertDebugDeclareToDebugValue(DbgVariableRecord *DVR,
291 PHINode *LI, DIBuilder &Builder);
292
293/// Lowers dbg.declare records into appropriate set of dbg.value records.
294LLVM_ABI bool LowerDbgDeclare(Function &F);
295
296/// Propagate dbg.value intrinsics through the newly inserted PHIs.
297LLVM_ABI void
298insertDebugValuesForPHIs(BasicBlock *BB,
299 SmallVectorImpl<PHINode *> &InsertedPHIs);
300
301/// Replaces dbg.declare record when the address it
302/// describes is replaced with a new value. If Deref is true, an
303/// additional DW_OP_deref is prepended to the expression. If Offset
304/// is non-zero, a constant displacement is added to the expression
305/// (between the optional Deref operations). Offset can be negative.
306LLVM_ABI bool replaceDbgDeclare(Value *Address, Value *NewAddress,
307 DIBuilder &Builder, uint8_t DIExprFlags,
308 int Offset);
309
310/// Replaces multiple dbg.value records when the alloca it describes
311/// is replaced with a new value. If Offset is non-zero, a constant displacement
312/// is added to the expression (after the mandatory Deref). Offset can be
313/// negative. New dbg.value records are inserted at the locations of
314/// the instructions they replace.
315LLVM_ABI void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
316 DIBuilder &Builder, int Offset = 0);
317
318/// Assuming the instruction \p I is going to be deleted, attempt to salvage
319/// debug users of \p I by writing the effect of \p I in a DIExpression. If it
320/// cannot be salvaged changes its debug uses to undef.
321LLVM_ABI void salvageDebugInfo(Instruction &I);
322
323/// Implementation of salvageDebugInfo, applying only to instructions in
324/// \p Insns, rather than all debug users from findDbgUsers( \p I).
325/// Mark undef if salvaging cannot be completed.
326LLVM_ABI void
328 ArrayRef<DbgVariableRecord *> DPInsns);
329
330/// Given an instruction \p I and DIExpression \p DIExpr operating on
331/// it, append the effects of \p I to the DIExpression operand list
332/// \p Ops, or return \p nullptr if it cannot be salvaged.
333/// \p CurrentLocOps is the number of SSA values referenced by the
334/// incoming \p Ops. \return the first non-constant operand
335/// implicitly referred to by Ops. If \p I references more than one
336/// non-constant operand, any additional operands are added to
337/// \p AdditionalValues.
338///
339/// \example
340////
341/// I = add %a, i32 1
342///
343/// Return = %a
344/// Ops = llvm::dwarf::DW_OP_lit1 llvm::dwarf::DW_OP_add
345///
346/// I = add %a, %b
347///
348/// Return = %a
349/// Ops = llvm::dwarf::DW_OP_LLVM_arg0 llvm::dwarf::DW_OP_add
350/// AdditionalValues = %b
351LLVM_ABI Value *
352salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps,
353 SmallVectorImpl<uint64_t> &Ops,
354 SmallVectorImpl<Value *> &AdditionalValues);
355
356/// Point debug users of \p From to \p To or salvage them. Use this function
357/// only when replacing all uses of \p From with \p To, with a guarantee that
358/// \p From is going to be deleted.
359///
360/// Follow these rules to prevent use-before-def of \p To:
361/// . If \p To is a linked Instruction, set \p DomPoint to \p To.
362/// . If \p To is an unlinked Instruction, set \p DomPoint to the Instruction
363/// \p To will be inserted after.
364/// . If \p To is not an Instruction (e.g a Constant), the choice of
365/// \p DomPoint is arbitrary. Pick \p From for simplicity.
366///
367/// If a debug user cannot be preserved without reordering variable updates or
368/// introducing a use-before-def, it is either salvaged (\ref salvageDebugInfo)
369/// or deleted. Returns true if any debug users were updated.
370LLVM_ABI bool replaceAllDbgUsesWith(Instruction &From, Value &To,
371 Instruction &DomPoint, DominatorTree &DT);
372
373/// If a terminator in an unreachable basic block has an operand of type
374/// Instruction, transform it into poison. Return true if any operands
375/// are changed to poison. Original Values prior to being changed to poison
376/// are returned in \p PoisonedValues.
377LLVM_ABI bool
378handleUnreachableTerminator(Instruction *I,
379 SmallVectorImpl<Value *> &PoisonedValues);
380
381/// Remove all instructions from a basic block other than its terminator
382/// and any present EH pad instructions. Returns the number of instructions
383/// that have been removed.
385
386/// Insert an unreachable instruction before the specified
387/// instruction, making it and the rest of the code in the block dead.
388LLVM_ABI unsigned changeToUnreachable(Instruction *I,
389 bool PreserveLCSSA = false,
390 DomTreeUpdater *DTU = nullptr,
391 MemorySSAUpdater *MSSAU = nullptr);
392
393/// Convert the CallInst to InvokeInst with the specified unwind edge basic
394/// block. This also splits the basic block where CI is located, because
395/// InvokeInst is a terminator instruction. Returns the newly split basic
396/// block.
397LLVM_ABI BasicBlock *
398changeToInvokeAndSplitBasicBlock(CallInst *CI, BasicBlock *UnwindEdge,
399 DomTreeUpdater *DTU = nullptr);
400
401/// Replace 'BB's terminator with one that does not have an unwind successor
402/// block. Rewrites `invoke` to `call`, etc. Updates any PHIs in unwind
403/// successor. Returns the instruction that replaced the original terminator,
404/// which might be a call in case the original terminator was an invoke.
405///
406/// \param BB Block whose terminator will be replaced. Its terminator must
407/// have an unwind successor.
408LLVM_ABI Instruction *removeUnwindEdge(BasicBlock *BB,
409 DomTreeUpdater *DTU = nullptr);
410
411/// Remove all blocks that can not be reached from the function's entry.
412///
413/// Returns true if any basic block was removed.
414LLVM_ABI bool removeUnreachableBlocks(Function &F,
415 DomTreeUpdater *DTU = nullptr,
416 MemorySSAUpdater *MSSAU = nullptr);
417
418/// Combine the metadata of two instructions so that K can replace J. This
419/// specifically handles the case of CSE-like transformations. Some
420/// metadata can only be kept if K dominates J. For this to be correct,
421/// K cannot be hoisted.
422///
423/// Unknown metadata is removed.
424LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J,
425 bool DoesKMove);
426
427/// Combine metadata of two instructions, where instruction J is a memory
428/// access that has been merged into K. This will intersect alias-analysis
429/// metadata, while preserving other known metadata.
430LLVM_ABI void combineAAMetadata(Instruction *K, const Instruction *J);
431
432/// Copy the metadata from the source instruction to the destination (the
433/// replacement for the source instruction).
434LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source);
435
436/// Patch the replacement so that it is not more restrictive than the value
437/// being replaced. It assumes that the replacement does not get moved from
438/// its original position.
439LLVM_ABI void patchReplacementInstruction(Instruction *I, Value *Repl);
440
441// Replace each use of 'From' with 'To', if that use does not belong to basic
442// block where 'From' is defined. Returns the number of replacements made.
443LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To);
444
445/// Replace each use of 'From' with 'To' if that use is dominated by
446/// the given edge. Returns the number of replacements made.
447LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To,
448 DominatorTree &DT,
449 const BasicBlockEdge &Edge);
450/// Replace each use of 'From' with 'To' if that use is dominated by
451/// the end of the given BasicBlock. Returns the number of replacements made.
452LLVM_ABI unsigned replaceDominatedUsesWith(Value *From, Value *To,
453 DominatorTree &DT,
454 const BasicBlock *BB);
455/// Replace each use of 'From' with 'To' if that use is dominated by
456/// the given edge and the callback ShouldReplace returns true. Returns the
457/// number of replacements made.
459 Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge,
460 function_ref<bool(const Use &U, const Value *To)> ShouldReplace);
461/// Replace each use of 'From' with 'To' if that use is dominated by
462/// the end of the given BasicBlock and the callback ShouldReplace returns true.
463/// Returns the number of replacements made.
465 Value *From, Value *To, DominatorTree &DT, const BasicBlock *BB,
466 function_ref<bool(const Use &U, const Value *To)> ShouldReplace);
467
468/// Return true if this call calls a gc leaf function.
469///
470/// A leaf function is a function that does not safepoint the thread during its
471/// execution. During a call or invoke to such a function, the callers stack
472/// does not have to be made parseable.
473///
474/// Most passes can and should ignore this information, and it is only used
475/// during lowering by the GC infrastructure.
476LLVM_ABI bool callsGCLeafFunction(const CallBase *Call,
477 const TargetLibraryInfo &TLI);
478
479/// Copy a nonnull metadata node to a new load instruction.
480///
481/// This handles mapping it to range metadata if the new load is an integer
482/// load instead of a pointer load.
483LLVM_ABI void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N,
484 LoadInst &NewLI);
485
486/// Copy a range metadata node to a new load instruction.
487///
488/// This handles mapping it to nonnull metadata if the new load is a pointer
489/// load instead of an integer load and the range doesn't cover null.
490LLVM_ABI void copyRangeMetadata(const DataLayout &DL, const LoadInst &OldLI,
491 MDNode *N, LoadInst &NewLI);
492
493/// Remove the debug intrinsic instructions for the given instruction.
494LLVM_ABI void dropDebugUsers(Instruction &I);
495
496/// Hoist all of the instructions in the \p IfBlock to the dominant block
497/// \p DomBlock, by moving its instructions to the insertion point \p InsertPt.
498///
499/// The moved instructions receive the insertion point debug location values
500/// (DILocations) and their debug intrinsic instructions are removed.
501LLVM_ABI void hoistAllInstructionsInto(BasicBlock *DomBlock,
502 Instruction *InsertPt, BasicBlock *BB);
503
504/// Given a constant, create a debug information expression.
505LLVM_ABI DIExpression *getExpressionForConstant(DIBuilder &DIB,
506 const Constant &C, Type &Ty);
507
508/// Remap the operands of the debug records attached to \p Inst, and the
509/// operands of \p Inst itself if it's a debug intrinsic.
510LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst);
511
512//===----------------------------------------------------------------------===//
513// Intrinsic pattern matching
514//
515
516/// Try to match a bswap or bitreverse idiom.
517///
518/// If an idiom is matched, an intrinsic call is inserted before \c I. Any added
519/// instructions are returned in \c InsertedInsts. They will all have been added
520/// to a basic block.
521///
522/// A bitreverse idiom normally requires around 2*BW nodes to be searched (where
523/// BW is the bitwidth of the integer type). A bswap idiom requires anywhere up
524/// to BW / 4 nodes to be searched, so is significantly faster.
525///
526/// This function returns true on a successful match or false otherwise.
527LLVM_ABI bool
528recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps,
529 bool MatchBitReversals,
530 SmallVectorImpl<Instruction *> &InsertedInsts);
531
532//===----------------------------------------------------------------------===//
533// Sanitizer utilities
534//
535
536/// Given a CallInst, check if it calls a string function known to CodeGen,
537/// and mark it with NoBuiltin if so. To be used by sanitizers that intend
538/// to intercept string functions and want to avoid converting them to target
539/// specific instructions.
540LLVM_ABI void
542 const TargetLibraryInfo *TLI);
543
544//===----------------------------------------------------------------------===//
545// Transform predicates
546//
547
548/// Given an instruction, is it legal to set operand OpIdx to a non-constant
549/// value?
550LLVM_ABI bool canReplaceOperandWithVariable(const Instruction *I,
551 unsigned OpIdx);
552
553//===----------------------------------------------------------------------===//
554// Value helper functions
555//
556
557/// Invert the given true/false value, possibly reusing an existing copy.
558LLVM_ABI Value *invertCondition(Value *Condition);
559
560//===----------------------------------------------------------------------===//
561// Assorted
562//
563
564/// If we can infer one attribute from another on the declaration of a
565/// function, explicitly materialize the maximal set in the IR.
566LLVM_ABI bool inferAttributesFromOthers(Function &F);
567
568//===----------------------------------------------------------------------===//
569// Helpers to track and update flags on instructions.
570//
571
573 bool HasNUW = true;
574 bool HasNSW = true;
575 bool IsDisjoint = true;
576
577#ifndef NDEBUG
578 /// Opcode of merged instructions. All instructions passed to mergeFlags must
579 /// have the same opcode.
580 std::optional<unsigned> Opcode;
581#endif
582
583 // Note: At the moment, users are responsible to manage AllKnownNonNegative
584 // and AllKnownNonZero manually. AllKnownNonNegative can be true in a case
585 // where one of the operands is negative, but one the operators is not NSW.
586 // AllKnownNonNegative should not be used independently of HasNSW
588 bool AllKnownNonZero = true;
589
590 OverflowTracking() = default;
591
592 /// Merge in the no-wrap flags from \p I.
594
595 /// Apply the no-wrap flags to \p I if applicable.
597};
598
599} // end namespace llvm
600
601#endif // LLVM_TRANSFORMS_UTILS_LOCAL_H
ReachingDefAnalysis InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
BlockVerifier::State From
RelocType Type
Definition: COFFYAML.cpp:410
#define LLVM_ABI
Definition: Compiler.h:213
uint64_t Align
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
static LVOptions Options
Definition: LVOptions.cpp:25
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
MachineInstr unsigned OpIdx
uint64_t IntrinsicInst * II
#define P(N)
StandardInstrumentations SI(Mod->getContext(), Debug, VerifyEach)
A cache of @llvm.assume calls within a function.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:165
LLVM Value Representation.
Definition: Value.h:75
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition: ISDOpcodes.h:81
template class LLVM_TEMPLATE_ABI opt< bool >
Definition: CommandLine.cpp:79
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:477
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:2485
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:533
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:2603
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.
Definition: FlattenCFG.cpp:533
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:3236
LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
Definition: Local.cpp:3207
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:1723
LLVM_ABI CallInst * changeToCall(InvokeInst *II, DomTreeUpdater *DTU=nullptr)
This function converts the specified invoke into a normal call.
Definition: Local.cpp:2579
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:3090
LLVM_ABI void InsertDebugValueAtStoreLoc(DbgVariableRecord *DVR, StoreInst *SI, DIBuilder &Builder)
===------------------------------------------------------------------—===// Dbg Intrinsic utilities
Definition: Local.cpp:1708
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:3420
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:721
LLVM_ABI void insertDebugValuesForPHIs(BasicBlock *BB, SmallVectorImpl< PHINode * > &InsertedPHIs)
Propagate dbg.value intrinsics through the newly inserted PHIs.
Definition: Local.cpp:1879
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:2468
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 ...
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:252
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:402
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:1140
LLVM_ABI bool recognizeBSwapOrBitReverseIdiom(Instruction *I, bool MatchBSwaps, bool MatchBitReversals, SmallVectorImpl< Instruction * > &InsertedInsts)
Try to match a bswap or bitreverse idiom.
Definition: Local.cpp:3725
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:1566
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:409
LLVM_ABI bool LowerDbgDeclare(Function &F)
Lowers dbg.declare records into appropriate set of dbg.value records.
Definition: Local.cpp:1795
LLVM_ABI DIExpression * getExpressionForConstant(DIBuilder &DIB, const Constant &C, Type &Ty)
Given a constant, create a debug information expression.
Definition: Local.cpp:3382
LLVM_ABI CallInst * createCallMatchingInvoke(InvokeInst *II)
Create a call that matches the invoke II in terms of arguments, attributes, debug information,...
Definition: Local.cpp:2553
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:1662
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:2845
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:421
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:3143
LLVM_ABI void salvageDebugInfoForDbgValues(Instruction &I, ArrayRef< DbgVariableRecord * > DPInsns)
Implementation of salvageDebugInfo, applying only to instructions in Insns, rather than all debug use...
Definition: Local.cpp:2037
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:3222
LLVM_ABI cl::opt< bool > RequireAndPreserveDomTree
This function is used to do simplification of a CFG.
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:2513
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:2414
LLVM_ABI Value * salvageDebugInfoImpl(Instruction &I, uint64_t CurrentLocOps, SmallVectorImpl< uint64_t > &Ops, SmallVectorImpl< Value * > &AdditionalValues)
Definition: Local.cpp:2274
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:3081
LLVM_ABI void dropDebugUsers(Instruction &I)
Remove the debug intrinsic instructions for the given instruction.
Definition: Local.cpp:3332
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:761
LLVM_ABI bool replaceDbgUsesWithUndef(Instruction *I)
Replace all the uses of an SSA value in @llvm.dbg intrinsics with undef.
Definition: Local.cpp:610
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:3339
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:3308
LLVM_ABI void copyNonnullMetadata(const LoadInst &OldLI, MDNode *N, LoadInst &NewLI)
Copy a nonnull metadata node to a new load instruction.
Definition: Local.cpp:3283
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:3839
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:1982
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:1517
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:548
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:3086
LLVM_ABI bool RecursivelyDeleteDeadPHINode(PHINode *PN, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=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:641
LLVM_ABI bool foldBranchToCommonDest(BranchInst *BI, llvm::DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr, const TargetTransformInfo *TTI=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 bool inferAttributesFromOthers(Function &F)
If we can infer one attribute from another on the declaration of a function, explicitly materialize t...
Definition: Local.cpp:3957
LLVM_ABI Value * invertCondition(Value *Condition)
Invert the given true/false value, possibly reusing an existing copy.
Definition: Local.cpp:3923
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:3829
LLVM_ABI bool removeUnreachableBlocks(Function &F, DomTreeUpdater *DTU=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Remove all blocks that can not be reached from the function's entry.
Definition: Local.cpp:2883
LLVM_ABI bool EliminateDuplicatePHINodes(BasicBlock *BB)
Check for and eliminate duplicate PHI nodes in this block.
Definition: Local.cpp:1509
LLVM_ABI bool callsGCLeafFunction(const CallBase *Call, const TargetLibraryInfo &TLI)
Return true if this call calls a gc leaf function.
Definition: Local.cpp:3254
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:1942
#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:117
bool AllKnownNonNegative
Definition: Local.h:587
std::optional< unsigned > Opcode
Opcode of merged instructions.
Definition: Local.h:580
LLVM_ABI void mergeFlags(Instruction &I)
Merge in the no-wrap flags from I.
Definition: Local.cpp:3987
LLVM_ABI void applyFlags(Instruction &I)
Apply the no-wrap flags to I if applicable.
Definition: Local.cpp:4003