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