1 //===- InstCombine.h - Main InstCombine pass definition ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINE_H
11 #define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINE_H
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"
26 #define DEBUG_TYPE "instcombine"
32 class TargetLibraryInfo;
37 /// \brief Specific patterns of select instructions we can match.
38 enum SelectPatternFlavor {
48 /// \brief Assign a complexity or rank value to LLVM Values.
50 /// This routine maps IR values to various complexity ranks:
53 /// 2 -> Other non-instructions
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))
66 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
69 /// \brief Add one to a Constant
70 static inline Constant *AddOne(Constant *C) {
71 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
73 /// \brief Subtract one from a Constant
74 static inline Constant *SubOne(Constant *C) {
75 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
78 /// \brief An IRBuilder inserter that adds new instructions to the instcombine
80 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
81 : public IRBuilderDefaultInserter<true> {
82 InstCombineWorklist &Worklist;
86 InstCombineIRInserter(InstCombineWorklist &WL, AssumptionCache *AC)
87 : Worklist(WL), AC(AC) {}
89 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
90 BasicBlock::iterator InsertPt) const {
91 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
94 using namespace llvm::PatternMatch;
95 if (match(I, m_Intrinsic<Intrinsic::assume>()))
96 AC->registerAssumption(cast<CallInst>(I));
100 /// \brief The core instruction combiner logic.
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 // FIXME: These members shouldn't be public.
109 /// \brief A worklist of the instructions that need to be simplified.
110 InstCombineWorklist &Worklist;
112 /// \brief An IRBuilder that automatically inserts new instructions into the
114 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
118 // Mode in which we are running the combiner.
119 const bool MinimizeSize;
121 // Required analyses.
122 // FIXME: These can never be null and should be references.
124 TargetLibraryInfo *TLI;
127 // Optional analyses. When non-null, these can both be used to do better
128 // combining and will be updated to reflect any changes.
129 const DataLayout *DL;
135 InstCombiner(InstCombineWorklist &Worklist, BuilderTy *Builder,
136 bool MinimizeSize, AssumptionCache *AC, TargetLibraryInfo *TLI,
137 DominatorTree *DT, const DataLayout *DL, LoopInfo *LI)
138 : Worklist(Worklist), Builder(Builder), MinimizeSize(MinimizeSize),
139 AC(AC), TLI(TLI), DT(DT), DL(DL), LI(LI), MadeIRChange(false) {}
141 /// \brief Run the combiner over the entire worklist until it is empty.
143 /// \returns true if the IR is changed.
146 AssumptionCache *getAssumptionCache() const { return AC; }
148 const DataLayout *getDataLayout() const { return DL; }
150 DominatorTree *getDominatorTree() const { return DT; }
152 LoopInfo *getLoopInfo() const { return LI; }
154 TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
159 // null - No change was made
160 // I - Change was made, I is still valid, I may be dead though
161 // otherwise - Change was made, replace I with returned instruction
163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitFAdd(BinaryOperator &I);
165 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
166 Instruction *visitSub(BinaryOperator &I);
167 Instruction *visitFSub(BinaryOperator &I);
168 Instruction *visitMul(BinaryOperator &I);
169 Value *foldFMulConst(Instruction *FMulOrDiv, Constant *C,
170 Instruction *InsertBefore);
171 Instruction *visitFMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
183 Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
184 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
185 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
186 Instruction *visitAnd(BinaryOperator &I);
187 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI);
188 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
189 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, Value *A,
191 Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op, Value *A,
193 Instruction *visitOr(BinaryOperator &I);
194 Instruction *visitXor(BinaryOperator &I);
195 Instruction *visitShl(BinaryOperator &I);
196 Instruction *visitAShr(BinaryOperator &I);
197 Instruction *visitLShr(BinaryOperator &I);
198 Instruction *commonShiftTransforms(BinaryOperator &I);
199 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
201 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
202 GlobalVariable *GV, CmpInst &ICI,
203 ConstantInt *AndCst = nullptr);
204 Instruction *visitFCmpInst(FCmpInst &I);
205 Instruction *visitICmpInst(ICmpInst &I);
206 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
207 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHS,
209 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210 ConstantInt *DivRHS);
211 Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
212 ConstantInt *DivRHS);
213 Instruction *FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
214 ConstantInt *CI1, ConstantInt *CI2);
215 Instruction *FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
216 ConstantInt *CI1, ConstantInt *CI2);
217 Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
218 ICmpInst::Predicate Pred);
219 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
220 ICmpInst::Predicate Cond, Instruction &I);
221 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
223 Instruction *commonCastTransforms(CastInst &CI);
224 Instruction *commonPointerCastTransforms(CastInst &CI);
225 Instruction *visitTrunc(TruncInst &CI);
226 Instruction *visitZExt(ZExtInst &CI);
227 Instruction *visitSExt(SExtInst &CI);
228 Instruction *visitFPTrunc(FPTruncInst &CI);
229 Instruction *visitFPExt(CastInst &CI);
230 Instruction *visitFPToUI(FPToUIInst &FI);
231 Instruction *visitFPToSI(FPToSIInst &FI);
232 Instruction *visitUIToFP(CastInst &CI);
233 Instruction *visitSIToFP(CastInst &CI);
234 Instruction *visitPtrToInt(PtrToIntInst &CI);
235 Instruction *visitIntToPtr(IntToPtrInst &CI);
236 Instruction *visitBitCast(BitCastInst &CI);
237 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
238 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
239 Instruction *FoldSelectIntoOp(SelectInst &SI, Value *, Value *);
240 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
241 Value *A, Value *B, Instruction &Outer,
242 SelectPatternFlavor SPF2, Value *C);
243 Instruction *visitSelectInst(SelectInst &SI);
244 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
245 Instruction *visitCallInst(CallInst &CI);
246 Instruction *visitInvokeInst(InvokeInst &II);
248 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
249 Instruction *visitPHINode(PHINode &PN);
250 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
251 Instruction *visitAllocaInst(AllocaInst &AI);
252 Instruction *visitAllocSite(Instruction &FI);
253 Instruction *visitFree(CallInst &FI);
254 Instruction *visitLoadInst(LoadInst &LI);
255 Instruction *visitStoreInst(StoreInst &SI);
256 Instruction *visitBranchInst(BranchInst &BI);
257 Instruction *visitSwitchInst(SwitchInst &SI);
258 Instruction *visitReturnInst(ReturnInst &RI);
259 Instruction *visitInsertValueInst(InsertValueInst &IV);
260 Instruction *visitInsertElementInst(InsertElementInst &IE);
261 Instruction *visitExtractElementInst(ExtractElementInst &EI);
262 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
263 Instruction *visitExtractValueInst(ExtractValueInst &EV);
264 Instruction *visitLandingPadInst(LandingPadInst &LI);
266 // visitInstruction - Specify what to return for unhandled instructions...
267 Instruction *visitInstruction(Instruction &I) { return nullptr; }
269 // True when DB dominates all uses of DI execpt UI.
270 // UI must be in the same block as DI.
271 // The routine checks that the DI parent and DB are different.
272 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
273 const BasicBlock *DB) const;
275 // Replace select with select operand SIOpd in SI-ICmp sequence when possible
276 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
277 const unsigned SIOpd);
280 bool ShouldChangeType(Type *From, Type *To) const;
281 Value *dyn_castNegVal(Value *V) const;
282 Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
283 Type *FindElementAtOffset(Type *PtrTy, int64_t Offset,
284 SmallVectorImpl<Value *> &NewIndices);
285 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
287 /// \brief Classify whether a cast is worth optimizing.
289 /// Returns true if the cast from "V to Ty" actually results in any code
290 /// being generated and is interesting to optimize out. If the cast can be
291 /// eliminated by some other simple transformation, we prefer to do the
292 /// simplification first.
293 bool ShouldOptimizeCast(Instruction::CastOps opcode, const Value *V,
296 Instruction *visitCallSite(CallSite CS);
297 Instruction *tryOptimizeCall(CallInst *CI, const DataLayout *DL);
298 bool transformConstExprCastCall(CallSite CS);
299 Instruction *transformCallThroughTrampoline(CallSite CS,
300 IntrinsicInst *Tramp);
301 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
302 bool DoXform = true);
303 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
304 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction *CxtI);
305 bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
306 bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
307 bool WillNotOverflowSignedMul(Value *LHS, Value *RHS, Instruction *CxtI);
308 Value *EmitGEPOffset(User *GEP);
309 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
310 Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
313 /// \brief Inserts an instruction \p New before instruction \p Old
315 /// Also adds the new instruction to the worklist and returns \p New so that
316 /// it is suitable for use as the return from the visitation patterns.
317 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
318 assert(New && !New->getParent() &&
319 "New instruction already inserted into a basic block!");
320 BasicBlock *BB = Old.getParent();
321 BB->getInstList().insert(&Old, New); // Insert inst
326 /// \brief Same as InsertNewInstBefore, but also sets the debug loc.
327 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
328 New->setDebugLoc(Old.getDebugLoc());
329 return InsertNewInstBefore(New, Old);
332 /// \brief A combiner-aware RAUW-like routine.
334 /// This method is to be used when an instruction is found to be dead,
335 /// replacable with another preexisting expression. Here we add all uses of
336 /// I to the worklist, replace all uses of I with the new value, then return
337 /// I, so that the inst combiner will know that I was modified.
338 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
339 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
341 // If we are replacing the instruction with itself, this must be in a
342 // segment of unreachable code, so just clobber the instruction.
344 V = UndefValue::get(I.getType());
346 DEBUG(dbgs() << "IC: Replacing " << I << "\n"
347 << " with " << *V << '\n');
349 I.replaceAllUsesWith(V);
353 /// Creates a result tuple for an overflow intrinsic \p II with a given
354 /// \p Result and a constant \p Overflow value. If \p ReUseName is true the
355 /// \p Result's name is taken from \p II.
356 Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
357 bool Overflow, bool ReUseName = true) {
359 Result->takeName(II);
360 Constant *V[] = {UndefValue::get(Result->getType()),
361 Overflow ? Builder->getTrue() : Builder->getFalse()};
362 StructType *ST = cast<StructType>(II->getType());
363 Constant *Struct = ConstantStruct::get(ST, V);
364 return InsertValueInst::Create(Struct, Result, 0);
367 /// \brief Combiner aware instruction erasure.
369 /// When dealing with an instruction that has side effects or produces a void
370 /// value, we can't rely on DCE to delete the instruction. Instead, visit
371 /// methods should return the value returned by this function.
372 Instruction *EraseInstFromFunction(Instruction &I) {
373 DEBUG(dbgs() << "IC: ERASE " << I << '\n');
375 assert(I.use_empty() && "Cannot erase instruction that is used!");
376 // Make sure that we reprocess all operands now that we reduced their
378 if (I.getNumOperands() < 8) {
379 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
380 if (Instruction *Op = dyn_cast<Instruction>(*i))
386 return nullptr; // Don't do anything with FI
389 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
390 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
391 return llvm::computeKnownBits(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
395 bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth = 0,
396 Instruction *CxtI = nullptr) const {
397 return llvm::MaskedValueIsZero(V, Mask, DL, Depth, AC, CxtI, DT);
399 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0,
400 Instruction *CxtI = nullptr) const {
401 return llvm::ComputeNumSignBits(Op, DL, Depth, AC, CxtI, DT);
403 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
404 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
405 return llvm::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
408 OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
409 const Instruction *CxtI) {
410 return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, AC, CxtI, DT);
412 OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
413 const Instruction *CxtI) {
414 return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, AC, CxtI, DT);
418 /// \brief Performs a few simplifications for operators which are associative
420 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
422 /// \brief Tries to simplify binary operations which some other binary
423 /// operation distributes over.
425 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
426 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
427 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
428 /// value, or null if it didn't simplify.
429 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
431 /// \brief Attempts to replace V with a simpler value based on the demanded
433 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, APInt &KnownZero,
434 APInt &KnownOne, unsigned Depth,
435 Instruction *CxtI = nullptr);
436 bool SimplifyDemandedBits(Use &U, APInt DemandedMask, APInt &KnownZero,
437 APInt &KnownOne, unsigned Depth = 0);
438 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
439 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
440 Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
441 APInt DemandedMask, APInt &KnownZero,
444 /// \brief Tries to simplify operands to an integer instruction based on its
446 bool SimplifyDemandedInstructionBits(Instruction &Inst);
448 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
449 APInt &UndefElts, unsigned Depth = 0);
451 Value *SimplifyVectorOp(BinaryOperator &Inst);
452 Value *SimplifyBSwap(BinaryOperator &Inst);
454 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
455 // which has a PHI node as operand #0, see if we can fold the instruction
456 // into the PHI (which is only possible if all operands to the PHI are
459 Instruction *FoldOpIntoPhi(Instruction &I);
461 /// \brief Try to rotate an operation below a PHI node, using PHI nodes for
463 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
464 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
465 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
466 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
468 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
469 ConstantInt *AndRHS, BinaryOperator &TheAnd);
471 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
472 bool isSub, Instruction &I);
473 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, bool isSigned,
475 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
476 Instruction *MatchBSwap(BinaryOperator &I);
477 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
478 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
479 Instruction *SimplifyMemSet(MemSetInst *MI);
481 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
483 /// \brief Returns a value X such that Val = X * Scale, or null if none.
485 /// If the multiplication is known not to overflow then NoSignedWrap is set.
486 Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
489 } // end namespace llvm.