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