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