1 //===- InstCombine.h - Main InstCombine pass definition -------------------===//
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 INSTCOMBINE_INSTCOMBINE_H
11 #define INSTCOMBINE_INSTCOMBINE_H
13 #include "InstCombineWorklist.h"
14 #include "llvm/Pass.h"
15 #include "llvm/Analysis/ValueTracking.h"
16 #include "llvm/Support/IRBuilder.h"
17 #include "llvm/Support/InstVisitor.h"
18 #include "llvm/Support/TargetFolder.h"
27 /// SelectPatternFlavor - We can match a variety of different patterns for
28 /// select operations.
29 enum SelectPatternFlavor {
36 /// getComplexity: Assign a complexity or rank value to LLVM Values...
37 /// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
38 static inline unsigned getComplexity(Value *V) {
39 if (isa<Instruction>(V)) {
40 if (BinaryOperator::isNeg(V) ||
41 BinaryOperator::isFNeg(V) ||
42 BinaryOperator::isNot(V))
46 if (isa<Argument>(V)) return 3;
47 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
51 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
52 /// just like the normal insertion helper, but also adds any new instructions
53 /// to the instcombine worklist.
54 class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
55 : public IRBuilderDefaultInserter<true> {
56 InstCombineWorklist &Worklist;
58 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
60 void InsertHelper(Instruction *I, const Twine &Name,
61 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
62 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
67 /// InstCombiner - The -instcombine pass.
68 class LLVM_LIBRARY_VISIBILITY InstCombiner
69 : public FunctionPass,
70 public InstVisitor<InstCombiner, Instruction*> {
72 bool MustPreserveLCSSA;
75 /// Worklist - All of the instructions that need to be simplified.
76 InstCombineWorklist Worklist;
78 /// Builder - This is an IRBuilder that automatically inserts new
79 /// instructions into the worklist when they are created.
80 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
83 static char ID; // Pass identification, replacement for typeid
84 InstCombiner() : FunctionPass(ID), TD(0), Builder(0) {
85 initializeInstCombinerPass(*PassRegistry::getPassRegistry());
89 virtual bool runOnFunction(Function &F);
91 bool DoOneIteration(Function &F, unsigned ItNum);
93 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
95 TargetData *getTargetData() const { return TD; }
97 // Visitation implementation - Implement instruction combining for different
98 // instruction types. The semantics are as follows:
100 // null - No change was made
101 // I - Change was made, I is still valid, I may be dead though
102 // otherwise - Change was made, replace I with returned instruction
104 Instruction *visitAdd(BinaryOperator &I);
105 Instruction *visitFAdd(BinaryOperator &I);
106 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
107 Instruction *visitSub(BinaryOperator &I);
108 Instruction *visitFSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitFMul(BinaryOperator &I);
111 Instruction *visitURem(BinaryOperator &I);
112 Instruction *visitSRem(BinaryOperator &I);
113 Instruction *visitFRem(BinaryOperator &I);
114 bool SimplifyDivRemOfSelect(BinaryOperator &I);
115 Instruction *commonRemTransforms(BinaryOperator &I);
116 Instruction *commonIRemTransforms(BinaryOperator &I);
117 Instruction *commonDivTransforms(BinaryOperator &I);
118 Instruction *commonIDivTransforms(BinaryOperator &I);
119 Instruction *visitUDiv(BinaryOperator &I);
120 Instruction *visitSDiv(BinaryOperator &I);
121 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
122 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
123 Instruction *visitAnd(BinaryOperator &I);
124 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS);
125 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
126 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
127 Value *A, Value *B, Value *C);
128 Instruction *visitOr (BinaryOperator &I);
129 Instruction *visitXor(BinaryOperator &I);
130 Instruction *visitShl(BinaryOperator &I);
131 Instruction *visitAShr(BinaryOperator &I);
132 Instruction *visitLShr(BinaryOperator &I);
133 Instruction *commonShiftTransforms(BinaryOperator &I);
134 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
136 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
137 GlobalVariable *GV, CmpInst &ICI,
138 ConstantInt *AndCst = 0);
139 Instruction *visitFCmpInst(FCmpInst &I);
140 Instruction *visitICmpInst(ICmpInst &I);
141 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
142 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
145 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
146 ConstantInt *DivRHS);
147 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
148 ICmpInst::Predicate Pred, Value *TheAdd);
149 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
150 ICmpInst::Predicate Cond, Instruction &I);
151 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
153 Instruction *commonCastTransforms(CastInst &CI);
154 Instruction *commonPointerCastTransforms(CastInst &CI);
155 Instruction *visitTrunc(TruncInst &CI);
156 Instruction *visitZExt(ZExtInst &CI);
157 Instruction *visitSExt(SExtInst &CI);
158 Instruction *visitFPTrunc(FPTruncInst &CI);
159 Instruction *visitFPExt(CastInst &CI);
160 Instruction *visitFPToUI(FPToUIInst &FI);
161 Instruction *visitFPToSI(FPToSIInst &FI);
162 Instruction *visitUIToFP(CastInst &CI);
163 Instruction *visitSIToFP(CastInst &CI);
164 Instruction *visitPtrToInt(PtrToIntInst &CI);
165 Instruction *visitIntToPtr(IntToPtrInst &CI);
166 Instruction *visitBitCast(BitCastInst &CI);
167 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
169 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
170 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
171 Value *A, Value *B, Instruction &Outer,
172 SelectPatternFlavor SPF2, Value *C);
173 Instruction *visitSelectInst(SelectInst &SI);
174 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
175 Instruction *visitCallInst(CallInst &CI);
176 Instruction *visitInvokeInst(InvokeInst &II);
178 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
179 Instruction *visitPHINode(PHINode &PN);
180 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
181 Instruction *visitAllocaInst(AllocaInst &AI);
182 Instruction *visitMalloc(Instruction &FI);
183 Instruction *visitFree(CallInst &FI);
184 Instruction *visitLoadInst(LoadInst &LI);
185 Instruction *visitStoreInst(StoreInst &SI);
186 Instruction *visitBranchInst(BranchInst &BI);
187 Instruction *visitSwitchInst(SwitchInst &SI);
188 Instruction *visitInsertElementInst(InsertElementInst &IE);
189 Instruction *visitExtractElementInst(ExtractElementInst &EI);
190 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
191 Instruction *visitExtractValueInst(ExtractValueInst &EV);
193 // visitInstruction - Specify what to return for unhandled instructions...
194 Instruction *visitInstruction(Instruction &I) { return 0; }
197 bool ShouldChangeType(const Type *From, const Type *To) const;
198 Value *dyn_castNegVal(Value *V) const;
199 Value *dyn_castFNegVal(Value *V) const;
200 const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
201 SmallVectorImpl<Value*> &NewIndices);
202 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
204 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
205 /// results in any code being generated and is interesting to optimize out. If
206 /// the cast can be eliminated by some other simple transformation, we prefer
207 /// to do the simplification first.
208 bool ShouldOptimizeCast(Instruction::CastOps opcode,const Value *V,
211 Instruction *visitCallSite(CallSite CS);
212 Instruction *tryOptimizeCall(CallInst *CI, const TargetData *TD);
213 bool transformConstExprCastCall(CallSite CS);
214 Instruction *transformCallThroughTrampoline(CallSite CS);
215 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
216 bool DoXform = true);
217 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
218 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
219 Value *EmitGEPOffset(User *GEP);
222 // InsertNewInstBefore - insert an instruction New before instruction Old
223 // in the program. Add the new instruction to the worklist.
225 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
226 assert(New && New->getParent() == 0 &&
227 "New instruction already inserted into a basic block!");
228 BasicBlock *BB = Old.getParent();
229 BB->getInstList().insert(&Old, New); // Insert inst
234 // ReplaceInstUsesWith - This method is to be used when an instruction is
235 // found to be dead, replacable with another preexisting expression. Here
236 // we add all uses of I to the worklist, replace all uses of I with the new
237 // value, then return I, so that the inst combiner will know that I was
240 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
241 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
243 // If we are replacing the instruction with itself, this must be in a
244 // segment of unreachable code, so just clobber the instruction.
246 V = UndefValue::get(I.getType());
248 I.replaceAllUsesWith(V);
252 // EraseInstFromFunction - When dealing with an instruction that has side
253 // effects or produces a void value, we can't rely on DCE to delete the
254 // instruction. Instead, visit methods should return the value returned by
256 Instruction *EraseInstFromFunction(Instruction &I) {
257 DEBUG(errs() << "IC: ERASE " << I << '\n');
259 assert(I.use_empty() && "Cannot erase instruction that is used!");
260 // Make sure that we reprocess all operands now that we reduced their
262 if (I.getNumOperands() < 8) {
263 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
264 if (Instruction *Op = dyn_cast<Instruction>(*i))
270 return 0; // Don't do anything with FI
273 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
274 APInt &KnownOne, unsigned Depth = 0) const {
275 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
278 bool MaskedValueIsZero(Value *V, const APInt &Mask,
279 unsigned Depth = 0) const {
280 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
282 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
283 return llvm::ComputeNumSignBits(Op, TD, Depth);
288 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
289 /// operators which are associative or commutative.
290 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
292 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
293 /// which some other binary operation distributes over either by factorizing
294 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
295 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
296 /// a win). Returns the simplified value, or null if it didn't simplify.
297 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
299 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
300 /// based on the demanded bits.
301 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
302 APInt& KnownZero, APInt& KnownOne,
304 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
305 APInt& KnownZero, APInt& KnownOne,
308 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
309 /// SimplifyDemandedBits knows about. See if the instruction has any
310 /// properties that allow us to simplify its operands.
311 bool SimplifyDemandedInstructionBits(Instruction &Inst);
313 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
314 APInt& UndefElts, unsigned Depth = 0);
316 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
317 // which has a PHI node as operand #0, see if we can fold the instruction
318 // into the PHI (which is only possible if all operands to the PHI are
321 Instruction *FoldOpIntoPhi(Instruction &I);
323 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
324 // operator and they all are only used by the PHI, PHI together their
325 // inputs, and do the operation once, to the result of the PHI.
326 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
327 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
328 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
329 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
332 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
333 ConstantInt *AndRHS, BinaryOperator &TheAnd);
335 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
336 bool isSub, Instruction &I);
337 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
338 bool isSigned, bool Inside);
339 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
340 Instruction *MatchBSwap(BinaryOperator &I);
341 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
342 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
343 Instruction *SimplifyMemSet(MemSetInst *MI);
346 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
351 } // end namespace llvm.