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