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