blob: cfeada349bd2b3088ea2494e85f29e2b07d07bcd [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Chris Lattnerca081252001-12-14 16:52:21 +00002//
3// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +00004// instructions. This pass does not modify the CFG This pass is where algebraic
5// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +00006//
7// This pass combines things like:
8// %Y = add int 1, %X
9// %Z = add int 1, %Y
10// into:
11// %Z = add int 2, %X
12//
13// This is a simple worklist driven algorithm.
14//
15//===----------------------------------------------------------------------===//
16
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000017#include "llvm/Transforms/Scalar.h"
Chris Lattner9b55e5a2002-05-07 18:12:18 +000018#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerae7a0d32002-08-02 19:29:35 +000019#include "llvm/Transforms/Utils/Local.h"
Chris Lattner471bd762003-05-22 19:07:21 +000020#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000021#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000022#include "llvm/Constants.h"
23#include "llvm/ConstantHandling.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000024#include "llvm/DerivedTypes.h"
Chris Lattner60a65912002-02-12 21:07:25 +000025#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000026#include "llvm/Support/InstVisitor.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000027#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000028#include <algorithm>
Chris Lattnerca081252001-12-14 16:52:21 +000029
Chris Lattner260ab202002-04-18 17:39:14 +000030namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000031 Statistic<> NumCombined ("instcombine", "Number of insts combined");
32 Statistic<> NumConstProp("instcombine", "Number of constant folds");
33 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
34
Chris Lattnerc8e66542002-04-27 06:56:12 +000035 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000036 public InstVisitor<InstCombiner, Instruction*> {
37 // Worklist of all of the instructions that need to be simplified.
38 std::vector<Instruction*> WorkList;
39
Chris Lattner113f4f42002-06-25 16:13:24 +000040 void AddUsesToWorkList(Instruction &I) {
Chris Lattner260ab202002-04-18 17:39:14 +000041 // The instruction was simplified, add all users of the instruction to
42 // the work lists because they might get more simplified now...
43 //
Chris Lattner113f4f42002-06-25 16:13:24 +000044 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000045 UI != UE; ++UI)
46 WorkList.push_back(cast<Instruction>(*UI));
47 }
48
Chris Lattner99f48c62002-09-02 04:59:56 +000049 // removeFromWorkList - remove all instances of I from the worklist.
50 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000051 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000052 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000053
Chris Lattnerf12cc842002-04-28 21:27:06 +000054 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000055 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000056 }
57
Chris Lattner260ab202002-04-18 17:39:14 +000058 // Visitation implementation - Implement instruction combining for different
59 // instruction types. The semantics are as follows:
60 // Return Value:
61 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000062 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000063 // otherwise - Change was made, replace I with returned instruction
64 //
Chris Lattner113f4f42002-06-25 16:13:24 +000065 Instruction *visitAdd(BinaryOperator &I);
66 Instruction *visitSub(BinaryOperator &I);
67 Instruction *visitMul(BinaryOperator &I);
68 Instruction *visitDiv(BinaryOperator &I);
69 Instruction *visitRem(BinaryOperator &I);
70 Instruction *visitAnd(BinaryOperator &I);
71 Instruction *visitOr (BinaryOperator &I);
72 Instruction *visitXor(BinaryOperator &I);
73 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +000074 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +000075 Instruction *visitCastInst(CastInst &CI);
76 Instruction *visitPHINode(PHINode &PN);
77 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +000078 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner9eef8a72003-06-04 04:46:00 +000079 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner260ab202002-04-18 17:39:14 +000080
81 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +000082 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +000083
84 // InsertNewInstBefore - insert an instruction New before instruction Old
85 // in the program. Add the new instruction to the worklist.
86 //
87 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +000088 assert(New && New->getParent() == 0 &&
89 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +000090 BasicBlock *BB = Old.getParent();
91 BB->getInstList().insert(&Old, New); // Insert inst
92 WorkList.push_back(New); // Add to worklist
93 }
94
95 // ReplaceInstUsesWith - This method is to be used when an instruction is
96 // found to be dead, replacable with another preexisting expression. Here
97 // we add all uses of I to the worklist, replace all uses of I with the new
98 // value, then return I, so that the inst combiner will know that I was
99 // modified.
100 //
101 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
102 AddUsesToWorkList(I); // Add all modified instrs to worklist
103 I.replaceAllUsesWith(V);
104 return &I;
105 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000106
107 // SimplifyCommutative - This performs a few simplifications for commutative
108 // operators...
109 bool SimplifyCommutative(BinaryOperator &I);
110
Chris Lattner260ab202002-04-18 17:39:14 +0000111 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000112
Chris Lattnerc8b70922002-07-26 21:12:46 +0000113 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000114}
115
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000116// getComplexity: Assign a complexity or rank value to LLVM Values...
117// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
118static unsigned getComplexity(Value *V) {
119 if (isa<Instruction>(V)) {
120 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
121 return 2;
122 return 3;
123 }
124 if (isa<Argument>(V)) return 2;
125 return isa<Constant>(V) ? 0 : 1;
126}
Chris Lattner260ab202002-04-18 17:39:14 +0000127
Chris Lattner7fb29e12003-03-11 00:12:48 +0000128// isOnlyUse - Return true if this instruction will be deleted if we stop using
129// it.
130static bool isOnlyUse(Value *V) {
131 return V->use_size() == 1 || isa<Constant>(V);
132}
133
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000134// SimplifyCommutative - This performs a few simplifications for commutative
135// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000136//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000137// 1. Order operands such that they are listed from right (least complex) to
138// left (most complex). This puts constants before unary operators before
139// binary operators.
140//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000141// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
142// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000143//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000144bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000145 bool Changed = false;
146 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
147 Changed = !I.swapOperands();
148
149 if (!I.isAssociative()) return Changed;
150 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000151 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
152 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
153 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000154 Constant *Folded = ConstantExpr::get(I.getOpcode(),
155 cast<Constant>(I.getOperand(1)),
156 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000157 I.setOperand(0, Op->getOperand(0));
158 I.setOperand(1, Folded);
159 return true;
160 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
161 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
162 isOnlyUse(Op) && isOnlyUse(Op1)) {
163 Constant *C1 = cast<Constant>(Op->getOperand(1));
164 Constant *C2 = cast<Constant>(Op1->getOperand(1));
165
166 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000167 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000168 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
169 Op1->getOperand(0),
170 Op1->getName(), &I);
171 WorkList.push_back(New);
172 I.setOperand(0, New);
173 I.setOperand(1, Folded);
174 return true;
175 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000176 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000177 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000178}
Chris Lattnerca081252001-12-14 16:52:21 +0000179
Chris Lattnerbb74e222003-03-10 23:06:50 +0000180// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
181// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000182//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000183static inline Value *dyn_castNegVal(Value *V) {
184 if (BinaryOperator::isNeg(V))
185 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
186
Chris Lattner9244df62003-04-30 22:19:10 +0000187 // Constants can be considered to be negated values if they can be folded...
188 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000189 return ConstantExpr::get(Instruction::Sub,
190 Constant::getNullValue(V->getType()), C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000191 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000192}
193
Chris Lattnerbb74e222003-03-10 23:06:50 +0000194static inline Value *dyn_castNotVal(Value *V) {
195 if (BinaryOperator::isNot(V))
196 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
197
198 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000199 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000200 return ConstantExpr::get(Instruction::Xor,
201 ConstantIntegral::getAllOnesValue(C->getType()),C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000202 return 0;
203}
204
Chris Lattner7fb29e12003-03-11 00:12:48 +0000205// dyn_castFoldableMul - If this value is a multiply that can be folded into
206// other computations (because it has a constant operand), return the
207// non-constant operand of the multiply.
208//
209static inline Value *dyn_castFoldableMul(Value *V) {
210 if (V->use_size() == 1 && V->getType()->isInteger())
211 if (Instruction *I = dyn_cast<Instruction>(V))
212 if (I->getOpcode() == Instruction::Mul)
213 if (isa<Constant>(I->getOperand(1)))
214 return I->getOperand(0);
215 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000216}
Chris Lattner31ae8632002-08-14 17:51:49 +0000217
Chris Lattner7fb29e12003-03-11 00:12:48 +0000218// dyn_castMaskingAnd - If this value is an And instruction masking a value with
219// a constant, return the constant being anded with.
220//
221static inline Constant *dyn_castMaskingAnd(Value *V) {
222 if (Instruction *I = dyn_cast<Instruction>(V))
223 if (I->getOpcode() == Instruction::And)
224 return dyn_cast<Constant>(I->getOperand(1));
225
226 // If this is a constant, it acts just like we were masking with it.
227 return dyn_cast<Constant>(V);
228}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000229
230// Log2 - Calculate the log base 2 for the specified value if it is exactly a
231// power of 2.
232static unsigned Log2(uint64_t Val) {
233 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
234 unsigned Count = 0;
235 while (Val != 1) {
236 if (Val & 1) return 0; // Multiple bits set?
237 Val >>= 1;
238 ++Count;
239 }
240 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000241}
242
Chris Lattner113f4f42002-06-25 16:13:24 +0000243Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000244 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000245 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000246
247 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000248 if (RHS == Constant::getNullValue(I.getType()))
249 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000250
Chris Lattner147e9752002-05-08 22:46:53 +0000251 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000252 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000253 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000254
255 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000256 if (!isa<Constant>(RHS))
257 if (Value *V = dyn_castNegVal(RHS))
258 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000259
Chris Lattner57c8d992003-02-18 19:57:07 +0000260 // X*C + X --> X * (C+1)
261 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000262 Constant *CP1 =
263 ConstantExpr::get(Instruction::Add,
264 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
265 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000266 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
267 }
268
269 // X + X*C --> X * (C+1)
270 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000271 Constant *CP1 =
272 ConstantExpr::get(Instruction::Add,
273 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
274 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000275 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
276 }
277
Chris Lattner7fb29e12003-03-11 00:12:48 +0000278 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
279 if (Constant *C1 = dyn_castMaskingAnd(LHS))
280 if (Constant *C2 = dyn_castMaskingAnd(RHS))
Chris Lattner34428442003-05-27 16:40:51 +0000281 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282 return BinaryOperator::create(Instruction::Or, LHS, RHS);
283
Chris Lattner113f4f42002-06-25 16:13:24 +0000284 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000285}
286
Chris Lattner113f4f42002-06-25 16:13:24 +0000287Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000288 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000289
Chris Lattnere6794492002-08-12 21:17:25 +0000290 if (Op0 == Op1) // sub X, X -> 0
291 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000292
Chris Lattnere6794492002-08-12 21:17:25 +0000293 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000294 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000295 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000296
Chris Lattner3082c5a2003-02-18 19:28:33 +0000297 // Replace (-1 - A) with (~A)...
298 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
299 if (C->isAllOnesValue())
300 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000301
Chris Lattner3082c5a2003-02-18 19:28:33 +0000302 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
303 if (Op1I->use_size() == 1) {
304 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
305 // is not used by anyone else...
306 //
307 if (Op1I->getOpcode() == Instruction::Sub) {
308 // Swap the two operands of the subexpr...
309 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
310 Op1I->setOperand(0, IIOp1);
311 Op1I->setOperand(1, IIOp0);
312
313 // Create the new top level add instruction...
314 return BinaryOperator::create(Instruction::Add, Op0, Op1);
315 }
316
317 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
318 //
319 if (Op1I->getOpcode() == Instruction::And &&
320 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
321 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
322
323 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
324 return BinaryOperator::create(Instruction::And, Op0, NewNot);
325 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000326
327 // X - X*C --> X * (1-C)
328 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000329 Constant *CP1 =
330 ConstantExpr::get(Instruction::Sub,
331 ConstantInt::get(I.getType(), 1),
332 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000333 assert(CP1 && "Couldn't constant fold 1-C?");
334 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
335 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000336 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000337
Chris Lattner57c8d992003-02-18 19:57:07 +0000338 // X*C - X --> X * (C-1)
339 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000340 Constant *CP1 =
341 ConstantExpr::get(Instruction::Sub,
342 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
343 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000344 assert(CP1 && "Couldn't constant fold C - 1?");
345 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
346 }
347
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000348 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000349}
350
Chris Lattner113f4f42002-06-25 16:13:24 +0000351Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000352 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000353 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000354
Chris Lattnere6794492002-08-12 21:17:25 +0000355 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000356 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
357 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
358 const Type *Ty = CI->getType();
359 uint64_t Val = Ty->isSigned() ?
360 (uint64_t)cast<ConstantSInt>(CI)->getValue() :
361 cast<ConstantUInt>(CI)->getValue();
362 switch (Val) {
363 case 0:
364 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
365 case 1:
366 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
367 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
368 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
369 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000370
Chris Lattner3082c5a2003-02-18 19:28:33 +0000371 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
372 return new ShiftInst(Instruction::Shl, Op0,
373 ConstantUInt::get(Type::UByteTy, C));
374 } else {
375 ConstantFP *Op1F = cast<ConstantFP>(Op1);
376 if (Op1F->isNullValue())
377 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000378
Chris Lattner3082c5a2003-02-18 19:28:33 +0000379 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
380 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
381 if (Op1F->getValue() == 1.0)
382 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
383 }
Chris Lattner260ab202002-04-18 17:39:14 +0000384 }
385
Chris Lattner934a64cf2003-03-10 23:23:04 +0000386 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
387 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
388 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
389
Chris Lattner113f4f42002-06-25 16:13:24 +0000390 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000391}
392
Chris Lattner113f4f42002-06-25 16:13:24 +0000393Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000394 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000395 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000396 if (RHS->equalsInt(1))
397 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000398
399 // Check to see if this is an unsigned division with an exact power of 2,
400 // if so, convert to a right shift.
401 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
402 if (uint64_t Val = C->getValue()) // Don't break X / 0
403 if (uint64_t C = Log2(Val))
404 return new ShiftInst(Instruction::Shr, I.getOperand(0),
405 ConstantUInt::get(Type::UByteTy, C));
406 }
407
408 // 0 / X == 0, we don't need to preserve faults!
409 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
410 if (LHS->equalsInt(0))
411 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
412
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000413 return 0;
414}
415
416
Chris Lattner113f4f42002-06-25 16:13:24 +0000417Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000418 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
419 if (RHS->equalsInt(1)) // X % 1 == 0
420 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
421
422 // Check to see if this is an unsigned remainder with an exact power of 2,
423 // if so, convert to a bitwise and.
424 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
425 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
426 if (Log2(Val))
427 return BinaryOperator::create(Instruction::And, I.getOperand(0),
428 ConstantUInt::get(I.getType(), Val-1));
429 }
430
431 // 0 % X == 0, we don't need to preserve faults!
432 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
433 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000434 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
435
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000436 return 0;
437}
438
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000439// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000440static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000441 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
442 // Calculate -1 casted to the right type...
443 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
444 uint64_t Val = ~0ULL; // All ones
445 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
446 return CU->getValue() == Val-1;
447 }
448
449 const ConstantSInt *CS = cast<ConstantSInt>(C);
450
451 // Calculate 0111111111..11111
452 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
453 int64_t Val = INT64_MAX; // All ones
454 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
455 return CS->getValue() == Val-1;
456}
457
458// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000459static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000460 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
461 return CU->getValue() == 1;
462
463 const ConstantSInt *CS = cast<ConstantSInt>(C);
464
465 // Calculate 1111111111000000000000
466 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
467 int64_t Val = -1; // All ones
468 Val <<= TypeBits-1; // Shift over to the right spot
469 return CS->getValue() == Val+1;
470}
471
472
Chris Lattner113f4f42002-06-25 16:13:24 +0000473Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000474 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000475 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000476
477 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000478 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
479 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000480
481 // and X, -1 == X
Chris Lattner83282632002-08-13 17:50:24 +0000482 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000483 if (RHS->isAllOnesValue())
484 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000485
Chris Lattnerbb74e222003-03-10 23:06:50 +0000486 Value *Op0NotVal = dyn_castNotVal(Op0);
487 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000488
489 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000490 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000491 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
492 Op1NotVal,I.getName()+".demorgan",
493 &I);
Chris Lattner3e327a42003-03-10 23:13:59 +0000494 WorkList.push_back(Or);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000495 return BinaryOperator::createNot(Or);
496 }
497
498 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
499 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000500
Chris Lattner113f4f42002-06-25 16:13:24 +0000501 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000502}
503
504
505
Chris Lattner113f4f42002-06-25 16:13:24 +0000506Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000507 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000508 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000509
510 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000511 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
512 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000513
514 // or X, -1 == -1
Chris Lattner83282632002-08-13 17:50:24 +0000515 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000516 if (RHS->isAllOnesValue())
517 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000518
Chris Lattner3e327a42003-03-10 23:13:59 +0000519 Value *Op0NotVal = dyn_castNotVal(Op0);
520 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000521
Chris Lattner3e327a42003-03-10 23:13:59 +0000522 if (Op1 == Op0NotVal) // ~A | A == -1
523 return ReplaceInstUsesWith(I,
524 ConstantIntegral::getAllOnesValue(I.getType()));
525
526 if (Op0 == Op1NotVal) // A | ~A == -1
527 return ReplaceInstUsesWith(I,
528 ConstantIntegral::getAllOnesValue(I.getType()));
529
530 // (~A | ~B) == (~(A & B)) - Demorgan's Law
531 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
532 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
533 Op1NotVal,I.getName()+".demorgan",
534 &I);
535 WorkList.push_back(And);
536 return BinaryOperator::createNot(And);
537 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000538
Chris Lattner113f4f42002-06-25 16:13:24 +0000539 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000540}
541
542
543
Chris Lattner113f4f42002-06-25 16:13:24 +0000544Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000545 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000546 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000547
548 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000549 if (Op0 == Op1)
550 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000551
Chris Lattner83282632002-08-13 17:50:24 +0000552 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000553 // xor X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000554 if (Op1C->isNullValue())
555 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000556
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000557 // Is this a "NOT" instruction?
558 if (Op1C->isAllOnesValue()) {
559 // xor (xor X, -1), -1 = not (not X) = X
Chris Lattnerbb74e222003-03-10 23:06:50 +0000560 if (Value *X = dyn_castNotVal(Op0))
Chris Lattner31ae8632002-08-14 17:51:49 +0000561 return ReplaceInstUsesWith(I, X);
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000562
563 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
564 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
565 if (SCI->use_size() == 1)
566 return new SetCondInst(SCI->getInverseCondition(),
567 SCI->getOperand(0), SCI->getOperand(1));
568 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000569 }
570
Chris Lattnerbb74e222003-03-10 23:06:50 +0000571 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000572 if (X == Op1)
573 return ReplaceInstUsesWith(I,
574 ConstantIntegral::getAllOnesValue(I.getType()));
575
Chris Lattnerbb74e222003-03-10 23:06:50 +0000576 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000577 if (X == Op0)
578 return ReplaceInstUsesWith(I,
579 ConstantIntegral::getAllOnesValue(I.getType()));
580
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000581 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
582 if (Op1I->getOpcode() == Instruction::Or)
583 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
584 cast<BinaryOperator>(Op1I)->swapOperands();
585 I.swapOperands();
586 std::swap(Op0, Op1);
587 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
588 I.swapOperands();
589 std::swap(Op0, Op1);
590 }
591
592 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
593 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
594 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
595 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000596 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000597 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
598 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000599 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
600 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000601 }
602 }
603
Chris Lattner7fb29e12003-03-11 00:12:48 +0000604 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
605 if (Constant *C1 = dyn_castMaskingAnd(Op0))
606 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +0000607 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000608 return BinaryOperator::create(Instruction::Or, Op0, Op1);
609
Chris Lattner113f4f42002-06-25 16:13:24 +0000610 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000611}
612
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000613// AddOne, SubOne - Add or subtract a constant one from an integer constant...
614static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000615 Constant *Result = ConstantExpr::get(Instruction::Add, C,
616 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000617 assert(Result && "Constant folding integer addition failed!");
618 return Result;
619}
620static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000621 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
622 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000623 assert(Result && "Constant folding integer addition failed!");
624 return Result;
625}
626
Chris Lattner1fc23f32002-05-09 20:11:54 +0000627// isTrueWhenEqual - Return true if the specified setcondinst instruction is
628// true when both operands are equal...
629//
Chris Lattner113f4f42002-06-25 16:13:24 +0000630static bool isTrueWhenEqual(Instruction &I) {
631 return I.getOpcode() == Instruction::SetEQ ||
632 I.getOpcode() == Instruction::SetGE ||
633 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000634}
635
Chris Lattner113f4f42002-06-25 16:13:24 +0000636Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000637 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000638 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
639 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000640
641 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000642 if (Op0 == Op1)
643 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000644
645 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000646 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
647 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
648
649 // setcc's with boolean values can always be turned into bitwise operations
650 if (Ty == Type::BoolTy) {
651 // If this is <, >, or !=, we can change this into a simple xor instruction
652 if (!isTrueWhenEqual(I))
653 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
654
655 // Otherwise we need to make a temporary intermediate instruction and insert
656 // it into the instruction stream. This is what we are after:
657 //
658 // seteq bool %A, %B -> ~(A^B)
659 // setle bool %A, %B -> ~A | B
660 // setge bool %A, %B -> A | ~B
661 //
662 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
663 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
664 I.getName()+"tmp");
665 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000666 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000667 }
668
669 // Handle the setXe cases...
670 assert(I.getOpcode() == Instruction::SetGE ||
671 I.getOpcode() == Instruction::SetLE);
672
673 if (I.getOpcode() == Instruction::SetGE)
674 std::swap(Op0, Op1); // Change setge -> setle
675
676 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000677 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000678 InsertNewInstBefore(Not, I);
679 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
680 }
681
682 // Check to see if we are doing one of many comparisons against constant
683 // integers at the end of their ranges...
684 //
685 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere967b342003-06-04 05:10:11 +0000686 if (CI->isNullValue()) {
687 if (I.getOpcode() == Instruction::SetNE)
688 return new CastInst(Op0, Type::BoolTy, I.getName());
689 else if (I.getOpcode() == Instruction::SetEQ) {
690 // seteq X, 0 -> not (cast X to bool)
691 Instruction *Val = new CastInst(Op0, Type::BoolTy, I.getName()+".not");
692 InsertNewInstBefore(Val, I);
693 return BinaryOperator::createNot(Val, I.getName());
694 }
695 }
Chris Lattner791ac1a2003-06-01 03:35:25 +0000696
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000697 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000698 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000699 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
700 return ReplaceInstUsesWith(I, ConstantBool::False);
701 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
702 return ReplaceInstUsesWith(I, ConstantBool::True);
703 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
704 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
705 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
706 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
707
Chris Lattnere6794492002-08-12 21:17:25 +0000708 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000709 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
710 return ReplaceInstUsesWith(I, ConstantBool::False);
711 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
712 return ReplaceInstUsesWith(I, ConstantBool::True);
713 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
714 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
715 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
716 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
717
718 // Comparing against a value really close to min or max?
719 } else if (isMinValuePlusOne(CI)) {
720 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
721 return BinaryOperator::create(Instruction::SetEQ, Op0,
722 SubOne(CI), I.getName());
723 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
724 return BinaryOperator::create(Instruction::SetNE, Op0,
725 SubOne(CI), I.getName());
726
727 } else if (isMaxValueMinusOne(CI)) {
728 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
729 return BinaryOperator::create(Instruction::SetEQ, Op0,
730 AddOne(CI), I.getName());
731 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
732 return BinaryOperator::create(Instruction::SetNE, Op0,
733 AddOne(CI), I.getName());
734 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000735 }
736
Chris Lattner113f4f42002-06-25 16:13:24 +0000737 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000738}
739
740
741
Chris Lattnere8d6c602003-03-10 19:16:08 +0000742Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000743 assert(I.getOperand(1)->getType() == Type::UByteTy);
744 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000745
746 // shl X, 0 == X and shr X, 0 == X
747 // shl 0, X == 0 and shr 0, X == 0
748 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000749 Op0 == Constant::getNullValue(Op0->getType()))
750 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000751
Chris Lattnere8d6c602003-03-10 19:16:08 +0000752 // If this is a shift of a shift, see if we can fold the two together...
753 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
754 if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
755 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
756 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
757 unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
758
759 // Check for (A << c1) << c2 and (A >> c1) >> c2
760 if (I.getOpcode() == Op0SI->getOpcode()) {
761 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
762 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
763 ConstantUInt::get(Type::UByteTy, Amt));
764 }
765
766 if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
767 // Calculate bitmask for what gets shifted off the edge...
768 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
769 if (I.getOpcode() == Instruction::Shr)
Chris Lattner34428442003-05-27 16:40:51 +0000770 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000771 else
Chris Lattner34428442003-05-27 16:40:51 +0000772 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000773
774 Instruction *Mask =
775 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
776 C, Op0SI->getOperand(0)->getName()+".mask",&I);
777 WorkList.push_back(Mask);
778
779 // Figure out what flavor of shift we should use...
780 if (ShiftAmt1 == ShiftAmt2)
781 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
782 else if (ShiftAmt1 < ShiftAmt2) {
783 return new ShiftInst(I.getOpcode(), Mask,
784 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
785 } else {
786 return new ShiftInst(Op0SI->getOpcode(), Mask,
787 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
788 }
789 }
790 }
791 }
792
Chris Lattnere6794492002-08-12 21:17:25 +0000793 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000794 // a signed value.
795 //
796 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattnere8d6c602003-03-10 19:16:08 +0000797 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
798 if (CUI->getValue() >= TypeBits &&
799 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
800 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000801
802 // Check to see if we are shifting left by 1. If so, turn it into an add
803 // instruction.
804 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
Chris Lattner3082c5a2003-02-18 19:28:33 +0000805 // Convert 'shl int %X, 1' to 'add int %X, %X'
Chris Lattner55f3d942002-09-10 23:04:09 +0000806 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
807
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000808 }
Chris Lattner2e0fb392002-10-08 16:16:40 +0000809
810 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
811 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
812 if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
813 return ReplaceInstUsesWith(I, CSI);
814
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000815 return 0;
816}
817
818
Chris Lattner48a44f72002-05-02 17:06:02 +0000819// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
820// instruction.
821//
Chris Lattner113f4f42002-06-25 16:13:24 +0000822static inline bool isEliminableCastOfCast(const CastInst &CI,
Chris Lattner48a44f72002-05-02 17:06:02 +0000823 const CastInst *CSrc) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000824 assert(CI.getOperand(0) == CSrc);
Chris Lattner48a44f72002-05-02 17:06:02 +0000825 const Type *SrcTy = CSrc->getOperand(0)->getType();
826 const Type *MidTy = CSrc->getType();
Chris Lattner113f4f42002-06-25 16:13:24 +0000827 const Type *DstTy = CI.getType();
Chris Lattner48a44f72002-05-02 17:06:02 +0000828
Chris Lattner650b6da2002-08-02 20:00:25 +0000829 // It is legal to eliminate the instruction if casting A->B->A if the sizes
830 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +0000831 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +0000832 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +0000833 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +0000834
835 // Allow free casting and conversion of sizes as long as the sign doesn't
836 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000837 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +0000838 unsigned SrcSize = SrcTy->getPrimitiveSize();
839 unsigned MidSize = MidTy->getPrimitiveSize();
840 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +0000841
Chris Lattner3732aca2002-08-15 16:15:25 +0000842 // Cases where we are monotonically decreasing the size of the type are
843 // always ok, regardless of what sign changes are going on.
844 //
Chris Lattner0bb75912002-08-14 23:21:10 +0000845 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000846 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +0000847
Chris Lattner555518c2002-09-23 23:39:43 +0000848 // Cases where the source and destination type are the same, but the middle
849 // type is bigger are noops.
850 //
851 if (SrcSize == DstSize && MidSize > SrcSize)
852 return true;
853
Chris Lattner3732aca2002-08-15 16:15:25 +0000854 // If we are monotonically growing, things are more complex.
855 //
856 if (SrcSize <= MidSize && MidSize <= DstSize) {
857 // We have eight combinations of signedness to worry about. Here's the
858 // table:
859 static const int SignTable[8] = {
860 // CODE, SrcSigned, MidSigned, DstSigned, Comment
861 1, // U U U Always ok
862 1, // U U S Always ok
863 3, // U S U Ok iff SrcSize != MidSize
864 3, // U S S Ok iff SrcSize != MidSize
865 0, // S U U Never ok
866 2, // S U S Ok iff MidSize == DstSize
867 1, // S S U Always ok
868 1, // S S S Always ok
869 };
870
871 // Choose an action based on the current entry of the signtable that this
872 // cast of cast refers to...
873 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
874 switch (SignTable[Row]) {
875 case 0: return false; // Never ok
876 case 1: return true; // Always ok
877 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
878 case 3: // Ok iff SrcSize != MidSize
879 return SrcSize != MidSize || SrcTy == Type::BoolTy;
880 default: assert(0 && "Bad entry in sign table!");
881 }
Chris Lattner3732aca2002-08-15 16:15:25 +0000882 }
Chris Lattner650b6da2002-08-02 20:00:25 +0000883 }
Chris Lattner48a44f72002-05-02 17:06:02 +0000884
885 // Otherwise, we cannot succeed. Specifically we do not want to allow things
886 // like: short -> ushort -> uint, because this can create wrong results if
887 // the input short is negative!
888 //
889 return false;
890}
891
892
893// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +0000894//
Chris Lattner113f4f42002-06-25 16:13:24 +0000895Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000896 // If the user is casting a value to the same type, eliminate this cast
897 // instruction...
Chris Lattnere6794492002-08-12 21:17:25 +0000898 if (CI.getType() == CI.getOperand(0)->getType())
899 return ReplaceInstUsesWith(CI, CI.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000900
Chris Lattner48a44f72002-05-02 17:06:02 +0000901 // If casting the result of another cast instruction, try to eliminate this
902 // one!
903 //
Chris Lattner650b6da2002-08-02 20:00:25 +0000904 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000905 if (isEliminableCastOfCast(CI, CSrc)) {
906 // This instruction now refers directly to the cast's src operand. This
907 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +0000908 CI.setOperand(0, CSrc->getOperand(0));
909 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +0000910 }
911
Chris Lattner650b6da2002-08-02 20:00:25 +0000912 // If this is an A->B->A cast, and we are dealing with integral types, try
913 // to convert this into a logical 'and' instruction.
914 //
915 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000916 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +0000917 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
918 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
919 assert(CSrc->getType() != Type::ULongTy &&
920 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +0000921 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +0000922 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
923 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
924 AndOp);
925 }
926 }
927
Chris Lattner260ab202002-04-18 17:39:14 +0000928 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +0000929}
930
Chris Lattner48a44f72002-05-02 17:06:02 +0000931
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000932// PHINode simplification
933//
Chris Lattner113f4f42002-06-25 16:13:24 +0000934Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000935 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +0000936 if (PN.getNumIncomingValues() == 1)
937 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +0000938
939 // Otherwise if all of the incoming values are the same for the PHI, replace
940 // the PHI node with the incoming value.
941 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +0000942 Value *InVal = 0;
943 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
944 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
945 if (InVal && PN.getIncomingValue(i) != InVal)
946 return 0; // Not the same, bail out.
947 else
948 InVal = PN.getIncomingValue(i);
949
950 // The only case that could cause InVal to be null is if we have a PHI node
951 // that only has entries for itself. In this case, there is no entry into the
952 // loop, so kill the PHI.
953 //
954 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000955
Chris Lattner9cd1e662002-08-20 15:35:35 +0000956 // All of the incoming values are the same, replace the PHI node now.
957 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +0000958}
959
Chris Lattner48a44f72002-05-02 17:06:02 +0000960
Chris Lattner113f4f42002-06-25 16:13:24 +0000961Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +0000962 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +0000963 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000964 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +0000965 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000966 GEP.getNumOperands() == 1)
967 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000968
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000969 // Combine Indices - If the source pointer to this getelementptr instruction
970 // is a getelementptr instruction, combine the indices of the two
971 // getelementptr instructions into a single instruction.
972 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +0000973 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000974 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +0000975
Chris Lattnerae7a0d32002-08-02 19:29:35 +0000976 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +0000977 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
978 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +0000979 // Replace: gep (gep %P, long C1), long C2, ...
980 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +0000981 Value *Sum = ConstantExpr::get(Instruction::Add,
982 cast<Constant>(Src->getOperand(1)),
983 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +0000984 assert(Sum && "Constant folding of longs failed!?");
985 GEP.setOperand(0, Src->getOperand(0));
986 GEP.setOperand(1, Sum);
987 AddUsesToWorkList(*Src); // Reduce use count of Src
988 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +0000989 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +0000990 // Replace: gep (gep %P, long B), long A, ...
991 // With: T = long A+B; gep %P, T, ...
992 //
993 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
994 GEP.getOperand(1),
995 Src->getName()+".sum", &GEP);
996 GEP.setOperand(0, Src->getOperand(0));
997 GEP.setOperand(1, Sum);
998 WorkList.push_back(cast<Instruction>(Sum));
999 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00001000 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00001001 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001002 // Otherwise we can do the fold if the first index of the GEP is a zero
1003 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1004 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00001005 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1006 Constant::getNullValue(Type::LongTy)) {
1007 // If the src gep ends with a constant array index, merge this get into
1008 // it, even if we have a non-zero array index.
1009 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1010 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001011 }
1012
1013 if (!Indices.empty())
1014 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001015
1016 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1017 // GEP of global variable. If all of the indices for this GEP are
1018 // constants, we can promote this to a constexpr instead of an instruction.
1019
1020 // Scan for nonconstants...
1021 std::vector<Constant*> Indices;
1022 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1023 for (; I != E && isa<Constant>(*I); ++I)
1024 Indices.push_back(cast<Constant>(*I));
1025
1026 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001027 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001028 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1029
1030 // Replace all uses of the GEP with the new constexpr...
1031 return ReplaceInstUsesWith(GEP, CE);
1032 }
Chris Lattnerca081252001-12-14 16:52:21 +00001033 }
1034
Chris Lattnerca081252001-12-14 16:52:21 +00001035 return 0;
1036}
1037
Chris Lattner1085bdf2002-11-04 16:18:53 +00001038Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1039 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1040 if (AI.isArrayAllocation()) // Check C != 1
1041 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1042 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001043 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001044
1045 // Create and insert the replacement instruction...
1046 if (isa<MallocInst>(AI))
1047 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001048 else {
1049 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001050 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001051 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001052
1053 // Scan to the end of the allocation instructions, to skip over a block of
1054 // allocas if possible...
1055 //
1056 BasicBlock::iterator It = New;
1057 while (isa<AllocationInst>(*It)) ++It;
1058
1059 // Now that I is pointing to the first non-allocation-inst in the block,
1060 // insert our getelementptr instruction...
1061 //
1062 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1063 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1064
1065 // Now make everything use the getelementptr instead of the original
1066 // allocation.
1067 ReplaceInstUsesWith(AI, V);
1068 return &AI;
1069 }
1070 return 0;
1071}
1072
Chris Lattner9eef8a72003-06-04 04:46:00 +00001073Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1074 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnere967b342003-06-04 05:10:11 +00001075 if (BI.isConditional())
1076 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1077 BasicBlock *TrueDest = BI.getSuccessor(0);
1078 BasicBlock *FalseDest = BI.getSuccessor(1);
1079 // Swap Destinations and condition...
1080 BI.setCondition(V);
1081 BI.setSuccessor(0, FalseDest);
1082 BI.setSuccessor(1, TrueDest);
1083 return &BI;
1084 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00001085 return 0;
1086}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001087
Chris Lattnerca081252001-12-14 16:52:21 +00001088
Chris Lattner99f48c62002-09-02 04:59:56 +00001089void InstCombiner::removeFromWorkList(Instruction *I) {
1090 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1091 WorkList.end());
1092}
1093
Chris Lattner113f4f42002-06-25 16:13:24 +00001094bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001095 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001096
Chris Lattner260ab202002-04-18 17:39:14 +00001097 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001098
1099 while (!WorkList.empty()) {
1100 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1101 WorkList.pop_back();
1102
Misha Brukman632df282002-10-29 23:06:16 +00001103 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001104 // Check to see if we can DIE the instruction...
1105 if (isInstructionTriviallyDead(I)) {
1106 // Add operands to the worklist...
1107 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1108 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1109 WorkList.push_back(Op);
1110
1111 ++NumDeadInst;
1112 BasicBlock::iterator BBI = I;
1113 if (dceInstruction(BBI)) {
1114 removeFromWorkList(I);
1115 continue;
1116 }
1117 }
1118
Misha Brukman632df282002-10-29 23:06:16 +00001119 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001120 if (Constant *C = ConstantFoldInstruction(I)) {
1121 // Add operands to the worklist...
1122 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1123 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1124 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001125 ReplaceInstUsesWith(*I, C);
1126
Chris Lattner99f48c62002-09-02 04:59:56 +00001127 ++NumConstProp;
1128 BasicBlock::iterator BBI = I;
1129 if (dceInstruction(BBI)) {
1130 removeFromWorkList(I);
1131 continue;
1132 }
1133 }
1134
Chris Lattnerca081252001-12-14 16:52:21 +00001135 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001136 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001137 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001138 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001139 if (Result != I) {
1140 // Instructions can end up on the worklist more than once. Make sure
1141 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001142 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001143 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001144 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001145 BasicBlock::iterator II = I;
1146
1147 // If the instruction was modified, it's possible that it is now dead.
1148 // if so, remove it.
1149 if (dceInstruction(II)) {
1150 // Instructions may end up in the worklist more than once. Erase them
1151 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001152 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001153 Result = 0;
1154 }
Chris Lattner053c0932002-05-14 15:24:07 +00001155 }
Chris Lattner260ab202002-04-18 17:39:14 +00001156
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001157 if (Result) {
1158 WorkList.push_back(Result);
1159 AddUsesToWorkList(*Result);
1160 }
Chris Lattner260ab202002-04-18 17:39:14 +00001161 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001162 }
1163 }
1164
Chris Lattner260ab202002-04-18 17:39:14 +00001165 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001166}
1167
1168Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001169 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001170}