1 //===-- Local.h - Functions to perform local transformations ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform various local transformations to the
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_TRANSFORMS_UTILS_LOCAL_H
16 #define LLVM_TRANSFORMS_UTILS_LOCAL_H
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/Dominators.h"
21 #include "llvm/IR/GetElementPtrTypeIterator.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/ADT/SmallPtrSet.h"
41 class AssumptionCache;
44 class TargetLibraryInfo;
45 class TargetTransformInfo;
50 template<typename T> class SmallVectorImpl;
52 typedef SmallVector<DbgValueInst *, 1> DbgValueList;
54 //===----------------------------------------------------------------------===//
55 // Local constant propagation.
58 /// If a terminator instruction is predicated on a constant value, convert it
59 /// into an unconditional branch to the constant destination.
60 /// This is a nontrivial operation because the successors of this basic block
61 /// must have their PHI nodes updated.
62 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
63 /// conditions and indirectbr addresses this might make dead if
64 /// DeleteDeadConditions is true.
65 bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions = false,
66 const TargetLibraryInfo *TLI = nullptr);
68 //===----------------------------------------------------------------------===//
69 // Local dead code elimination.
72 /// Return true if the result produced by the instruction is not used, and the
73 /// instruction has no side effects.
74 bool isInstructionTriviallyDead(Instruction *I,
75 const TargetLibraryInfo *TLI = nullptr);
77 /// If the specified value is a trivially dead instruction, delete it.
78 /// If that makes any of its operands trivially dead, delete them too,
79 /// recursively. Return true if any instructions were deleted.
80 bool RecursivelyDeleteTriviallyDeadInstructions(Value *V,
81 const TargetLibraryInfo *TLI = nullptr);
83 /// If the specified value is an effectively dead PHI node, due to being a
84 /// def-use chain of single-use nodes that either forms a cycle or is terminated
85 /// by a trivially dead instruction, delete it. If that makes any of its
86 /// operands trivially dead, delete them too, recursively. Return true if a
88 bool RecursivelyDeleteDeadPHINode(PHINode *PN,
89 const TargetLibraryInfo *TLI = nullptr);
91 /// Scan the specified basic block and try to simplify any instructions in it
92 /// and recursively delete dead instructions.
94 /// This returns true if it changed the code, note that it can delete
95 /// instructions in other blocks as well in this block.
96 bool SimplifyInstructionsInBlock(BasicBlock *BB,
97 const TargetLibraryInfo *TLI = nullptr);
99 //===----------------------------------------------------------------------===//
100 // Control Flow Graph Restructuring.
103 /// Like BasicBlock::removePredecessor, this method is called when we're about
104 /// to delete Pred as a predecessor of BB. If BB contains any PHI nodes, this
105 /// drops the entries in the PHI nodes for Pred.
107 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
108 /// nodes that collapse into identity values. For example, if we have:
109 /// x = phi(1, 0, 0, 0)
112 /// .. and delete the predecessor corresponding to the '1', this will attempt to
113 /// recursively fold the 'and' to 0.
114 void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred);
116 /// BB is a block with one predecessor and its predecessor is known to have one
117 /// successor (BB!). Eliminate the edge between them, moving the instructions in
118 /// the predecessor into BB. This deletes the predecessor block.
119 void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DominatorTree *DT = nullptr);
121 /// BB is known to contain an unconditional branch, and contains no instructions
122 /// other than PHI nodes, potential debug intrinsics and the branch. If
123 /// possible, eliminate BB by rewriting all the predecessors to branch to the
124 /// successor block and return true. If we can't transform, return false.
125 bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB);
127 /// Check for and eliminate duplicate PHI nodes in this block. This doesn't try
128 /// to be clever about PHI nodes which differ only in the order of the incoming
129 /// values, but instcombine orders them so it usually won't matter.
130 bool EliminateDuplicatePHINodes(BasicBlock *BB);
132 /// This function is used to do simplification of a CFG. For
133 /// example, it adjusts branches to branches to eliminate the extra hop, it
134 /// eliminates unreachable basic blocks, and does other "peephole" optimization
135 /// of the CFG. It returns true if a modification was made, possibly deleting
136 /// the basic block that was pointed to. LoopHeaders is an optional input
137 /// parameter, providing the set of loop header that SimplifyCFG should not
139 bool SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
140 unsigned BonusInstThreshold, AssumptionCache *AC = nullptr,
141 SmallPtrSetImpl<BasicBlock *> *LoopHeaders = nullptr);
143 /// This function is used to flatten a CFG. For example, it uses parallel-and
144 /// and parallel-or mode to collapse if-conditions and merge if-regions with
145 /// identical statements.
146 bool FlattenCFG(BasicBlock *BB, AliasAnalysis *AA = nullptr);
148 /// If this basic block is ONLY a setcc and a branch, and if a predecessor
149 /// branches to us and one of our successors, fold the setcc into the
150 /// predecessor and use logical operations to pick the right destination.
151 bool FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold = 1);
153 /// This function takes a virtual register computed by an Instruction and
154 /// replaces it with a slot in the stack frame, allocated via alloca.
155 /// This allows the CFG to be changed around without fear of invalidating the
156 /// SSA information for the value. It returns the pointer to the alloca inserted
157 /// to create a stack slot for X.
158 AllocaInst *DemoteRegToStack(Instruction &X,
159 bool VolatileLoads = false,
160 Instruction *AllocaPoint = nullptr);
162 /// This function takes a virtual register computed by a phi node and replaces
163 /// it with a slot in the stack frame, allocated via alloca. The phi node is
164 /// deleted and it returns the pointer to the alloca inserted.
165 AllocaInst *DemotePHIToStack(PHINode *P, Instruction *AllocaPoint = nullptr);
167 /// Try to ensure that the alignment of \p V is at least \p PrefAlign bytes. If
168 /// the owning object can be modified and has an alignment less than \p
169 /// PrefAlign, it will be increased and \p PrefAlign returned. If the alignment
170 /// cannot be increased, the known alignment of the value is returned.
172 /// It is not always possible to modify the alignment of the underlying object,
173 /// so if alignment is important, a more reliable approach is to simply align
174 /// all global variables and allocation instructions to their preferred
175 /// alignment from the beginning.
176 unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
177 const DataLayout &DL,
178 const Instruction *CxtI = nullptr,
179 AssumptionCache *AC = nullptr,
180 const DominatorTree *DT = nullptr);
182 /// Try to infer an alignment for the specified pointer.
183 static inline unsigned getKnownAlignment(Value *V, const DataLayout &DL,
184 const Instruction *CxtI = nullptr,
185 AssumptionCache *AC = nullptr,
186 const DominatorTree *DT = nullptr) {
187 return getOrEnforceKnownAlignment(V, 0, DL, CxtI, AC, DT);
190 /// Given a getelementptr instruction/constantexpr, emit the code necessary to
191 /// compute the offset from the base pointer (without adding in the base
192 /// pointer). Return the result as a signed integer of intptr size.
193 /// When NoAssumptions is true, no assumptions about index computation not
194 /// overflowing is made.
195 template <typename IRBuilderTy>
196 Value *EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &DL, User *GEP,
197 bool NoAssumptions = false) {
198 GEPOperator *GEPOp = cast<GEPOperator>(GEP);
199 Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
200 Value *Result = Constant::getNullValue(IntPtrTy);
202 // If the GEP is inbounds, we know that none of the addressing operations will
203 // overflow in an unsigned sense.
204 bool isInBounds = GEPOp->isInBounds() && !NoAssumptions;
206 // Build a mask for high order bits.
207 unsigned IntPtrWidth = IntPtrTy->getScalarType()->getIntegerBitWidth();
208 uint64_t PtrSizeMask = ~0ULL >> (64 - IntPtrWidth);
210 gep_type_iterator GTI = gep_type_begin(GEP);
211 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
214 uint64_t Size = DL.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
215 if (Constant *OpC = dyn_cast<Constant>(Op)) {
216 if (OpC->isZeroValue())
219 // Handle a struct index, which adds its field offset to the pointer.
220 if (StructType *STy = GTI.getStructTypeOrNull()) {
221 if (OpC->getType()->isVectorTy())
222 OpC = OpC->getSplatValue();
224 uint64_t OpValue = cast<ConstantInt>(OpC)->getZExtValue();
225 Size = DL.getStructLayout(STy)->getElementOffset(OpValue);
228 Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
229 GEP->getName()+".offs");
233 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
234 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
235 Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
236 // Emit an add instruction.
237 Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
240 // Convert to correct type.
241 if (Op->getType() != IntPtrTy)
242 Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
244 // We'll let instcombine(mul) convert this to a shl if possible.
245 Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
246 GEP->getName()+".idx", isInBounds /*NUW*/);
249 // Emit an add instruction.
250 Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
255 ///===---------------------------------------------------------------------===//
256 /// Dbg Intrinsic utilities
259 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
260 /// that has an associated llvm.dbg.decl intrinsic.
261 void ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
262 StoreInst *SI, DIBuilder &Builder);
264 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
265 /// that has an associated llvm.dbg.decl intrinsic.
266 void ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
267 LoadInst *LI, DIBuilder &Builder);
269 /// Inserts a llvm.dbg.value intrinsic after a phi of an alloca'd value
270 /// that has an associated llvm.dbg.decl intrinsic.
271 void ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
272 PHINode *LI, DIBuilder &Builder);
274 /// Lowers llvm.dbg.declare intrinsics into appropriate set of
275 /// llvm.dbg.value intrinsics.
276 bool LowerDbgDeclare(Function &F);
278 /// Finds the llvm.dbg.declare intrinsic corresponding to an alloca, if any.
279 DbgDeclareInst *FindAllocaDbgDeclare(Value *V);
281 /// Finds the llvm.dbg.value intrinsics corresponding to an alloca, if any.
282 void FindAllocaDbgValues(DbgValueList &DbgValues, Value *V);
284 /// Replaces llvm.dbg.declare instruction when the address it describes
285 /// is replaced with a new value. If Deref is true, an additional DW_OP_deref is
286 /// prepended to the expression. If Offset is non-zero, a constant displacement
287 /// is added to the expression (after the optional Deref). Offset can be
289 bool replaceDbgDeclare(Value *Address, Value *NewAddress,
290 Instruction *InsertBefore, DIBuilder &Builder,
291 bool Deref, int Offset);
293 /// Replaces llvm.dbg.declare instruction when the alloca it describes
294 /// is replaced with a new value. If Deref is true, an additional DW_OP_deref is
295 /// prepended to the expression. If Offset is non-zero, a constant displacement
296 /// is added to the expression (after the optional Deref). Offset can be
297 /// negative. New llvm.dbg.declare is inserted immediately before AI.
298 bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
299 DIBuilder &Builder, bool Deref, int Offset = 0);
301 /// Replaces multiple llvm.dbg.value instructions when the alloca it describes
302 /// is replaced with a new value. If Offset is non-zero, a constant displacement
303 /// is added to the expression (after the mandatory Deref). Offset can be
304 /// negative. New llvm.dbg.value instructions are inserted at the locations of
305 /// the instructions they replace.
306 void replaceDbgValueForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
307 DIBuilder &Builder, int Offset = 0);
309 /// Remove all instructions from a basic block other than it's terminator
310 /// and any present EH pad instructions.
311 unsigned removeAllNonTerminatorAndEHPadInstructions(BasicBlock *BB);
313 /// Insert an unreachable instruction before the specified
314 /// instruction, making it and the rest of the code in the block dead.
315 unsigned changeToUnreachable(Instruction *I, bool UseLLVMTrap,
316 bool PreserveLCSSA = false);
318 /// Convert the CallInst to InvokeInst with the specified unwind edge basic
319 /// block. This also splits the basic block where CI is located, because
320 /// InvokeInst is a terminator instruction. Returns the newly split basic
322 BasicBlock *changeToInvokeAndSplitBasicBlock(CallInst *CI,
323 BasicBlock *UnwindEdge);
325 /// Replace 'BB's terminator with one that does not have an unwind successor
326 /// block. Rewrites `invoke` to `call`, etc. Updates any PHIs in unwind
329 /// \param BB Block whose terminator will be replaced. Its terminator must
330 /// have an unwind successor.
331 void removeUnwindEdge(BasicBlock *BB);
333 /// Remove all blocks that can not be reached from the function's entry.
335 /// Returns true if any basic block was removed.
336 bool removeUnreachableBlocks(Function &F, LazyValueInfo *LVI = nullptr);
338 /// Combine the metadata of two instructions so that K can replace J
340 /// Metadata not listed as known via KnownIDs is removed
341 void combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs);
343 /// Combine the metadata of two instructions so that K can replace J. This
344 /// specifically handles the case of CSE-like transformations.
346 /// Unknown metadata is removed.
347 void combineMetadataForCSE(Instruction *K, const Instruction *J);
349 /// Replace each use of 'From' with 'To' if that use is dominated by
350 /// the given edge. Returns the number of replacements made.
351 unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT,
352 const BasicBlockEdge &Edge);
353 /// Replace each use of 'From' with 'To' if that use is dominated by
354 /// the end of the given BasicBlock. Returns the number of replacements made.
355 unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT,
356 const BasicBlock *BB);
359 /// Return true if the CallSite CS calls a gc leaf function.
361 /// A leaf function is a function that does not safepoint the thread during its
362 /// execution. During a call or invoke to such a function, the callers stack
363 /// does not have to be made parseable.
365 /// Most passes can and should ignore this information, and it is only used
366 /// during lowering by the GC infrastructure.
367 bool callsGCLeafFunction(ImmutableCallSite CS);
369 //===----------------------------------------------------------------------===//
370 // Intrinsic pattern matching
373 /// Try and match a bswap or bitreverse idiom.
375 /// If an idiom is matched, an intrinsic call is inserted before \c I. Any added
376 /// instructions are returned in \c InsertedInsts. They will all have been added
377 /// to a basic block.
379 /// A bitreverse idiom normally requires around 2*BW nodes to be searched (where
380 /// BW is the bitwidth of the integer type). A bswap idiom requires anywhere up
381 /// to BW / 4 nodes to be searched, so is significantly faster.
383 /// This function returns true on a successful match or false otherwise.
384 bool recognizeBSwapOrBitReverseIdiom(
385 Instruction *I, bool MatchBSwaps, bool MatchBitReversals,
386 SmallVectorImpl<Instruction *> &InsertedInsts);
388 //===----------------------------------------------------------------------===//
389 // Sanitizer utilities
392 /// Given a CallInst, check if it calls a string function known to CodeGen,
393 /// and mark it with NoBuiltin if so. To be used by sanitizers that intend
394 /// to intercept string functions and want to avoid converting them to target
395 /// specific instructions.
396 void maybeMarkSanitizerLibraryCallNoBuiltin(CallInst *CI,
397 const TargetLibraryInfo *TLI);
399 } // End llvm namespace