blob: 450e7f0a398bcb1ceec404f554b188aae45cd41a [file] [log] [blame]
Chris Lattnerac8f2fd2010-01-04 07:12:23 +00001//===- InstCombine.h - Main InstCombine pass definition -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef INSTCOMBINE_INSTCOMBINE_H
11#define INSTCOMBINE_INSTCOMBINE_H
12
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"
19
20namespace llvm {
21 class CallSite;
22 class TargetData;
Chris Lattner43fd9012010-01-05 05:21:26 +000023 class DbgDeclareInst;
24 class MemIntrinsic;
25 class MemSetInst;
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000026
27/// SelectPatternFlavor - We can match a variety of different patterns for
28/// select operations.
29enum SelectPatternFlavor {
30 SPF_UNKNOWN = 0,
31 SPF_SMIN, SPF_UMIN,
32 SPF_SMAX, SPF_UMAX
33 //SPF_ABS - TODO.
34};
Chris Lattner02446fc2010-01-04 07:37:31 +000035
36/// getComplexity: Assign a complexity or rank value to LLVM Values...
37/// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
38static inline unsigned getComplexity(Value *V) {
39 if (isa<Instruction>(V)) {
40 if (BinaryOperator::isNeg(V) ||
41 BinaryOperator::isFNeg(V) ||
42 BinaryOperator::isNot(V))
43 return 3;
44 return 4;
45 }
46 if (isa<Argument>(V)) return 3;
47 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
48}
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000049
50
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.
Duncan Sands16d8f8b2010-05-11 20:16:09 +000054class LLVM_LIBRARY_VISIBILITY InstCombineIRInserter
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000055 : public IRBuilderDefaultInserter<true> {
56 InstCombineWorklist &Worklist;
57public:
58 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
59
60 void InsertHelper(Instruction *I, const Twine &Name,
61 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
62 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
63 Worklist.Add(I);
64 }
65};
66
67/// InstCombiner - The -instcombine pass.
Duncan Sands16d8f8b2010-05-11 20:16:09 +000068class LLVM_LIBRARY_VISIBILITY InstCombiner
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000069 : public FunctionPass,
70 public InstVisitor<InstCombiner, Instruction*> {
71 TargetData *TD;
72 bool MustPreserveLCSSA;
73 bool MadeIRChange;
74public:
75 /// Worklist - All of the instructions that need to be simplified.
76 InstCombineWorklist Worklist;
77
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;
81 BuilderTy *Builder;
82
83 static char ID; // Pass identification, replacement for typeid
Owen Anderson081c34b2010-10-19 17:21:58 +000084 InstCombiner() : FunctionPass(ID), TD(0), Builder(0) {
85 initializeInstCombinerPass(*PassRegistry::getPassRegistry());
86 }
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000087
88public:
89 virtual bool runOnFunction(Function &F);
90
91 bool DoOneIteration(Function &F, unsigned ItNum);
92
Chris Lattnere0b4b722010-01-04 07:17:19 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
94
Chris Lattnerac8f2fd2010-01-04 07:12:23 +000095 TargetData *getTargetData() const { return TD; }
96
97 // Visitation implementation - Implement instruction combining for different
98 // instruction types. The semantics are as follows:
99 // Return Value:
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
103 //
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);
Frits van Bommel31726c12011-01-29 17:50:27 +0000121 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000122 Value *FoldAndOfICmps(ICmpInst *LHS, ICmpInst *RHS);
123 Value *FoldAndOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000124 Instruction *visitAnd(BinaryOperator &I);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000125 Value *FoldOrOfICmps(ICmpInst *LHS, ICmpInst *RHS);
126 Value *FoldOrOfFCmps(FCmpInst *LHS, FCmpInst *RHS);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000127 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
128 Value *A, Value *B, Value *C);
129 Instruction *visitOr (BinaryOperator &I);
130 Instruction *visitXor(BinaryOperator &I);
131 Instruction *visitShl(BinaryOperator &I);
132 Instruction *visitAShr(BinaryOperator &I);
133 Instruction *visitLShr(BinaryOperator &I);
134 Instruction *commonShiftTransforms(BinaryOperator &I);
135 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
136 Constant *RHSC);
137 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
138 GlobalVariable *GV, CmpInst &ICI,
139 ConstantInt *AndCst = 0);
140 Instruction *visitFCmpInst(FCmpInst &I);
141 Instruction *visitICmpInst(ICmpInst &I);
142 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
143 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
144 Instruction *LHS,
145 ConstantInt *RHS);
146 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
147 ConstantInt *DivRHS);
148 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
149 ICmpInst::Predicate Pred, Value *TheAdd);
150 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
151 ICmpInst::Predicate Cond, Instruction &I);
152 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
153 BinaryOperator &I);
154 Instruction *commonCastTransforms(CastInst &CI);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000155 Instruction *commonPointerCastTransforms(CastInst &CI);
156 Instruction *visitTrunc(TruncInst &CI);
157 Instruction *visitZExt(ZExtInst &CI);
158 Instruction *visitSExt(SExtInst &CI);
159 Instruction *visitFPTrunc(FPTruncInst &CI);
160 Instruction *visitFPExt(CastInst &CI);
161 Instruction *visitFPToUI(FPToUIInst &FI);
162 Instruction *visitFPToSI(FPToSIInst &FI);
163 Instruction *visitUIToFP(CastInst &CI);
164 Instruction *visitSIToFP(CastInst &CI);
165 Instruction *visitPtrToInt(PtrToIntInst &CI);
166 Instruction *visitIntToPtr(IntToPtrInst &CI);
167 Instruction *visitBitCast(BitCastInst &CI);
168 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
169 Instruction *FI);
170 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
171 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
172 Value *A, Value *B, Instruction &Outer,
173 SelectPatternFlavor SPF2, Value *C);
174 Instruction *visitSelectInst(SelectInst &SI);
175 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
176 Instruction *visitCallInst(CallInst &CI);
177 Instruction *visitInvokeInst(InvokeInst &II);
178
179 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
180 Instruction *visitPHINode(PHINode &PN);
181 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
182 Instruction *visitAllocaInst(AllocaInst &AI);
Duncan Sands1d9b9732010-05-27 19:09:06 +0000183 Instruction *visitMalloc(Instruction &FI);
Gabor Greif91697372010-06-24 12:21:15 +0000184 Instruction *visitFree(CallInst &FI);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000185 Instruction *visitLoadInst(LoadInst &LI);
186 Instruction *visitStoreInst(StoreInst &SI);
187 Instruction *visitBranchInst(BranchInst &BI);
188 Instruction *visitSwitchInst(SwitchInst &SI);
189 Instruction *visitInsertElementInst(InsertElementInst &IE);
190 Instruction *visitExtractElementInst(ExtractElementInst &EI);
191 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
192 Instruction *visitExtractValueInst(ExtractValueInst &EV);
193
194 // visitInstruction - Specify what to return for unhandled instructions...
195 Instruction *visitInstruction(Instruction &I) { return 0; }
196
197private:
Chris Lattner80f43d32010-01-04 07:53:58 +0000198 bool ShouldChangeType(const Type *From, const Type *To) const;
Chris Lattner02446fc2010-01-04 07:37:31 +0000199 Value *dyn_castNegVal(Value *V) const;
Chris Lattnerd12c27c2010-01-05 06:09:35 +0000200 Value *dyn_castFNegVal(Value *V) const;
Chris Lattner80f43d32010-01-04 07:53:58 +0000201 const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
202 SmallVectorImpl<Value*> &NewIndices);
203 Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI);
204
Chris Lattner8c5ad3a2010-02-11 06:26:33 +0000205 /// ShouldOptimizeCast - Return true if the cast from "V to Ty" actually
206 /// results in any code being generated and is interesting to optimize out. If
207 /// the cast can be eliminated by some other simple transformation, we prefer
208 /// to do the simplification first.
209 bool ShouldOptimizeCast(Instruction::CastOps opcode,const Value *V,
210 const Type *Ty);
Chris Lattner02446fc2010-01-04 07:37:31 +0000211
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000212 Instruction *visitCallSite(CallSite CS);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000213 Instruction *tryOptimizeCall(CallInst *CI, const TargetData *TD);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000214 bool transformConstExprCastCall(CallSite CS);
215 Instruction *transformCallThroughTrampoline(CallSite CS);
216 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
217 bool DoXform = true);
218 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
219 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
Chris Lattner02446fc2010-01-04 07:37:31 +0000220 Value *EmitGEPOffset(User *GEP);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000221
222public:
223 // InsertNewInstBefore - insert an instruction New before instruction Old
224 // in the program. Add the new instruction to the worklist.
225 //
226 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
227 assert(New && New->getParent() == 0 &&
228 "New instruction already inserted into a basic block!");
229 BasicBlock *BB = Old.getParent();
230 BB->getInstList().insert(&Old, New); // Insert inst
231 Worklist.Add(New);
232 return New;
233 }
234
235 // ReplaceInstUsesWith - This method is to be used when an instruction is
236 // found to be dead, replacable with another preexisting expression. Here
237 // we add all uses of I to the worklist, replace all uses of I with the new
238 // value, then return I, so that the inst combiner will know that I was
239 // modified.
240 //
241 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
242 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
243
244 // If we are replacing the instruction with itself, this must be in a
245 // segment of unreachable code, so just clobber the instruction.
246 if (&I == V)
247 V = UndefValue::get(I.getType());
248
249 I.replaceAllUsesWith(V);
250 return &I;
251 }
252
253 // EraseInstFromFunction - When dealing with an instruction that has side
254 // effects or produces a void value, we can't rely on DCE to delete the
255 // instruction. Instead, visit methods should return the value returned by
256 // this function.
257 Instruction *EraseInstFromFunction(Instruction &I) {
258 DEBUG(errs() << "IC: ERASE " << I << '\n');
259
260 assert(I.use_empty() && "Cannot erase instruction that is used!");
261 // Make sure that we reprocess all operands now that we reduced their
262 // use counts.
263 if (I.getNumOperands() < 8) {
264 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
265 if (Instruction *Op = dyn_cast<Instruction>(*i))
266 Worklist.Add(Op);
267 }
268 Worklist.Remove(&I);
269 I.eraseFromParent();
270 MadeIRChange = true;
271 return 0; // Don't do anything with FI
272 }
273
274 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
275 APInt &KnownOne, unsigned Depth = 0) const {
276 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
277 }
278
279 bool MaskedValueIsZero(Value *V, const APInt &Mask,
280 unsigned Depth = 0) const {
281 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
282 }
283 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
284 return llvm::ComputeNumSignBits(Op, TD, Depth);
285 }
286
287private:
288
Duncan Sands096aa792010-11-13 15:10:37 +0000289 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
290 /// operators which are associative or commutative.
291 bool SimplifyAssociativeOrCommutative(BinaryOperator &I);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000292
Duncan Sands37bf92b2010-12-22 13:36:08 +0000293 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
294 /// which some other binary operation distributes over either by factorizing
295 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
296 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
297 /// a win). Returns the simplified value, or null if it didn't simplify.
298 Value *SimplifyUsingDistributiveLaws(BinaryOperator &I);
Duncan Sands5057f382010-11-23 14:23:47 +0000299
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000300 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
301 /// based on the demanded bits.
302 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
303 APInt& KnownZero, APInt& KnownOne,
304 unsigned Depth);
305 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
306 APInt& KnownZero, APInt& KnownOne,
307 unsigned Depth=0);
308
309 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
310 /// SimplifyDemandedBits knows about. See if the instruction has any
311 /// properties that allow us to simplify its operands.
312 bool SimplifyDemandedInstructionBits(Instruction &Inst);
313
314 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
315 APInt& UndefElts, unsigned Depth = 0);
316
317 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
318 // which has a PHI node as operand #0, see if we can fold the instruction
319 // into the PHI (which is only possible if all operands to the PHI are
320 // constants).
321 //
Chris Lattner9922ccf2011-01-16 05:14:26 +0000322 Instruction *FoldOpIntoPhi(Instruction &I);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000323
324 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
325 // operator and they all are only used by the PHI, PHI together their
326 // inputs, and do the operation once, to the result of the PHI.
327 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
328 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
329 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
330 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
331
332
333 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
334 ConstantInt *AndRHS, BinaryOperator &TheAnd);
335
336 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
337 bool isSub, Instruction &I);
Chris Lattnerf34f48c2010-03-05 08:46:26 +0000338 Value *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
339 bool isSigned, bool Inside);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000340 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
341 Instruction *MatchBSwap(BinaryOperator &I);
342 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
343 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
344 Instruction *SimplifyMemSet(MemSetInst *MI);
345
346
347 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerac8f2fd2010-01-04 07:12:23 +0000348};
349
350
351
352} // end namespace llvm.
353
354#endif