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