Move llvm/Support/IRBuilder.h -> llvm/IRBuilder.h
[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/IRBuilder.h"
19 #include "llvm/Operator.h"
20 #include "llvm/Support/GetElementPtrTypeIterator.h"
21 #include "llvm/Target/TargetData.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 ConstantExpr;
38 class TargetData;
39 class DIBuilder;
40
41 template<typename T> class SmallVectorImpl;
42   
43 //===----------------------------------------------------------------------===//
44 //  Local constant propagation.
45 //
46
47 /// ConstantFoldTerminator - If a terminator instruction is predicated on a
48 /// constant value, convert it into an unconditional branch to the constant
49 /// destination.  This is a nontrivial operation because the successors of this
50 /// basic block must have their PHI nodes updated.
51 /// Also calls RecursivelyDeleteTriviallyDeadInstructions() on any branch/switch
52 /// conditions and indirectbr addresses this might make dead if
53 /// DeleteDeadConditions is true.
54 bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions = false);
55
56 //===----------------------------------------------------------------------===//
57 //  Local dead code elimination.
58 //
59
60 /// isInstructionTriviallyDead - Return true if the result produced by the
61 /// instruction is not used, and the instruction has no side effects.
62 ///
63 bool isInstructionTriviallyDead(Instruction *I);
64
65 /// RecursivelyDeleteTriviallyDeadInstructions - If the specified value is a
66 /// trivially dead instruction, delete it.  If that makes any of its operands
67 /// trivially dead, delete them too, recursively.  Return true if any
68 /// instructions were deleted.
69 bool RecursivelyDeleteTriviallyDeadInstructions(Value *V);
70
71 /// RecursivelyDeleteDeadPHINode - If the specified value is an effectively
72 /// dead PHI node, due to being a def-use chain of single-use nodes that
73 /// either forms a cycle or is terminated by a trivially dead instruction,
74 /// delete it.  If that makes any of its operands trivially dead, delete them
75 /// too, recursively.  Return true if a change was made.
76 bool RecursivelyDeleteDeadPHINode(PHINode *PN);
77
78   
79 /// SimplifyInstructionsInBlock - Scan the specified basic block and try to
80 /// simplify any instructions in it and recursively delete dead instructions.
81 ///
82 /// This returns true if it changed the code, note that it can delete
83 /// instructions in other blocks as well in this block.
84 bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetData *TD = 0);
85     
86 //===----------------------------------------------------------------------===//
87 //  Control Flow Graph Restructuring.
88 //
89
90 /// RemovePredecessorAndSimplify - Like BasicBlock::removePredecessor, this
91 /// method is called when we're about to delete Pred as a predecessor of BB.  If
92 /// BB contains any PHI nodes, this drops the entries in the PHI nodes for Pred.
93 ///
94 /// Unlike the removePredecessor method, this attempts to simplify uses of PHI
95 /// nodes that collapse into identity values.  For example, if we have:
96 ///   x = phi(1, 0, 0, 0)
97 ///   y = and x, z
98 ///
99 /// .. and delete the predecessor corresponding to the '1', this will attempt to
100 /// recursively fold the 'and' to 0.
101 void RemovePredecessorAndSimplify(BasicBlock *BB, BasicBlock *Pred,
102                                   TargetData *TD = 0);
103     
104   
105 /// MergeBasicBlockIntoOnlyPred - BB is a block with one predecessor and its
106 /// predecessor is known to have one successor (BB!).  Eliminate the edge
107 /// between them, moving the instructions in the predecessor into BB.  This
108 /// deletes the predecessor block.
109 ///
110 void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, Pass *P = 0);
111     
112
113 /// TryToSimplifyUncondBranchFromEmptyBlock - BB is known to contain an
114 /// unconditional branch, and contains no instructions other than PHI nodes,
115 /// potential debug intrinsics and the branch.  If possible, eliminate BB by
116 /// rewriting all the predecessors to branch to the successor block and return
117 /// true.  If we can't transform, return false.
118 bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB);
119
120 /// EliminateDuplicatePHINodes - Check for and eliminate duplicate PHI
121 /// nodes in this block. This doesn't try to be clever about PHI nodes
122 /// which differ only in the order of the incoming values, but instcombine
123 /// orders them so it usually won't matter.
124 ///
125 bool EliminateDuplicatePHINodes(BasicBlock *BB);
126
127 /// SimplifyCFG - This function is used to do simplification of a CFG.  For
128 /// example, it adjusts branches to branches to eliminate the extra hop, it
129 /// eliminates unreachable basic blocks, and does other "peephole" optimization
130 /// of the CFG.  It returns true if a modification was made, possibly deleting
131 /// the basic block that was pointed to.
132 ///
133 bool SimplifyCFG(BasicBlock *BB, const TargetData *TD = 0);
134
135 /// FoldBranchToCommonDest - If this basic block is ONLY a setcc and a branch,
136 /// and if a predecessor branches to us and one of our successors, fold the
137 /// setcc into the predecessor and use logical operations to pick the right
138 /// destination.
139 bool FoldBranchToCommonDest(BranchInst *BI);
140
141 /// DemoteRegToStack - This function takes a virtual register computed by an
142 /// Instruction and replaces it with a slot in the stack frame, allocated via
143 /// alloca.  This allows the CFG to be changed around without fear of
144 /// invalidating the SSA information for the value.  It returns the pointer to
145 /// the alloca inserted to create a stack slot for X.
146 ///
147 AllocaInst *DemoteRegToStack(Instruction &X,
148                              bool VolatileLoads = false,
149                              Instruction *AllocaPoint = 0);
150
151 /// DemotePHIToStack - This function takes a virtual register computed by a phi
152 /// node and replaces it with a slot in the stack frame, allocated via alloca.
153 /// The phi node is deleted and it returns the pointer to the alloca inserted. 
154 AllocaInst *DemotePHIToStack(PHINode *P, Instruction *AllocaPoint = 0);
155
156 /// getOrEnforceKnownAlignment - If the specified pointer has an alignment that
157 /// we can determine, return it, otherwise return 0.  If PrefAlign is specified,
158 /// and it is more than the alignment of the ultimate object, see if we can
159 /// increase the alignment of the ultimate object, making this check succeed.
160 unsigned getOrEnforceKnownAlignment(Value *V, unsigned PrefAlign,
161                                     const TargetData *TD = 0);
162
163 /// getKnownAlignment - Try to infer an alignment for the specified pointer.
164 static inline unsigned getKnownAlignment(Value *V, const TargetData *TD = 0) {
165   return getOrEnforceKnownAlignment(V, 0, TD);
166 }
167
168 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
169 /// code necessary to compute the offset from the base pointer (without adding
170 /// in the base pointer).  Return the result as a signed integer of intptr size.
171 template<typename IRBuilderTy>
172 Value *EmitGEPOffset(IRBuilderTy *Builder, const TargetData &TD, User *GEP) {
173   gep_type_iterator GTI = gep_type_begin(GEP);
174   Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
175   Value *Result = Constant::getNullValue(IntPtrTy);
176
177   // If the GEP is inbounds, we know that none of the addressing operations will
178   // overflow in an unsigned sense.
179   bool isInBounds = cast<GEPOperator>(GEP)->isInBounds();
180
181   // Build a mask for high order bits.
182   unsigned IntPtrWidth = TD.getPointerSizeInBits();
183   uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
184
185   for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
186        ++i, ++GTI) {
187     Value *Op = *i;
188     uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
189     if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
190       if (OpC->isZero()) continue;
191
192       // Handle a struct index, which adds its field offset to the pointer.
193       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
194         Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
195
196         if (Size)
197           Result = Builder->CreateAdd(Result, ConstantInt::get(IntPtrTy, Size),
198                                       GEP->getName()+".offs");
199         continue;
200       }
201
202       Constant *Scale = ConstantInt::get(IntPtrTy, Size);
203       Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
204       Scale = ConstantExpr::getMul(OC, Scale, isInBounds/*NUW*/);
205       // Emit an add instruction.
206       Result = Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
207       continue;
208     }
209     // Convert to correct type.
210     if (Op->getType() != IntPtrTy)
211       Op = Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
212     if (Size != 1) {
213       // We'll let instcombine(mul) convert this to a shl if possible.
214       Op = Builder->CreateMul(Op, ConstantInt::get(IntPtrTy, Size),
215                               GEP->getName()+".idx", isInBounds /*NUW*/);
216     }
217
218     // Emit an add instruction.
219     Result = Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
220   }
221   return Result;
222 }
223
224 ///===---------------------------------------------------------------------===//
225 ///  Dbg Intrinsic utilities
226 ///
227
228 /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
229 /// that has an associated llvm.dbg.decl intrinsic.
230 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
231                                      StoreInst *SI, DIBuilder &Builder);
232
233 /// Inserts a llvm.dbg.value instrinsic before the stores to an alloca'd value
234 /// that has an associated llvm.dbg.decl intrinsic.
235 bool ConvertDebugDeclareToDebugValue(DbgDeclareInst *DDI,
236                                      LoadInst *LI, DIBuilder &Builder);
237
238 /// LowerDbgDeclare - Lowers llvm.dbg.declare intrinsics into appropriate set
239 /// of llvm.dbg.value intrinsics.
240 bool LowerDbgDeclare(Function &F);
241
242 /// FindAllocaDbgDeclare - Finds the llvm.dbg.declare intrinsic corresponding to
243 /// an alloca, if any.
244 DbgDeclareInst *FindAllocaDbgDeclare(Value *V);
245
246 } // End llvm namespace
247
248 #endif