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