1 //===- InstCombineInternal.h - InstCombine pass internals -------*- 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 //===----------------------------------------------------------------------===//
11 /// This file provides internal interfaces used to implement the InstCombine.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
16 #define LLVM_LIB_TRANSFORMS_INSTCOMBINE_INSTCOMBINEINTERNAL_H
18 #include "InstCombineWorklist.h"
19 #include "llvm/Analysis/AssumptionCache.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/TargetFolder.h"
22 #include "llvm/Analysis/ValueTracking.h"
23 #include "llvm/IR/Dominators.h"
24 #include "llvm/IR/IRBuilder.h"
25 #include "llvm/IR/InstVisitor.h"
26 #include "llvm/IR/IntrinsicInst.h"
27 #include "llvm/IR/Operator.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/Pass.h"
31 #define DEBUG_TYPE "instcombine"
37 class TargetLibraryInfo;
42 /// \brief Specific patterns of select instructions we can match.
43 enum SelectPatternFlavor {
53 /// \brief Assign a complexity or rank value to LLVM Values.
55 /// This routine maps IR values to various complexity ranks:
58 /// 2 -> Other non-instructions
60 /// 3 -> Unary operations
61 /// 4 -> Other instructions
62 static inline unsigned getComplexity(Value *V) {
63 if (isa<Instruction>(V)) {
64 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
65 BinaryOperator::isNot(V))
71 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
74 /// \brief Add one to a Constant
75 static inline Constant *AddOne(Constant *C) {
76 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
78 /// \brief Subtract one from a Constant
79 static inline Constant *SubOne(Constant *C) {
80 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
83 /// \brief An IRBuilder inserter that adds new instructions to the instcombine
85 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
86 : public IRBuilderDefaultInserter<true> {
87 InstCombineWorklist &Worklist;
91 InstCombineIRInserter(InstCombineWorklist &WL, AssumptionCache *AC)
92 : Worklist(WL), AC(AC) {}
94 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
95 BasicBlock::iterator InsertPt) const {
96 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
99 using namespace llvm::PatternMatch;
100 if (match(I, m_Intrinsic<Intrinsic::assume>()))
101 AC->registerAssumption(cast<CallInst>(I));
105 /// \brief The core instruction combiner logic.
107 /// This class provides both the logic to recursively visit instructions and
108 /// combine them, as well as the pass infrastructure for running this as part
109 /// of the LLVM pass pipeline.
110 class LLVM_LIBRARY_VISIBILITY InstCombiner
111 : public InstVisitor<InstCombiner, Instruction *> {
112 // FIXME: These members shouldn't be public.
114 /// \brief A worklist of the instructions that need to be simplified.
115 InstCombineWorklist &Worklist;
117 /// \brief An IRBuilder that automatically inserts new instructions into the
119 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
123 // Mode in which we are running the combiner.
124 const bool MinimizeSize;
126 // Required analyses.
127 // FIXME: These can never be null and should be references.
129 TargetLibraryInfo *TLI;
132 // Optional analyses. When non-null, these can both be used to do better
133 // combining and will be updated to reflect any changes.
134 const DataLayout *DL;
140 InstCombiner(InstCombineWorklist &Worklist, BuilderTy *Builder,
141 bool MinimizeSize, AssumptionCache *AC, TargetLibraryInfo *TLI,
142 DominatorTree *DT, const DataLayout *DL, LoopInfo *LI)
143 : Worklist(Worklist), Builder(Builder), MinimizeSize(MinimizeSize),
144 AC(AC), TLI(TLI), DT(DT), DL(DL), LI(LI), MadeIRChange(false) {}
146 /// \brief Run the combiner over the entire worklist until it is empty.
148 /// \returns true if the IR is changed.
151 AssumptionCache *getAssumptionCache() const { return AC; }
153 const DataLayout *getDataLayout() const { return DL; }
155 DominatorTree *getDominatorTree() const { return DT; }
157 LoopInfo *getLoopInfo() const { return LI; }
159 TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
164 // null - No change was made
165 // I - Change was made, I is still valid, I may be dead though
166 // otherwise - Change was made, replace I with returned instruction
168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitFAdd(BinaryOperator &I);
170 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
171 Instruction *visitSub(BinaryOperator &I);
172 Instruction *visitFSub(BinaryOperator &I);
173 Instruction *visitMul(BinaryOperator &I);
174 Value *foldFMulConst(Instruction *FMulOrDiv, Constant *C,
175 Instruction *InsertBefore);
176 Instruction *visitFMul(BinaryOperator &I);
177 Instruction *visitURem(BinaryOperator &I);
178 Instruction *visitSRem(BinaryOperator &I);
179 Instruction *visitFRem(BinaryOperator &I);
180 bool SimplifyDivRemOfSelect(BinaryOperator &I);
181 Instruction *commonRemTransforms(BinaryOperator &I);
182 Instruction *commonIRemTransforms(BinaryOperator &I);
183 Instruction *commonDivTransforms(BinaryOperator &I);
184 Instruction *commonIDivTransforms(BinaryOperator &I);
185 Instruction *visitUDiv(BinaryOperator &I);
186 Instruction *visitSDiv(BinaryOperator &I);
187 Instruction *visitFDiv(BinaryOperator &I);
188 Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
189 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
190 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
191 Instruction *visitAnd(BinaryOperator &I);
192 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI);
193 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
194 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, Value *A,
196 Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op, Value *A,
198 Instruction *visitOr(BinaryOperator &I);
199 Instruction *visitXor(BinaryOperator &I);
200 Instruction *visitShl(BinaryOperator &I);
201 Instruction *visitAShr(BinaryOperator &I);
202 Instruction *visitLShr(BinaryOperator &I);
203 Instruction *commonShiftTransforms(BinaryOperator &I);
204 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
206 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
207 GlobalVariable *GV, CmpInst &ICI,
208 ConstantInt *AndCst = nullptr);
209 Instruction *visitFCmpInst(FCmpInst &I);
210 Instruction *visitICmpInst(ICmpInst &I);
211 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
212 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHS,
214 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
215 ConstantInt *DivRHS);
216 Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
217 ConstantInt *DivRHS);
218 Instruction *FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
219 ConstantInt *CI1, ConstantInt *CI2);
220 Instruction *FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
221 ConstantInt *CI1, ConstantInt *CI2);
222 Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
223 ICmpInst::Predicate Pred);
224 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
225 ICmpInst::Predicate Cond, Instruction &I);
226 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
228 Instruction *commonCastTransforms(CastInst &CI);
229 Instruction *commonPointerCastTransforms(CastInst &CI);
230 Instruction *visitTrunc(TruncInst &CI);
231 Instruction *visitZExt(ZExtInst &CI);
232 Instruction *visitSExt(SExtInst &CI);
233 Instruction *visitFPTrunc(FPTruncInst &CI);
234 Instruction *visitFPExt(CastInst &CI);
235 Instruction *visitFPToUI(FPToUIInst &FI);
236 Instruction *visitFPToSI(FPToSIInst &FI);
237 Instruction *visitUIToFP(CastInst &CI);
238 Instruction *visitSIToFP(CastInst &CI);
239 Instruction *visitPtrToInt(PtrToIntInst &CI);
240 Instruction *visitIntToPtr(IntToPtrInst &CI);
241 Instruction *visitBitCast(BitCastInst &CI);
242 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
243 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
244 Instruction *FoldSelectIntoOp(SelectInst &SI, Value *, Value *);
245 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
246 Value *A, Value *B, Instruction &Outer,
247 SelectPatternFlavor SPF2, Value *C);
248 Instruction *visitSelectInst(SelectInst &SI);
249 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
250 Instruction *visitCallInst(CallInst &CI);
251 Instruction *visitInvokeInst(InvokeInst &II);
253 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
254 Instruction *visitPHINode(PHINode &PN);
255 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
256 Instruction *visitAllocaInst(AllocaInst &AI);
257 Instruction *visitAllocSite(Instruction &FI);
258 Instruction *visitFree(CallInst &FI);
259 Instruction *visitLoadInst(LoadInst &LI);
260 Instruction *visitStoreInst(StoreInst &SI);
261 Instruction *visitBranchInst(BranchInst &BI);
262 Instruction *visitSwitchInst(SwitchInst &SI);
263 Instruction *visitReturnInst(ReturnInst &RI);
264 Instruction *visitInsertValueInst(InsertValueInst &IV);
265 Instruction *visitInsertElementInst(InsertElementInst &IE);
266 Instruction *visitExtractElementInst(ExtractElementInst &EI);
267 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
268 Instruction *visitExtractValueInst(ExtractValueInst &EV);
269 Instruction *visitLandingPadInst(LandingPadInst &LI);
271 // visitInstruction - Specify what to return for unhandled instructions...
272 Instruction *visitInstruction(Instruction &I) { return nullptr; }
274 // True when DB dominates all uses of DI execpt UI.
275 // UI must be in the same block as DI.
276 // The routine checks that the DI parent and DB are different.
277 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
278 const BasicBlock *DB) const;
280 // Replace select with select operand SIOpd in SI-ICmp sequence when possible
281 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
282 const unsigned SIOpd);
285 bool ShouldChangeType(Type *From, Type *To) const;
286 Value *dyn_castNegVal(Value *V) const;
287 Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
288 Type *FindElementAtOffset(Type *PtrTy, int64_t Offset,
289 SmallVectorImpl<Value *> &NewIndices);
290 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
292 /// \brief Classify whether a cast is worth optimizing.
294 /// Returns true if the cast from "V to Ty" actually results in any code
295 /// being generated and is interesting to optimize out. If the cast can be
296 /// eliminated by some other simple transformation, we prefer to do the
297 /// simplification first.
298 bool ShouldOptimizeCast(Instruction::CastOps opcode, const Value *V,
301 Instruction *visitCallSite(CallSite CS);
302 Instruction *tryOptimizeCall(CallInst *CI, const DataLayout *DL);
303 bool transformConstExprCastCall(CallSite CS);
304 Instruction *transformCallThroughTrampoline(CallSite CS,
305 IntrinsicInst *Tramp);
306 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
307 bool DoXform = true);
308 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
309 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction *CxtI);
310 bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
311 bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction *CxtI);
312 bool WillNotOverflowSignedMul(Value *LHS, Value *RHS, Instruction *CxtI);
313 Value *EmitGEPOffset(User *GEP);
314 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
315 Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
318 /// \brief Inserts an instruction \p New before instruction \p Old
320 /// Also adds the new instruction to the worklist and returns \p New so that
321 /// it is suitable for use as the return from the visitation patterns.
322 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
323 assert(New && !New->getParent() &&
324 "New instruction already inserted into a basic block!");
325 BasicBlock *BB = Old.getParent();
326 BB->getInstList().insert(&Old, New); // Insert inst
331 /// \brief Same as InsertNewInstBefore, but also sets the debug loc.
332 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
333 New->setDebugLoc(Old.getDebugLoc());
334 return InsertNewInstBefore(New, Old);
337 /// \brief A combiner-aware RAUW-like routine.
339 /// This method is to be used when an instruction is found to be dead,
340 /// replacable with another preexisting expression. Here we add all uses of
341 /// I to the worklist, replace all uses of I with the new value, then return
342 /// I, so that the inst combiner will know that I was modified.
343 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
344 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
346 // If we are replacing the instruction with itself, this must be in a
347 // segment of unreachable code, so just clobber the instruction.
349 V = UndefValue::get(I.getType());
351 DEBUG(dbgs() << "IC: Replacing " << I << "\n"
352 << " with " << *V << '\n');
354 I.replaceAllUsesWith(V);
358 /// Creates a result tuple for an overflow intrinsic \p II with a given
359 /// \p Result and a constant \p Overflow value. If \p ReUseName is true the
360 /// \p Result's name is taken from \p II.
361 Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
362 bool Overflow, bool ReUseName = true) {
364 Result->takeName(II);
365 Constant *V[] = {UndefValue::get(Result->getType()),
366 Overflow ? Builder->getTrue() : Builder->getFalse()};
367 StructType *ST = cast<StructType>(II->getType());
368 Constant *Struct = ConstantStruct::get(ST, V);
369 return InsertValueInst::Create(Struct, Result, 0);
372 /// \brief Combiner aware instruction erasure.
374 /// When dealing with an instruction that has side effects or produces a void
375 /// value, we can't rely on DCE to delete the instruction. Instead, visit
376 /// methods should return the value returned by this function.
377 Instruction *EraseInstFromFunction(Instruction &I) {
378 DEBUG(dbgs() << "IC: ERASE " << I << '\n');
380 assert(I.use_empty() && "Cannot erase instruction that is used!");
381 // Make sure that we reprocess all operands now that we reduced their
383 if (I.getNumOperands() < 8) {
384 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
385 if (Instruction *Op = dyn_cast<Instruction>(*i))
391 return nullptr; // Don't do anything with FI
394 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
395 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
396 return llvm::computeKnownBits(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
400 bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth = 0,
401 Instruction *CxtI = nullptr) const {
402 return llvm::MaskedValueIsZero(V, Mask, DL, Depth, AC, CxtI, DT);
404 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0,
405 Instruction *CxtI = nullptr) const {
406 return llvm::ComputeNumSignBits(Op, DL, Depth, AC, CxtI, DT);
408 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
409 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
410 return llvm::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
413 OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
414 const Instruction *CxtI) {
415 return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, AC, CxtI, DT);
417 OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
418 const Instruction *CxtI) {
419 return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, AC, CxtI, DT);
423 /// \brief Performs a few simplifications for operators which are associative
425 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
427 /// \brief Tries to simplify binary operations which some other binary
428 /// operation distributes over.
430 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
431 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
432 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
433 /// value, or null if it didn't simplify.
434 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
436 /// \brief Attempts to replace V with a simpler value based on the demanded
438 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, APInt &KnownZero,
439 APInt &KnownOne, unsigned Depth,
440 Instruction *CxtI = nullptr);
441 bool SimplifyDemandedBits(Use &U, APInt DemandedMask, APInt &KnownZero,
442 APInt &KnownOne, unsigned Depth = 0);
443 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
444 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
445 Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
446 APInt DemandedMask, APInt &KnownZero,
449 /// \brief Tries to simplify operands to an integer instruction based on its
451 bool SimplifyDemandedInstructionBits(Instruction &Inst);
453 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
454 APInt &UndefElts, unsigned Depth = 0);
456 Value *SimplifyVectorOp(BinaryOperator &Inst);
457 Value *SimplifyBSwap(BinaryOperator &Inst);
459 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
460 // which has a PHI node as operand #0, see if we can fold the instruction
461 // into the PHI (which is only possible if all operands to the PHI are
464 Instruction *FoldOpIntoPhi(Instruction &I);
466 /// \brief Try to rotate an operation below a PHI node, using PHI nodes for
468 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
469 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
470 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
471 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
473 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
474 ConstantInt *AndRHS, BinaryOperator &TheAnd);
476 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
477 bool isSub, Instruction &I);
478 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, bool isSigned,
480 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
481 Instruction *MatchBSwap(BinaryOperator &I);
482 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
483 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
484 Instruction *SimplifyMemSet(MemSetInst *MI);
486 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
488 /// \brief Returns a value X such that Val = X * Scale, or null if none.
490 /// If the multiplication is known not to overflow then NoSignedWrap is set.
491 Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
494 } // end namespace llvm.