llvm.dbg.declare intrinsic does not use any llvm::Values. It's magic!
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombine.h
1 //===- InstCombine.h - Main InstCombine pass definition -------------------===//
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 #ifndef INSTCOMBINE_INSTCOMBINE_H
11 #define INSTCOMBINE_INSTCOMBINE_H
12
13 #include "InstCombineWorklist.h"
14 #include "llvm/Pass.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Support/IRBuilder.h"
17 #include "llvm/Support/InstVisitor.h"
18 #include "llvm/Support/TargetFolder.h"
19
20 namespace llvm {
21   class CallSite;
22   class TargetData;
23   class DbgDeclareInst;
24   class MemIntrinsic;
25   class MemSetInst;
26   
27 /// SelectPatternFlavor - We can match a variety of different patterns for
28 /// select operations.
29 enum SelectPatternFlavor {
30   SPF_UNKNOWN = 0,
31   SPF_SMIN, SPF_UMIN,
32   SPF_SMAX, SPF_UMAX
33   //SPF_ABS - TODO.
34 };
35   
36 /// getComplexity:  Assign a complexity or rank value to LLVM Values...
37 ///   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
38 static inline unsigned getComplexity(Value *V) {
39   if (isa<Instruction>(V)) {
40     if (BinaryOperator::isNeg(V) ||
41         BinaryOperator::isFNeg(V) ||
42         BinaryOperator::isNot(V))
43       return 3;
44     return 4;
45   }
46   if (isa<Argument>(V)) return 3;
47   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
48 }
49
50   
51 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
52 /// just like the normal insertion helper, but also adds any new instructions
53 /// to the instcombine worklist.
54 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter 
55     : public IRBuilderDefaultInserter<true> {
56   InstCombineWorklist &Worklist;
57 public:
58   InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
59   
60   void InsertHelper(Instruction *I, const Twine &Name,
61                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
62     IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
63     Worklist.Add(I);
64   }
65 };
66   
67 /// InstCombiner - The -instcombine pass.
68 class LLVM_LIBRARY_VISIBILITY InstCombiner
69                              : public FunctionPass,
70                                public InstVisitor<InstCombiner, Instruction*> {
71   TargetData *TD;
72   bool MustPreserveLCSSA;
73   bool MadeIRChange;
74 public:
75   /// Worklist - All of the instructions that need to be simplified.
76   InstCombineWorklist Worklist;
77
78   /// Builder - This is an IRBuilder that automatically inserts new
79   /// instructions into the worklist when they are created.
80   typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
81   BuilderTy *Builder;
82       
83   static char ID; // Pass identification, replacement for typeid
84   InstCombiner() : FunctionPass(ID), TD(0), Builder(0) {
85     initializeInstCombinerPass(*PassRegistry::getPassRegistry());
86   }
87
88 public:
89   virtual bool runOnFunction(Function &F);
90   
91   bool DoOneIteration(Function &F, unsigned ItNum);
92
93   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
94                                  
95   TargetData *getTargetData() const { return TD; }
96
97   // Visitation implementation - Implement instruction combining for different
98   // instruction types.  The semantics are as follows:
99   // Return Value:
100   //    null        - No change was made
101   //     I          - Change was made, I is still valid, I may be dead though
102   //   otherwise    - Change was made, replace I with returned instruction
103   //
104   Instruction *visitAdd(BinaryOperator &I);
105   Instruction *visitFAdd(BinaryOperator &I);
106   Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
107   Instruction *visitSub(BinaryOperator &I);
108   Instruction *visitFSub(BinaryOperator &I);
109   Instruction *visitMul(BinaryOperator &I);
110   Instruction *visitFMul(BinaryOperator &I);
111   Instruction *visitURem(BinaryOperator &I);
112   Instruction *visitSRem(BinaryOperator &I);
113   Instruction *visitFRem(BinaryOperator &I);
114   bool SimplifyDivRemOfSelect(BinaryOperator &I);
115   Instruction *commonRemTransforms(BinaryOperator &I);
116   Instruction *commonIRemTransforms(BinaryOperator &I);
117   Instruction *commonDivTransforms(BinaryOperator &I);
118   Instruction *commonIDivTransforms(BinaryOperator &I);
119   Instruction *visitUDiv(BinaryOperator &I);
120   Instruction *visitSDiv(BinaryOperator &I);
121   Instruction *visitFDiv(BinaryOperator &I);
122   Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
123   Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
124   Instruction *visitAnd(BinaryOperator &I);
125   Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS);
126   Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
127   Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
128                                    Value *A, Value *B, Value *C);
129   Instruction *visitOr (BinaryOperator &I);
130   Instruction *visitXor(BinaryOperator &I);
131   Instruction *visitShl(BinaryOperator &I);
132   Instruction *visitAShr(BinaryOperator &I);
133   Instruction *visitLShr(BinaryOperator &I);
134   Instruction *commonShiftTransforms(BinaryOperator &I);
135   Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
136                                     Constant *RHSC);
137   Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
138                                             GlobalVariable *GV, CmpInst &ICI,
139                                             ConstantInt *AndCst = 0);
140   Instruction *visitFCmpInst(FCmpInst &I);
141   Instruction *visitICmpInst(ICmpInst &I);
142   Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
143   Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
144                                               Instruction *LHS,
145                                               ConstantInt *RHS);
146   Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
147                               ConstantInt *DivRHS);
148   Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
149                               ConstantInt *DivRHS);
150   Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
151                                 ICmpInst::Predicate Pred, Value *TheAdd);
152   Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
153                            ICmpInst::Predicate Cond, Instruction &I);
154   Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
155                                    BinaryOperator &I);
156   Instruction *commonCastTransforms(CastInst &CI);
157   Instruction *commonPointerCastTransforms(CastInst &CI);
158   Instruction *visitTrunc(TruncInst &CI);
159   Instruction *visitZExt(ZExtInst &CI);
160   Instruction *visitSExt(SExtInst &CI);
161   Instruction *visitFPTrunc(FPTruncInst &CI);
162   Instruction *visitFPExt(CastInst &CI);
163   Instruction *visitFPToUI(FPToUIInst &FI);
164   Instruction *visitFPToSI(FPToSIInst &FI);
165   Instruction *visitUIToFP(CastInst &CI);
166   Instruction *visitSIToFP(CastInst &CI);
167   Instruction *visitPtrToInt(PtrToIntInst &CI);
168   Instruction *visitIntToPtr(IntToPtrInst &CI);
169   Instruction *visitBitCast(BitCastInst &CI);
170   Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
171                               Instruction *FI);
172   Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
173   Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
174                             Value *A, Value *B, Instruction &Outer,
175                             SelectPatternFlavor SPF2, Value *C);
176   Instruction *visitSelectInst(SelectInst &SI);
177   Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
178   Instruction *visitCallInst(CallInst &CI);
179   Instruction *visitInvokeInst(InvokeInst &II);
180
181   Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
182   Instruction *visitPHINode(PHINode &PN);
183   Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
184   Instruction *visitAllocaInst(AllocaInst &AI);
185   Instruction *visitMalloc(Instruction &FI);
186   Instruction *visitFree(CallInst &FI);
187   Instruction *visitLoadInst(LoadInst &LI);
188   Instruction *visitStoreInst(StoreInst &SI);
189   Instruction *visitBranchInst(BranchInst &BI);
190   Instruction *visitSwitchInst(SwitchInst &SI);
191   Instruction *visitInsertElementInst(InsertElementInst &IE);
192   Instruction *visitExtractElementInst(ExtractElementInst &EI);
193   Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
194   Instruction *visitExtractValueInst(ExtractValueInst &EV);
195
196   // visitInstruction - Specify what to return for unhandled instructions...
197   Instruction *visitInstruction(Instruction &I) { return 0; }
198
199 private:
200   bool ShouldChangeType(const Type *From, const Type *To) const;
201   Value *dyn_castNegVal(Value *V) const;
202   Value *dyn_castFNegVal(Value *V) const;
203   const Type *FindElementAtOffset(const Type *Ty, int64_t Offset, 
204                                   SmallVectorImpl<Value*> &NewIndices);
205   Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
206                                  
207   /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
208   /// results in any code being generated and is interesting to optimize out. If
209   /// the cast can be eliminated by some other simple transformation, we prefer
210   /// to do the simplification first.
211   bool ShouldOptimizeCast(Instruction::CastOps opcode,const Value *V,
212                           const Type *Ty);
213
214   Instruction *visitCallSite(CallSite CS);
215   Instruction *tryOptimizeCall(CallInst *CI, const TargetData *TD);
216   bool transformConstExprCastCall(CallSite CS);
217   Instruction *transformCallThroughTrampoline(CallSite CS);
218   Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
219                                  bool DoXform = true);
220   bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
221   Value *EmitGEPOffset(User *GEP);
222
223 public:
224   // InsertNewInstBefore - insert an instruction New before instruction Old
225   // in the program.  Add the new instruction to the worklist.
226   //
227   Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
228     assert(New && New->getParent() == 0 &&
229            "New instruction already inserted into a basic block!");
230     BasicBlock *BB = Old.getParent();
231     BB->getInstList().insert(&Old, New);  // Insert inst
232     Worklist.Add(New);
233     return New;
234   }
235       
236   // ReplaceInstUsesWith - This method is to be used when an instruction is
237   // found to be dead, replacable with another preexisting expression.  Here
238   // we add all uses of I to the worklist, replace all uses of I with the new
239   // value, then return I, so that the inst combiner will know that I was
240   // modified.
241   //
242   Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
243     Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
244     
245     // If we are replacing the instruction with itself, this must be in a
246     // segment of unreachable code, so just clobber the instruction.
247     if (&I == V) 
248       V = UndefValue::get(I.getType());
249       
250     I.replaceAllUsesWith(V);
251     return &I;
252   }
253
254   // EraseInstFromFunction - When dealing with an instruction that has side
255   // effects or produces a void value, we can't rely on DCE to delete the
256   // instruction.  Instead, visit methods should return the value returned by
257   // this function.
258   Instruction *EraseInstFromFunction(Instruction &I) {
259     DEBUG(errs() << "IC: ERASE " << I << '\n');
260
261     assert(I.use_empty() && "Cannot erase instruction that is used!");
262     // Make sure that we reprocess all operands now that we reduced their
263     // use counts.
264     if (I.getNumOperands() < 8) {
265       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
266         if (Instruction *Op = dyn_cast<Instruction>(*i))
267           Worklist.Add(Op);
268     }
269     Worklist.Remove(&I);
270     I.eraseFromParent();
271     MadeIRChange = true;
272     return 0;  // Don't do anything with FI
273   }
274       
275   void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
276                          APInt &KnownOne, unsigned Depth = 0) const {
277     return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
278   }
279   
280   bool MaskedValueIsZero(Value *V, const APInt &Mask, 
281                          unsigned Depth = 0) const {
282     return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
283   }
284   unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
285     return llvm::ComputeNumSignBits(Op, TD, Depth);
286   }
287
288 private:
289
290   /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
291   /// operators which are associative or commutative.
292   bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
293
294   /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
295   /// which some other binary operation distributes over either by factorizing
296   /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
297   /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
298   /// a win).  Returns the simplified value, or null if it didn't simplify.
299   Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
300
301   /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
302   /// based on the demanded bits.
303   Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, 
304                                  APInt& KnownZero, APInt& KnownOne,
305                                  unsigned Depth);
306   bool SimplifyDemandedBits(Use &U, APInt DemandedMask, 
307                             APInt& KnownZero, APInt& KnownOne,
308                             unsigned Depth=0);
309       
310   /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
311   /// SimplifyDemandedBits knows about.  See if the instruction has any
312   /// properties that allow us to simplify its operands.
313   bool SimplifyDemandedInstructionBits(Instruction &Inst);
314       
315   Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
316                                     APInt& UndefElts, unsigned Depth = 0);
317     
318   // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
319   // which has a PHI node as operand #0, see if we can fold the instruction
320   // into the PHI (which is only possible if all operands to the PHI are
321   // constants).
322   //
323   Instruction *FoldOpIntoPhi(Instruction &I);
324
325   // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
326   // operator and they all are only used by the PHI, PHI together their
327   // inputs, and do the operation once, to the result of the PHI.
328   Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
329   Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
330   Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
331   Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
332
333   
334   Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
335                         ConstantInt *AndRHS, BinaryOperator &TheAnd);
336   
337   Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
338                             bool isSub, Instruction &I);
339   Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
340                          bool isSigned, bool Inside);
341   Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
342   Instruction *MatchBSwap(BinaryOperator &I);
343   bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
344   Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
345   Instruction *SimplifyMemSet(MemSetInst *MI);
346
347
348   Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
349 };
350
351       
352   
353 } // end namespace llvm.
354
355 #endif