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