[PM] Split the AssumptionTracker immutable pass into two separate APIs:
[oota-llvm.git] / include / llvm / Transforms / Utils / Local.h
1 //===-- Local.h - Functions to perform local transformations ----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This family of functions perform various local transformations to the
11 // program.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_TRANSFORMS_UTILS_LOCAL_H
16 #define LLVM_TRANSFORMS_UTILS_LOCAL_H
17
18 #include "llvm/IR/DataLayout.h"
19 #include "llvm/IR/GetElementPtrTypeIterator.h"
20 #include "llvm/IR/IRBuilder.h"
21 #include "llvm/IR/Operator.h"
22
23 namespace llvm {
24
25 class User;
26 class BasicBlock;
27 class Function;
28 class BranchInst;
29 class Instruction;
30 class DbgDeclareInst;
31 class StoreInst;
32 class LoadInst;
33 class Value;
34 class Pass;
35 class PHINode;
36 class AllocaInst;
37 class AssumptionCache;
38 class ConstantExpr;
39 class DataLayout;
40 class TargetLibraryInfo;
41 class TargetTransformInfo;
42 class DIBuilder;
43 class AliasAnalysis;
44 class DominatorTree;
45
46 template<typename T> class SmallVectorImpl;
47
48 //===----------------------------------------------------------------------===//
49 //  Local constant propagation.
50 //
51
52 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
53 /// constant value, convert it into an unconditional branch to the constant
54 /// destination.  This is a nontrivial operation because the successors of this
55 /// basic block must have their PHI nodes updated.
56 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
57 /// conditions and indirectbr addresses this might make dead if
58 /// DeleteDeadConditions is true.
59 bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions = false,
60                             const TargetLibraryInfo *TLI = nullptr);
61
62 //===----------------------------------------------------------------------===//
63 //  Local dead code elimination.
64 //
65
66 /// isInstructionTriviallyDead - Return true if the result produced by the
67 /// instruction is not used, and the instruction has no side effects.
68 ///
69 bool isInstructionTriviallyDead(Instruction *I,
70                                 const TargetLibraryInfo *TLI = nullptr);
71
72 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
73 /// trivially dead instruction, delete it.  If that makes any of its operands
74 /// trivially dead, delete them too, recursively.  Return true if any
75 /// instructions were deleted.
76 bool RecursivelyDeleteTriviallyDeadInstructions(Value *V,
77                                         const TargetLibraryInfo *TLI = nullptr);
78
79 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
80 /// dead PHI node, due to being a def-use chain of single-use nodes that
81 /// either forms a cycle or is terminated by a trivially dead instruction,
82 /// delete it.  If that makes any of its operands trivially dead, delete them
83 /// too, recursively.  Return true if a change was made.
84 bool RecursivelyDeleteDeadPHINode(PHINode *PN,
85                                   const TargetLibraryInfo *TLI = nullptr);
86
87 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
88 /// simplify any instructions in it and recursively delete dead instructions.
89 ///
90 /// This returns true if it changed the code, note that it can delete
91 /// instructions in other blocks as well in this block.
92 bool SimplifyInstructionsInBlock(BasicBlock *BB, const DataLayout *TD = nullptr,
93                                  const TargetLibraryInfo *TLI = nullptr);
94
95 //===----------------------------------------------------------------------===//
96 //  Control Flow Graph Restructuring.
97 //
98
99 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
100 /// method is called when we're about to delete Pred as a predecessor of BB.  If
101 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
102 ///
103 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
104 /// nodes that collapse into identity values.  For example, if we have:
105 ///   x = phi(1, 0, 0, 0)
106 ///   y = and x, z
107 ///
108 /// .. and delete the predecessor corresponding to the '1', this will attempt to
109 /// recursively fold the 'and' to 0.
110 void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
111                                   DataLayout *TD = nullptr);
112
113 /// MergeBasicBlockIntoOnlyPred - BB is a block with one predecessor and its
114 /// predecessor is known to have one successor (BB!).  Eliminate the edge
115 /// between them, moving the instructions in the predecessor into BB.  This
116 /// deletes the predecessor block.
117 ///
118 void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, Pass *P = nullptr);
119
120 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
121 /// unconditional branch, and contains no instructions other than PHI nodes,
122 /// potential debug intrinsics and the branch.  If possible, eliminate BB by
123 /// rewriting all the predecessors to branch to the successor block and return
124 /// true.  If we can't transform, return false.
125 bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB);
126
127 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
128 /// nodes in this block. This doesn't try to be clever about PHI nodes
129 /// which differ only in the order of the incoming values, but instcombine
130 /// orders them so it usually won't matter.
131 ///
132 bool EliminateDuplicatePHINodes(BasicBlock *BB);
133
134 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
135 /// example, it adjusts branches to branches to eliminate the extra hop, it
136 /// eliminates unreachable basic blocks, and does other "peephole" optimization
137 /// of the CFG.  It returns true if a modification was made, possibly deleting
138 /// the basic block that was pointed to.
139 ///
140 bool SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
141                  unsigned BonusInstThreshold, const DataLayout *TD = nullptr,
142                  AssumptionCache *AC = nullptr);
143
144 /// FlatternCFG - This function is used to flatten a CFG.  For
145 /// example, it uses parallel-and and parallel-or mode to collapse
146 //  if-conditions and merge if-regions with identical statements.
147 ///
148 bool FlattenCFG(BasicBlock *BB, AliasAnalysis *AA = nullptr);
149
150 /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
151 /// and if a predecessor branches to us and one of our successors, fold the
152 /// setcc into the predecessor and use logical operations to pick the right
153 /// destination.
154 bool FoldBranchToCommonDest(BranchInst *BI, const DataLayout *DL = nullptr,
155                             unsigned BonusInstThreshold = 1);
156
157 /// DemoteRegToStack - This function takes a virtual register computed by an
158 /// Instruction and replaces it with a slot in the stack frame, allocated via
159 /// alloca.  This allows the CFG to be changed around without fear of
160 /// invalidating the SSA information for the value.  It returns the pointer to
161 /// the alloca inserted to create a stack slot for X.
162 ///
163 AllocaInst *DemoteRegToStack(Instruction &X,
164                              bool VolatileLoads = false,
165                              Instruction *AllocaPoint = nullptr);
166
167 /// DemotePHIToStack - This function takes a virtual register computed by a phi
168 /// node and replaces it with a slot in the stack frame, allocated via alloca.
169 /// The phi node is deleted and it returns the pointer to the alloca inserted.
170 AllocaInst *DemotePHIToStack(PHINode *P, Instruction *AllocaPoint = nullptr);
171
172 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
173 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
174 /// and it is more than the alignment of the ultimate object, see if we can
175 /// increase the alignment of the ultimate object, making this check succeed.
176 unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
177                                     const DataLayout *TD = nullptr,
178                                     AssumptionCache *AC = nullptr,
179                                     const Instruction *CxtI = nullptr,
180                                     const DominatorTree *DT = nullptr);
181
182 /// getKnownAlignment - Try to infer an alignment for the specified pointer.
183 static inline unsigned getKnownAlignment(Value *V,
184                                          const DataLayout *TD = nullptr,
185                                          AssumptionCache *AC = nullptr,
186                                          const Instruction *CxtI = nullptr,
187                                          const DominatorTree *DT = nullptr) {
188   return getOrEnforceKnownAlignment(V, 0, TD, AC, CxtI, DT);
189 }
190
191 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
192 /// code necessary to compute the offset from the base pointer (without adding
193 /// in the base pointer).  Return the result as a signed integer of intptr size.
194 /// When NoAssumptions is true, no assumptions about index computation not
195 /// overflowing is made.
196 template<typename IRBuilderTy>
197 Value *EmitGEPOffset(IRBuilderTy *Builder, const DataLayout &TD, User *GEP,
198                      bool NoAssumptions = false) {
199   GEPOperator *GEPOp = cast<GEPOperator>(GEP);
200   Type *IntPtrTy = TD.getIntPtrType(GEP->getType());
201   Value *Result = Constant::getNullValue(IntPtrTy);
202
203   // If the GEP is inbounds, we know that none of the addressing operations will
204   // overflow in an unsigned sense.
205   bool isInBounds = GEPOp->isInBounds() && !NoAssumptions;
206
207   // Build a mask for high order bits.
208   unsigned IntPtrWidth = IntPtrTy->getScalarType()->getIntegerBitWidth();
209   uint64_t PtrSizeMask = ~0ULL >> (64 - IntPtrWidth);
210
211   gep_type_iterator GTI = gep_type_begin(GEP);
212   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
213        ++i, ++GTI) {
214     Value *Op = *i;
215     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
216     if (Constant *OpC = dyn_cast<Constant>(Op)) {
217       if (OpC->isZeroValue())
218         continue;
219
220       // Handle a struct index, which adds its field offset to the pointer.
221       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
222         if (OpC->getType()->isVectorTy())
223           OpC = OpC->getSplatValue();
224
225         uint64_t OpValue = cast<ConstantInt>(OpC)->getZExtValue();
226         Size = TD.getStructLayout(STy)->getElementOffset(OpValue);
227
228         if (Size)
229           Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
230                                       GEP->getName()+".offs");
231         continue;
232       }
233
234       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
235       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
236       Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
237       // Emit an add instruction.
238       Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
239       continue;
240     }
241     // Convert to correct type.
242     if (Op->getType() != IntPtrTy)
243       Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
244     if (Size != 1) {
245       // We'll let instcombine(mul) convert this to a shl if possible.
246       Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
247                               GEP->getName()+".idx", isInBounds /*NUW*/);
248     }
249
250     // Emit an add instruction.
251     Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
252   }
253   return Result;
254 }
255
256 ///===---------------------------------------------------------------------===//
257 ///  Dbg Intrinsic utilities
258 ///
259
260 /// Inserts a llvm.dbg.value intrinsic before a store to an alloca'd value
261 /// that has an associated llvm.dbg.decl intrinsic.
262 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
263                                      StoreInst *SI, DIBuilder &Builder);
264
265 /// Inserts a llvm.dbg.value intrinsic before a load of an alloca'd value
266 /// that has an associated llvm.dbg.decl intrinsic.
267 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
268                                      LoadInst *LI, DIBuilder &Builder);
269
270 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
271 /// of llvm.dbg.value intrinsics.
272 bool LowerDbgDeclare(Function &F);
273
274 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic corresponding to
275 /// an alloca, if any.
276 DbgDeclareInst *FindAllocaDbgDeclare(Value *V);
277
278 /// replaceDbgDeclareForAlloca - Replaces llvm.dbg.declare instruction when
279 /// alloca is replaced with a new value.
280 bool replaceDbgDeclareForAlloca(AllocaInst *AI, Value *NewAllocaAddress,
281                                 DIBuilder &Builder);
282
283 /// \brief Remove all blocks that can not be reached from the function's entry.
284 ///
285 /// Returns true if any basic block was removed.
286 bool removeUnreachableBlocks(Function &F);
287
288 /// \brief Combine the metadata of two instructions so that K can replace J
289 ///
290 /// Metadata not listed as known via KnownIDs is removed
291 void combineMetadata(Instruction *K, const Instruction *J, ArrayRef<unsigned> KnownIDs);
292
293 } // End llvm namespace
294
295 #endif