LLVM API Documentation

InstCombine.h
Go to the documentation of this file.
00001 //===- InstCombine.h - Main InstCombine pass definition ---------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #ifndef INSTCOMBINE_INSTCOMBINE_H
00011 #define INSTCOMBINE_INSTCOMBINE_H
00012 
00013 #include "InstCombineWorklist.h"
00014 #include "llvm/Analysis/TargetFolder.h"
00015 #include "llvm/Analysis/ValueTracking.h"
00016 #include "llvm/IR/IRBuilder.h"
00017 #include "llvm/IR/InstVisitor.h"
00018 #include "llvm/IR/IntrinsicInst.h"
00019 #include "llvm/IR/Operator.h"
00020 #include "llvm/Pass.h"
00021 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
00022 
00023 namespace llvm {
00024   class CallSite;
00025   class DataLayout;
00026   class TargetLibraryInfo;
00027   class DbgDeclareInst;
00028   class MemIntrinsic;
00029   class MemSetInst;
00030 
00031 /// SelectPatternFlavor - We can match a variety of different patterns for
00032 /// select operations.
00033 enum SelectPatternFlavor {
00034   SPF_UNKNOWN = 0,
00035   SPF_SMIN, SPF_UMIN,
00036   SPF_SMAX, SPF_UMAX
00037   //SPF_ABS - TODO.
00038 };
00039 
00040 /// getComplexity:  Assign a complexity or rank value to LLVM Values...
00041 ///   0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
00042 static inline unsigned getComplexity(Value *V) {
00043   if (isa<Instruction>(V)) {
00044     if (BinaryOperator::isNeg(V) ||
00045         BinaryOperator::isFNeg(V) ||
00046         BinaryOperator::isNot(V))
00047       return 3;
00048     return 4;
00049   }
00050   if (isa<Argument>(V)) return 3;
00051   return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
00052 }
00053 
00054 /// AddOne - Add one to a Constant
00055 static inline Constant *AddOne(Constant *C) {
00056   return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
00057 }
00058 /// SubOne - Subtract one from a Constant
00059 static inline Constant *SubOne(Constant *C) {
00060   return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
00061 }
00062 
00063 
00064 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
00065 /// just like the normal insertion helper, but also adds any new instructions
00066 /// to the instcombine worklist.
00067 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
00068     : public IRBuilderDefaultInserter<true> {
00069   InstCombineWorklist &Worklist;
00070 public:
00071   InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
00072 
00073   void InsertHelper(Instruction *I, const Twine &Name,
00074                     BasicBlock *BB, BasicBlock::iterator InsertPt) const {
00075     IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
00076     Worklist.Add(I);
00077   }
00078 };
00079 
00080 /// InstCombiner - The -instcombine pass.
00081 class LLVM_LIBRARY_VISIBILITY InstCombiner
00082                              : public FunctionPass,
00083                                public InstVisitor<InstCombiner, Instruction*> {
00084   const DataLayout *DL;
00085   TargetLibraryInfo *TLI;
00086   bool MadeIRChange;
00087   LibCallSimplifier *Simplifier;
00088   bool MinimizeSize;
00089 public:
00090   /// Worklist - All of the instructions that need to be simplified.
00091   InstCombineWorklist Worklist;
00092 
00093   /// Builder - This is an IRBuilder that automatically inserts new
00094   /// instructions into the worklist when they are created.
00095   typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
00096   BuilderTy *Builder;
00097 
00098   static char ID; // Pass identification, replacement for typeid
00099   InstCombiner() : FunctionPass(ID), DL(0), Builder(0) {
00100     MinimizeSize = false;
00101     initializeInstCombinerPass(*PassRegistry::getPassRegistry());
00102   }
00103 
00104 public:
00105   bool runOnFunction(Function &F) override;
00106 
00107   bool DoOneIteration(Function &F, unsigned ItNum);
00108 
00109   void getAnalysisUsage(AnalysisUsage &AU) const override;
00110 
00111   const DataLayout *getDataLayout() const { return DL; }
00112 
00113   TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
00114 
00115   // Visitation implementation - Implement instruction combining for different
00116   // instruction types.  The semantics are as follows:
00117   // Return Value:
00118   //    null        - No change was made
00119   //     I          - Change was made, I is still valid, I may be dead though
00120   //   otherwise    - Change was made, replace I with returned instruction
00121   //
00122   Instruction *visitAdd(BinaryOperator &I);
00123   Instruction *visitFAdd(BinaryOperator &I);
00124   Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
00125   Instruction *visitSub(BinaryOperator &I);
00126   Instruction *visitFSub(BinaryOperator &I);
00127   Instruction *visitMul(BinaryOperator &I);
00128   Value *foldFMulConst(Instruction *FMulOrDiv, Constant *C,
00129                        Instruction *InsertBefore);
00130   Instruction *visitFMul(BinaryOperator &I);
00131   Instruction *visitURem(BinaryOperator &I);
00132   Instruction *visitSRem(BinaryOperator &I);
00133   Instruction *visitFRem(BinaryOperator &I);
00134   bool SimplifyDivRemOfSelect(BinaryOperator &I);
00135   Instruction *commonRemTransforms(BinaryOperator &I);
00136   Instruction *commonIRemTransforms(BinaryOperator &I);
00137   Instruction *commonDivTransforms(BinaryOperator &I);
00138   Instruction *commonIDivTransforms(BinaryOperator &I);
00139   Instruction *visitUDiv(BinaryOperator &I);
00140   Instruction *visitSDiv(BinaryOperator &I);
00141   Instruction *visitFDiv(BinaryOperator &I);
00142   Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
00143   Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
00144   Instruction *visitAnd(BinaryOperator &I);
00145   Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS);
00146   Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
00147   Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
00148                                    Value *A, Value *B, Value *C);
00149   Instruction *visitOr (BinaryOperator &I);
00150   Instruction *visitXor(BinaryOperator &I);
00151   Instruction *visitShl(BinaryOperator &I);
00152   Instruction *visitAShr(BinaryOperator &I);
00153   Instruction *visitLShr(BinaryOperator &I);
00154   Instruction *commonShiftTransforms(BinaryOperator &I);
00155   Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
00156                                     Constant *RHSC);
00157   Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
00158                                             GlobalVariable *GV, CmpInst &ICI,
00159                                             ConstantInt *AndCst = 0);
00160   Instruction *visitFCmpInst(FCmpInst &I);
00161   Instruction *visitICmpInst(ICmpInst &I);
00162   Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
00163   Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
00164                                               Instruction *LHS,
00165                                               ConstantInt *RHS);
00166   Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
00167                               ConstantInt *DivRHS);
00168   Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
00169                               ConstantInt *DivRHS);
00170   Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
00171                                 ICmpInst::Predicate Pred);
00172   Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
00173                            ICmpInst::Predicate Cond, Instruction &I);
00174   Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
00175                                    BinaryOperator &I);
00176   Instruction *commonCastTransforms(CastInst &CI);
00177   Instruction *commonPointerCastTransforms(CastInst &CI);
00178   Instruction *visitTrunc(TruncInst &CI);
00179   Instruction *visitZExt(ZExtInst &CI);
00180   Instruction *visitSExt(SExtInst &CI);
00181   Instruction *visitFPTrunc(FPTruncInst &CI);
00182   Instruction *visitFPExt(CastInst &CI);
00183   Instruction *visitFPToUI(FPToUIInst &FI);
00184   Instruction *visitFPToSI(FPToSIInst &FI);
00185   Instruction *visitUIToFP(CastInst &CI);
00186   Instruction *visitSIToFP(CastInst &CI);
00187   Instruction *visitPtrToInt(PtrToIntInst &CI);
00188   Instruction *visitIntToPtr(IntToPtrInst &CI);
00189   Instruction *visitBitCast(BitCastInst &CI);
00190   Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
00191   Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
00192                               Instruction *FI);
00193   Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
00194   Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
00195                             Value *A, Value *B, Instruction &Outer,
00196                             SelectPatternFlavor SPF2, Value *C);
00197   Instruction *visitSelectInst(SelectInst &SI);
00198   Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
00199   Instruction *visitCallInst(CallInst &CI);
00200   Instruction *visitInvokeInst(InvokeInst &II);
00201 
00202   Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
00203   Instruction *visitPHINode(PHINode &PN);
00204   Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
00205   Instruction *visitAllocaInst(AllocaInst &AI);
00206   Instruction *visitAllocSite(Instruction &FI);
00207   Instruction *visitFree(CallInst &FI);
00208   Instruction *visitLoadInst(LoadInst &LI);
00209   Instruction *visitStoreInst(StoreInst &SI);
00210   Instruction *visitBranchInst(BranchInst &BI);
00211   Instruction *visitSwitchInst(SwitchInst &SI);
00212   Instruction *visitInsertElementInst(InsertElementInst &IE);
00213   Instruction *visitExtractElementInst(ExtractElementInst &EI);
00214   Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
00215   Instruction *visitExtractValueInst(ExtractValueInst &EV);
00216   Instruction *visitLandingPadInst(LandingPadInst &LI);
00217 
00218   // visitInstruction - Specify what to return for unhandled instructions...
00219   Instruction *visitInstruction(Instruction &I) { return 0; }
00220 
00221 private:
00222   bool ShouldChangeType(Type *From, Type *To) const;
00223   Value *dyn_castNegVal(Value *V) const;
00224   Value *dyn_castFNegVal(Value *V, bool NoSignedZero=false) const;
00225   Type *FindElementAtOffset(Type *PtrTy, int64_t Offset,
00226                             SmallVectorImpl<Value*> &NewIndices);
00227   Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
00228 
00229   /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
00230   /// results in any code being generated and is interesting to optimize out. If
00231   /// the cast can be eliminated by some other simple transformation, we prefer
00232   /// to do the simplification first.
00233   bool ShouldOptimizeCast(Instruction::CastOps opcode,const Value *V,
00234                           Type *Ty);
00235 
00236   Instruction *visitCallSite(CallSite CS);
00237   Instruction *tryOptimizeCall(CallInst *CI, const DataLayout *DL);
00238   bool transformConstExprCastCall(CallSite CS);
00239   Instruction *transformCallThroughTrampoline(CallSite CS,
00240                                               IntrinsicInst *Tramp);
00241   Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
00242                                  bool DoXform = true);
00243   Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
00244   bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
00245   Value *EmitGEPOffset(User *GEP);
00246   Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
00247   Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
00248 
00249 public:
00250   // InsertNewInstBefore - insert an instruction New before instruction Old
00251   // in the program.  Add the new instruction to the worklist.
00252   //
00253   Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
00254     assert(New && New->getParent() == 0 &&
00255            "New instruction already inserted into a basic block!");
00256     BasicBlock *BB = Old.getParent();
00257     BB->getInstList().insert(&Old, New);  // Insert inst
00258     Worklist.Add(New);
00259     return New;
00260   }
00261 
00262   // InsertNewInstWith - same as InsertNewInstBefore, but also sets the
00263   // debug loc.
00264   //
00265   Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
00266     New->setDebugLoc(Old.getDebugLoc());
00267     return InsertNewInstBefore(New, Old);
00268   }
00269 
00270   // ReplaceInstUsesWith - This method is to be used when an instruction is
00271   // found to be dead, replacable with another preexisting expression.  Here
00272   // we add all uses of I to the worklist, replace all uses of I with the new
00273   // value, then return I, so that the inst combiner will know that I was
00274   // modified.
00275   //
00276   Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
00277     Worklist.AddUsersToWorkList(I);   // Add all modified instrs to worklist.
00278 
00279     // If we are replacing the instruction with itself, this must be in a
00280     // segment of unreachable code, so just clobber the instruction.
00281     if (&I == V)
00282       V = UndefValue::get(I.getType());
00283 
00284     DEBUG(dbgs() << "IC: Replacing " << I << "\n"
00285                     "    with " << *V << '\n');
00286 
00287     I.replaceAllUsesWith(V);
00288     return &I;
00289   }
00290 
00291   // EraseInstFromFunction - When dealing with an instruction that has side
00292   // effects or produces a void value, we can't rely on DCE to delete the
00293   // instruction.  Instead, visit methods should return the value returned by
00294   // this function.
00295   Instruction *EraseInstFromFunction(Instruction &I) {
00296     DEBUG(dbgs() << "IC: ERASE " << I << '\n');
00297 
00298     assert(I.use_empty() && "Cannot erase instruction that is used!");
00299     // Make sure that we reprocess all operands now that we reduced their
00300     // use counts.
00301     if (I.getNumOperands() < 8) {
00302       for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
00303         if (Instruction *Op = dyn_cast<Instruction>(*i))
00304           Worklist.Add(Op);
00305     }
00306     Worklist.Remove(&I);
00307     I.eraseFromParent();
00308     MadeIRChange = true;
00309     return 0;  // Don't do anything with FI
00310   }
00311 
00312   void ComputeMaskedBits(Value *V, APInt &KnownZero,
00313                          APInt &KnownOne, unsigned Depth = 0) const {
00314     return llvm::ComputeMaskedBits(V, KnownZero, KnownOne, DL, Depth);
00315   }
00316 
00317   bool MaskedValueIsZero(Value *V, const APInt &Mask,
00318                          unsigned Depth = 0) const {
00319     return llvm::MaskedValueIsZero(V, Mask, DL, Depth);
00320   }
00321   unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
00322     return llvm::ComputeNumSignBits(Op, DL, Depth);
00323   }
00324 
00325 private:
00326 
00327   /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
00328   /// operators which are associative or commutative.
00329   bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
00330 
00331   /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
00332   /// which some other binary operation distributes over either by factorizing
00333   /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
00334   /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
00335   /// a win).  Returns the simplified value, or null if it didn't simplify.
00336   Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
00337 
00338   /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
00339   /// based on the demanded bits.
00340   Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
00341                                  APInt& KnownZero, APInt& KnownOne,
00342                                  unsigned Depth);
00343   bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
00344                             APInt& KnownZero, APInt& KnownOne,
00345                             unsigned Depth=0);
00346   /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
00347   /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
00348   Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
00349                                     APInt DemandedMask, APInt &KnownZero,
00350                                     APInt &KnownOne);
00351 
00352   /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
00353   /// SimplifyDemandedBits knows about.  See if the instruction has any
00354   /// properties that allow us to simplify its operands.
00355   bool SimplifyDemandedInstructionBits(Instruction &Inst);
00356 
00357   Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
00358                                     APInt& UndefElts, unsigned Depth = 0);
00359 
00360   // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
00361   // which has a PHI node as operand #0, see if we can fold the instruction
00362   // into the PHI (which is only possible if all operands to the PHI are
00363   // constants).
00364   //
00365   Instruction *FoldOpIntoPhi(Instruction &I);
00366 
00367   // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
00368   // operator and they all are only used by the PHI, PHI together their
00369   // inputs, and do the operation once, to the result of the PHI.
00370   Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
00371   Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
00372   Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
00373   Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
00374 
00375 
00376   Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
00377                         ConstantInt *AndRHS, BinaryOperator &TheAnd);
00378 
00379   Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
00380                             bool isSub, Instruction &I);
00381   Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
00382                          bool isSigned, bool Inside);
00383   Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
00384   Instruction *MatchBSwap(BinaryOperator &I);
00385   bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
00386   Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
00387   Instruction *SimplifyMemSet(MemSetInst *MI);
00388 
00389 
00390   Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
00391 
00392   /// Descale - Return a value X such that Val = X * Scale, or null if none.  If
00393   /// the multiplication is known not to overflow then NoSignedWrap is set.
00394   Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
00395 };
00396 
00397 
00398 
00399 } // end namespace llvm.
00400 
00401 #endif