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