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 "llvm/Analysis/AssumptionCache.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/TargetFolder.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/IRBuilder.h"
24 #include "llvm/IR/InstVisitor.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Operator.h"
27 #include "llvm/IR/PatternMatch.h"
28 #include "llvm/Pass.h"
29 #include "llvm/Transforms/InstCombine/InstCombineWorklist.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 Return true if the specified value is free to invert (apply ~ to).
84 /// This happens in cases where the ~ can be eliminated. If WillInvertAllUses
85 /// is true, work under the assumption that the caller intends to remove all
86 /// uses of V and only keep uses of ~V.
88 static inline bool IsFreeToInvert(Value *V, bool WillInvertAllUses) {
90 if (BinaryOperator::isNot(V))
93 // Constants can be considered to be not'ed values.
94 if (isa<ConstantInt>(V))
97 // Compares can be inverted if all of their uses are being modified to use the
100 return WillInvertAllUses;
102 // If `V` is of the form `A + Constant` then `-1 - V` can be folded into `(-1
103 // - Constant) - A` if we are willing to invert all of the uses.
104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V))
105 if (BO->getOpcode() == Instruction::Add ||
106 BO->getOpcode() == Instruction::Sub)
107 if (isa<Constant>(BO->getOperand(0)) || isa<Constant>(BO->getOperand(1)))
108 return WillInvertAllUses;
113 /// \brief An IRBuilder inserter that adds new instructions to the instcombine
115 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
116 : public IRBuilderDefaultInserter<true> {
117 InstCombineWorklist &Worklist;
121 InstCombineIRInserter(InstCombineWorklist &WL, AssumptionCache *AC)
122 : Worklist(WL), AC(AC) {}
124 void InsertHelper(Instruction *I, const Twine &Name, BasicBlock *BB,
125 BasicBlock::iterator InsertPt) const {
126 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
129 using namespace llvm::PatternMatch;
130 if (match(I, m_Intrinsic<Intrinsic::assume>()))
131 AC->registerAssumption(cast<CallInst>(I));
135 /// \brief The core instruction combiner logic.
137 /// This class provides both the logic to recursively visit instructions and
138 /// combine them, as well as the pass infrastructure for running this as part
139 /// of the LLVM pass pipeline.
140 class LLVM_LIBRARY_VISIBILITY InstCombiner
141 : public InstVisitor<InstCombiner, Instruction *> {
142 // FIXME: These members shouldn't be public.
144 /// \brief A worklist of the instructions that need to be simplified.
145 InstCombineWorklist &Worklist;
147 /// \brief An IRBuilder that automatically inserts new instructions into the
149 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
153 // Mode in which we are running the combiner.
154 const bool MinimizeSize;
156 // Required analyses.
157 // FIXME: These can never be null and should be references.
159 TargetLibraryInfo *TLI;
161 const DataLayout &DL;
163 // Optional analyses. When non-null, these can both be used to do better
164 // combining and will be updated to reflect any changes.
170 InstCombiner(InstCombineWorklist &Worklist, BuilderTy *Builder,
171 bool MinimizeSize, AssumptionCache *AC, TargetLibraryInfo *TLI,
172 DominatorTree *DT, const DataLayout &DL, LoopInfo *LI)
173 : Worklist(Worklist), Builder(Builder), MinimizeSize(MinimizeSize),
174 AC(AC), TLI(TLI), DT(DT), DL(DL), LI(LI), MadeIRChange(false) {}
176 /// \brief Run the combiner over the entire worklist until it is empty.
178 /// \returns true if the IR is changed.
181 AssumptionCache *getAssumptionCache() const { return AC; }
183 const DataLayout &getDataLayout() const { return DL; }
185 DominatorTree *getDominatorTree() const { return DT; }
187 LoopInfo *getLoopInfo() const { return LI; }
189 TargetLibraryInfo *getTargetLibraryInfo() const { return TLI; }
191 // Visitation implementation - Implement instruction combining for different
192 // instruction types. The semantics are as follows:
194 // null - No change was made
195 // I - Change was made, I is still valid, I may be dead though
196 // otherwise - Change was made, replace I with returned instruction
198 Instruction *visitAdd(BinaryOperator &I);
199 Instruction *visitFAdd(BinaryOperator &I);
200 Value *OptimizePointerDifference(Value *LHS, Value *RHS, Type *Ty);
201 Instruction *visitSub(BinaryOperator &I);
202 Instruction *visitFSub(BinaryOperator &I);
203 Instruction *visitMul(BinaryOperator &I);
204 Value *foldFMulConst(Instruction *FMulOrDiv, Constant *C,
205 Instruction *InsertBefore);
206 Instruction *visitFMul(BinaryOperator &I);
207 Instruction *visitURem(BinaryOperator &I);
208 Instruction *visitSRem(BinaryOperator &I);
209 Instruction *visitFRem(BinaryOperator &I);
210 bool SimplifyDivRemOfSelect(BinaryOperator &I);
211 Instruction *commonRemTransforms(BinaryOperator &I);
212 Instruction *commonIRemTransforms(BinaryOperator &I);
213 Instruction *commonDivTransforms(BinaryOperator &I);
214 Instruction *commonIDivTransforms(BinaryOperator &I);
215 Instruction *visitUDiv(BinaryOperator &I);
216 Instruction *visitSDiv(BinaryOperator &I);
217 Instruction *visitFDiv(BinaryOperator &I);
218 Value *simplifyRangeCheck(ICmpInst *Cmp0, ICmpInst *Cmp1, bool Inverted);
219 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
220 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
221 Instruction *visitAnd(BinaryOperator &I);
222 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS, Instruction *CxtI);
223 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
224 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op, Value *A,
226 Instruction *FoldXorWithConstants(BinaryOperator &I, Value *Op, Value *A,
228 Instruction *visitOr(BinaryOperator &I);
229 Instruction *visitXor(BinaryOperator &I);
230 Instruction *visitShl(BinaryOperator &I);
231 Instruction *visitAShr(BinaryOperator &I);
232 Instruction *visitLShr(BinaryOperator &I);
233 Instruction *commonShiftTransforms(BinaryOperator &I);
234 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
236 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
237 GlobalVariable *GV, CmpInst &ICI,
238 ConstantInt *AndCst = nullptr);
239 Instruction *visitFCmpInst(FCmpInst &I);
240 Instruction *visitICmpInst(ICmpInst &I);
241 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
242 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI, Instruction *LHS,
244 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
245 ConstantInt *DivRHS);
246 Instruction *FoldICmpShrCst(ICmpInst &ICI, BinaryOperator *DivI,
247 ConstantInt *DivRHS);
248 Instruction *FoldICmpCstShrCst(ICmpInst &I, Value *Op, Value *A,
249 ConstantInt *CI1, ConstantInt *CI2);
250 Instruction *FoldICmpCstShlCst(ICmpInst &I, Value *Op, Value *A,
251 ConstantInt *CI1, ConstantInt *CI2);
252 Instruction *FoldICmpAddOpCst(Instruction &ICI, Value *X, ConstantInt *CI,
253 ICmpInst::Predicate Pred);
254 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
255 ICmpInst::Predicate Cond, Instruction &I);
256 Instruction *FoldShiftByConstant(Value *Op0, Constant *Op1,
258 Instruction *commonCastTransforms(CastInst &CI);
259 Instruction *commonPointerCastTransforms(CastInst &CI);
260 Instruction *visitTrunc(TruncInst &CI);
261 Instruction *visitZExt(ZExtInst &CI);
262 Instruction *visitSExt(SExtInst &CI);
263 Instruction *visitFPTrunc(FPTruncInst &CI);
264 Instruction *visitFPExt(CastInst &CI);
265 Instruction *visitFPToUI(FPToUIInst &FI);
266 Instruction *visitFPToSI(FPToSIInst &FI);
267 Instruction *visitUIToFP(CastInst &CI);
268 Instruction *visitSIToFP(CastInst &CI);
269 Instruction *visitPtrToInt(PtrToIntInst &CI);
270 Instruction *visitIntToPtr(IntToPtrInst &CI);
271 Instruction *visitBitCast(BitCastInst &CI);
272 Instruction *visitAddrSpaceCast(AddrSpaceCastInst &CI);
273 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI, Instruction *FI);
274 Instruction *FoldSelectIntoOp(SelectInst &SI, Value *, Value *);
275 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
276 Value *A, Value *B, Instruction &Outer,
277 SelectPatternFlavor SPF2, Value *C);
278 Instruction *FoldItoFPtoI(Instruction &FI);
279 Instruction *visitSelectInst(SelectInst &SI);
280 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
281 Instruction *visitCallInst(CallInst &CI);
282 Instruction *visitInvokeInst(InvokeInst &II);
284 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
285 Instruction *visitPHINode(PHINode &PN);
286 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
287 Instruction *visitAllocaInst(AllocaInst &AI);
288 Instruction *visitAllocSite(Instruction &FI);
289 Instruction *visitFree(CallInst &FI);
290 Instruction *visitLoadInst(LoadInst &LI);
291 Instruction *visitStoreInst(StoreInst &SI);
292 Instruction *visitBranchInst(BranchInst &BI);
293 Instruction *visitSwitchInst(SwitchInst &SI);
294 Instruction *visitReturnInst(ReturnInst &RI);
295 Instruction *visitInsertValueInst(InsertValueInst &IV);
296 Instruction *visitInsertElementInst(InsertElementInst &IE);
297 Instruction *visitExtractElementInst(ExtractElementInst &EI);
298 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
299 Instruction *visitExtractValueInst(ExtractValueInst &EV);
300 Instruction *visitLandingPadInst(LandingPadInst &LI);
302 // visitInstruction - Specify what to return for unhandled instructions...
303 Instruction *visitInstruction(Instruction &I) { return nullptr; }
305 // True when DB dominates all uses of DI execpt UI.
306 // UI must be in the same block as DI.
307 // The routine checks that the DI parent and DB are different.
308 bool dominatesAllUses(const Instruction *DI, const Instruction *UI,
309 const BasicBlock *DB) const;
311 // Replace select with select operand SIOpd in SI-ICmp sequence when possible
312 bool replacedSelectWithOperand(SelectInst *SI, const ICmpInst *Icmp,
313 const unsigned SIOpd);
316 bool ShouldChangeType(Type *From, Type *To) const;
317 Value *dyn_castNegVal(Value *V) const;
318 Value *dyn_castFNegVal(Value *V, bool NoSignedZero = false) const;
319 Type *FindElementAtOffset(Type *PtrTy, int64_t Offset,
320 SmallVectorImpl<Value *> &NewIndices);
321 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
323 /// \brief Classify whether a cast is worth optimizing.
325 /// Returns true if the cast from "V to Ty" actually results in any code
326 /// being generated and is interesting to optimize out. If the cast can be
327 /// eliminated by some other simple transformation, we prefer to do the
328 /// simplification first.
329 bool ShouldOptimizeCast(Instruction::CastOps opcode, const Value *V,
332 Instruction *visitCallSite(CallSite CS);
333 Instruction *tryOptimizeCall(CallInst *CI);
334 bool transformConstExprCastCall(CallSite CS);
335 Instruction *transformCallThroughTrampoline(CallSite CS,
336 IntrinsicInst *Tramp);
337 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
338 bool DoXform = true);
339 Instruction *transformSExtICmp(ICmpInst *ICI, Instruction &CI);
340 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS, Instruction &CxtI);
341 bool WillNotOverflowSignedSub(Value *LHS, Value *RHS, Instruction &CxtI);
342 bool WillNotOverflowUnsignedSub(Value *LHS, Value *RHS, Instruction &CxtI);
343 bool WillNotOverflowSignedMul(Value *LHS, Value *RHS, Instruction &CxtI);
344 Value *EmitGEPOffset(User *GEP);
345 Instruction *scalarizePHI(ExtractElementInst &EI, PHINode *PN);
346 Value *EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask);
349 /// \brief Inserts an instruction \p New before instruction \p Old
351 /// Also adds the new instruction to the worklist and returns \p New so that
352 /// it is suitable for use as the return from the visitation patterns.
353 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
354 assert(New && !New->getParent() &&
355 "New instruction already inserted into a basic block!");
356 BasicBlock *BB = Old.getParent();
357 BB->getInstList().insert(&Old, New); // Insert inst
362 /// \brief Same as InsertNewInstBefore, but also sets the debug loc.
363 Instruction *InsertNewInstWith(Instruction *New, Instruction &Old) {
364 New->setDebugLoc(Old.getDebugLoc());
365 return InsertNewInstBefore(New, Old);
368 /// \brief A combiner-aware RAUW-like routine.
370 /// This method is to be used when an instruction is found to be dead,
371 /// replacable with another preexisting expression. Here we add all uses of
372 /// I to the worklist, replace all uses of I with the new value, then return
373 /// I, so that the inst combiner will know that I was modified.
374 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
375 // If there are no uses to replace, then we return nullptr to indicate that
376 // no changes were made to the program.
377 if (I.use_empty()) return nullptr;
379 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
381 // If we are replacing the instruction with itself, this must be in a
382 // segment of unreachable code, so just clobber the instruction.
384 V = UndefValue::get(I.getType());
386 DEBUG(dbgs() << "IC: Replacing " << I << "\n"
387 << " with " << *V << '\n');
389 I.replaceAllUsesWith(V);
393 /// Creates a result tuple for an overflow intrinsic \p II with a given
394 /// \p Result and a constant \p Overflow value. If \p ReUseName is true the
395 /// \p Result's name is taken from \p II.
396 Instruction *CreateOverflowTuple(IntrinsicInst *II, Value *Result,
397 bool Overflow, bool ReUseName = true) {
399 Result->takeName(II);
400 Constant *V[] = {UndefValue::get(Result->getType()),
401 Overflow ? Builder->getTrue() : Builder->getFalse()};
402 StructType *ST = cast<StructType>(II->getType());
403 Constant *Struct = ConstantStruct::get(ST, V);
404 return InsertValueInst::Create(Struct, Result, 0);
407 /// \brief Combiner aware instruction erasure.
409 /// When dealing with an instruction that has side effects or produces a void
410 /// value, we can't rely on DCE to delete the instruction. Instead, visit
411 /// methods should return the value returned by this function.
412 Instruction *EraseInstFromFunction(Instruction &I) {
413 DEBUG(dbgs() << "IC: ERASE " << I << '\n');
415 assert(I.use_empty() && "Cannot erase instruction that is used!");
416 // Make sure that we reprocess all operands now that we reduced their
418 if (I.getNumOperands() < 8) {
419 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
420 if (Instruction *Op = dyn_cast<Instruction>(*i))
426 return nullptr; // Don't do anything with FI
429 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
430 unsigned Depth, Instruction *CxtI) const {
431 return llvm::computeKnownBits(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
435 bool MaskedValueIsZero(Value *V, const APInt &Mask, unsigned Depth = 0,
436 Instruction *CxtI = nullptr) const {
437 return llvm::MaskedValueIsZero(V, Mask, DL, Depth, AC, CxtI, DT);
439 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0,
440 Instruction *CxtI = nullptr) const {
441 return llvm::ComputeNumSignBits(Op, DL, Depth, AC, CxtI, DT);
443 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
444 unsigned Depth = 0, Instruction *CxtI = nullptr) const {
445 return llvm::ComputeSignBit(V, KnownZero, KnownOne, DL, Depth, AC, CxtI,
448 OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
449 const Instruction *CxtI) {
450 return llvm::computeOverflowForUnsignedMul(LHS, RHS, DL, AC, CxtI, DT);
452 OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
453 const Instruction *CxtI) {
454 return llvm::computeOverflowForUnsignedAdd(LHS, RHS, DL, AC, CxtI, DT);
458 /// \brief Performs a few simplifications for operators which are associative
460 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
462 /// \brief Tries to simplify binary operations which some other binary
463 /// operation distributes over.
465 /// It does this by either by factorizing out common terms (eg "(A*B)+(A*C)"
466 /// -> "A*(B+C)") or expanding out if this results in simplifications (eg: "A
467 /// & (B | C) -> (A&B) | (A&C)" if this is a win). Returns the simplified
468 /// value, or null if it didn't simplify.
469 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
471 /// \brief Attempts to replace V with a simpler value based on the demanded
473 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask, APInt &KnownZero,
474 APInt &KnownOne, unsigned Depth,
476 bool SimplifyDemandedBits(Use &U, APInt DemandedMask, APInt &KnownZero,
477 APInt &KnownOne, unsigned Depth = 0);
478 /// Helper routine of SimplifyDemandedUseBits. It tries to simplify demanded
479 /// bit for "r1 = shr x, c1; r2 = shl r1, c2" instruction sequence.
480 Value *SimplifyShrShlDemandedBits(Instruction *Lsr, Instruction *Sftl,
481 APInt DemandedMask, APInt &KnownZero,
484 /// \brief Tries to simplify operands to an integer instruction based on its
486 bool SimplifyDemandedInstructionBits(Instruction &Inst);
488 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
489 APInt &UndefElts, unsigned Depth = 0);
491 Value *SimplifyVectorOp(BinaryOperator &Inst);
492 Value *SimplifyBSwap(BinaryOperator &Inst);
494 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
495 // which has a PHI node as operand #0, see if we can fold the instruction
496 // into the PHI (which is only possible if all operands to the PHI are
499 Instruction *FoldOpIntoPhi(Instruction &I);
501 /// \brief Try to rotate an operation below a PHI node, using PHI nodes for
503 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
504 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
505 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
506 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
508 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
509 ConstantInt *AndRHS, BinaryOperator &TheAnd);
511 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
512 bool isSub, Instruction &I);
513 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi, bool isSigned,
515 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
516 Instruction *MatchBSwap(BinaryOperator &I);
517 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
518 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
519 Instruction *SimplifyMemSet(MemSetInst *MI);
521 Value *EvaluateInDifferentType(Value *V, Type *Ty, bool isSigned);
523 /// \brief Returns a value X such that Val = X * Scale, or null if none.
525 /// If the multiplication is known not to overflow then NoSignedWrap is set.
526 Value *Descale(Value *Val, APInt Scale, bool &NoSignedWrap);
529 } // end namespace llvm.