blob: a0a09e4b1daf0294927ad20d52571edfc0e6a63c [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 Lattner970c33a2003-06-19 17:00:31 +000027#include "llvm/Support/CallSite.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000028#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000029#include <algorithm>
Chris Lattnerca081252001-12-14 16:52:21 +000030
Chris Lattner260ab202002-04-18 17:39:14 +000031namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000032 Statistic<> NumCombined ("instcombine", "Number of insts combined");
33 Statistic<> NumConstProp("instcombine", "Number of constant folds");
34 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
35
Chris Lattnerc8e66542002-04-27 06:56:12 +000036 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000037 public InstVisitor<InstCombiner, Instruction*> {
38 // Worklist of all of the instructions that need to be simplified.
39 std::vector<Instruction*> WorkList;
40
Chris Lattner113f4f42002-06-25 16:13:24 +000041 void AddUsesToWorkList(Instruction &I) {
Chris Lattner260ab202002-04-18 17:39:14 +000042 // The instruction was simplified, add all users of the instruction to
43 // the work lists because they might get more simplified now...
44 //
Chris Lattner113f4f42002-06-25 16:13:24 +000045 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000046 UI != UE; ++UI)
47 WorkList.push_back(cast<Instruction>(*UI));
48 }
49
Chris Lattner99f48c62002-09-02 04:59:56 +000050 // removeFromWorkList - remove all instances of I from the worklist.
51 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000052 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000053 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000054
Chris Lattnerf12cc842002-04-28 21:27:06 +000055 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000056 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000057 }
58
Chris Lattner260ab202002-04-18 17:39:14 +000059 // Visitation implementation - Implement instruction combining for different
60 // instruction types. The semantics are as follows:
61 // Return Value:
62 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000063 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000064 // otherwise - Change was made, replace I with returned instruction
65 //
Chris Lattner113f4f42002-06-25 16:13:24 +000066 Instruction *visitAdd(BinaryOperator &I);
67 Instruction *visitSub(BinaryOperator &I);
68 Instruction *visitMul(BinaryOperator &I);
69 Instruction *visitDiv(BinaryOperator &I);
70 Instruction *visitRem(BinaryOperator &I);
71 Instruction *visitAnd(BinaryOperator &I);
72 Instruction *visitOr (BinaryOperator &I);
73 Instruction *visitXor(BinaryOperator &I);
74 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +000075 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +000076 Instruction *visitCastInst(CastInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +000077 Instruction *visitCallInst(CallInst &CI);
78 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +000079 Instruction *visitPHINode(PHINode &PN);
80 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +000081 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner9eef8a72003-06-04 04:46:00 +000082 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner260ab202002-04-18 17:39:14 +000083
84 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +000085 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +000086
Chris Lattner970c33a2003-06-19 17:00:31 +000087 private:
88 bool transformConstExprCastCall(CallSite CS);
89
Chris Lattner6d14f2a2002-08-09 23:47:40 +000090 // InsertNewInstBefore - insert an instruction New before instruction Old
91 // in the program. Add the new instruction to the worklist.
92 //
93 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +000094 assert(New && New->getParent() == 0 &&
95 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +000096 BasicBlock *BB = Old.getParent();
97 BB->getInstList().insert(&Old, New); // Insert inst
98 WorkList.push_back(New); // Add to worklist
99 }
100
101 // ReplaceInstUsesWith - This method is to be used when an instruction is
102 // found to be dead, replacable with another preexisting expression. Here
103 // we add all uses of I to the worklist, replace all uses of I with the new
104 // value, then return I, so that the inst combiner will know that I was
105 // modified.
106 //
107 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
108 AddUsesToWorkList(I); // Add all modified instrs to worklist
109 I.replaceAllUsesWith(V);
110 return &I;
111 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000112
113 // SimplifyCommutative - This performs a few simplifications for commutative
114 // operators...
115 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattner260ab202002-04-18 17:39:14 +0000116 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000117
Chris Lattnerc8b70922002-07-26 21:12:46 +0000118 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000119}
120
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000121// getComplexity: Assign a complexity or rank value to LLVM Values...
122// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
123static unsigned getComplexity(Value *V) {
124 if (isa<Instruction>(V)) {
125 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
126 return 2;
127 return 3;
128 }
129 if (isa<Argument>(V)) return 2;
130 return isa<Constant>(V) ? 0 : 1;
131}
Chris Lattner260ab202002-04-18 17:39:14 +0000132
Chris Lattner7fb29e12003-03-11 00:12:48 +0000133// isOnlyUse - Return true if this instruction will be deleted if we stop using
134// it.
135static bool isOnlyUse(Value *V) {
136 return V->use_size() == 1 || isa<Constant>(V);
137}
138
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000139// SimplifyCommutative - This performs a few simplifications for commutative
140// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000141//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000142// 1. Order operands such that they are listed from right (least complex) to
143// left (most complex). This puts constants before unary operators before
144// binary operators.
145//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000146// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
147// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000148//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000149bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000150 bool Changed = false;
151 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
152 Changed = !I.swapOperands();
153
154 if (!I.isAssociative()) return Changed;
155 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000156 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
157 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
158 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000159 Constant *Folded = ConstantExpr::get(I.getOpcode(),
160 cast<Constant>(I.getOperand(1)),
161 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000162 I.setOperand(0, Op->getOperand(0));
163 I.setOperand(1, Folded);
164 return true;
165 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
166 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
167 isOnlyUse(Op) && isOnlyUse(Op1)) {
168 Constant *C1 = cast<Constant>(Op->getOperand(1));
169 Constant *C2 = cast<Constant>(Op1->getOperand(1));
170
171 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000172 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000173 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
174 Op1->getOperand(0),
175 Op1->getName(), &I);
176 WorkList.push_back(New);
177 I.setOperand(0, New);
178 I.setOperand(1, Folded);
179 return true;
180 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000181 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000182 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000183}
Chris Lattnerca081252001-12-14 16:52:21 +0000184
Chris Lattnerbb74e222003-03-10 23:06:50 +0000185// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
186// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000187//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000188static inline Value *dyn_castNegVal(Value *V) {
189 if (BinaryOperator::isNeg(V))
190 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
191
Chris Lattner9244df62003-04-30 22:19:10 +0000192 // Constants can be considered to be negated values if they can be folded...
193 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000194 return ConstantExpr::get(Instruction::Sub,
195 Constant::getNullValue(V->getType()), C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000196 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000197}
198
Chris Lattnerbb74e222003-03-10 23:06:50 +0000199static inline Value *dyn_castNotVal(Value *V) {
200 if (BinaryOperator::isNot(V))
201 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
202
203 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000204 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000205 return ConstantExpr::get(Instruction::Xor,
206 ConstantIntegral::getAllOnesValue(C->getType()),C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000207 return 0;
208}
209
Chris Lattner7fb29e12003-03-11 00:12:48 +0000210// dyn_castFoldableMul - If this value is a multiply that can be folded into
211// other computations (because it has a constant operand), return the
212// non-constant operand of the multiply.
213//
214static inline Value *dyn_castFoldableMul(Value *V) {
215 if (V->use_size() == 1 && V->getType()->isInteger())
216 if (Instruction *I = dyn_cast<Instruction>(V))
217 if (I->getOpcode() == Instruction::Mul)
218 if (isa<Constant>(I->getOperand(1)))
219 return I->getOperand(0);
220 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000221}
Chris Lattner31ae8632002-08-14 17:51:49 +0000222
Chris Lattner7fb29e12003-03-11 00:12:48 +0000223// dyn_castMaskingAnd - If this value is an And instruction masking a value with
224// a constant, return the constant being anded with.
225//
226static inline Constant *dyn_castMaskingAnd(Value *V) {
227 if (Instruction *I = dyn_cast<Instruction>(V))
228 if (I->getOpcode() == Instruction::And)
229 return dyn_cast<Constant>(I->getOperand(1));
230
231 // If this is a constant, it acts just like we were masking with it.
232 return dyn_cast<Constant>(V);
233}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000234
235// Log2 - Calculate the log base 2 for the specified value if it is exactly a
236// power of 2.
237static unsigned Log2(uint64_t Val) {
238 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
239 unsigned Count = 0;
240 while (Val != 1) {
241 if (Val & 1) return 0; // Multiple bits set?
242 Val >>= 1;
243 ++Count;
244 }
245 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000246}
247
Chris Lattner113f4f42002-06-25 16:13:24 +0000248Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000249 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000250 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000251
252 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000253 if (RHS == Constant::getNullValue(I.getType()))
254 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000255
Chris Lattner147e9752002-05-08 22:46:53 +0000256 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000257 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000258 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000259
260 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000261 if (!isa<Constant>(RHS))
262 if (Value *V = dyn_castNegVal(RHS))
263 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000264
Chris Lattner57c8d992003-02-18 19:57:07 +0000265 // X*C + X --> X * (C+1)
266 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000267 Constant *CP1 =
268 ConstantExpr::get(Instruction::Add,
269 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
270 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000271 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
272 }
273
274 // X + X*C --> X * (C+1)
275 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000276 Constant *CP1 =
277 ConstantExpr::get(Instruction::Add,
278 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
279 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000280 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
281 }
282
Chris Lattner7fb29e12003-03-11 00:12:48 +0000283 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
284 if (Constant *C1 = dyn_castMaskingAnd(LHS))
285 if (Constant *C2 = dyn_castMaskingAnd(RHS))
Chris Lattner34428442003-05-27 16:40:51 +0000286 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000287 return BinaryOperator::create(Instruction::Or, LHS, RHS);
288
Chris Lattner113f4f42002-06-25 16:13:24 +0000289 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000290}
291
Chris Lattner113f4f42002-06-25 16:13:24 +0000292Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000293 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000294
Chris Lattnere6794492002-08-12 21:17:25 +0000295 if (Op0 == Op1) // sub X, X -> 0
296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000297
Chris Lattnere6794492002-08-12 21:17:25 +0000298 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000299 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000300 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000301
Chris Lattner3082c5a2003-02-18 19:28:33 +0000302 // Replace (-1 - A) with (~A)...
303 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
304 if (C->isAllOnesValue())
305 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000306
Chris Lattner3082c5a2003-02-18 19:28:33 +0000307 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
308 if (Op1I->use_size() == 1) {
309 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
310 // is not used by anyone else...
311 //
312 if (Op1I->getOpcode() == Instruction::Sub) {
313 // Swap the two operands of the subexpr...
314 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
315 Op1I->setOperand(0, IIOp1);
316 Op1I->setOperand(1, IIOp0);
317
318 // Create the new top level add instruction...
319 return BinaryOperator::create(Instruction::Add, Op0, Op1);
320 }
321
322 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
323 //
324 if (Op1I->getOpcode() == Instruction::And &&
325 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
326 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
327
328 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
329 return BinaryOperator::create(Instruction::And, Op0, NewNot);
330 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000331
332 // X - X*C --> X * (1-C)
333 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000334 Constant *CP1 =
335 ConstantExpr::get(Instruction::Sub,
336 ConstantInt::get(I.getType(), 1),
337 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000338 assert(CP1 && "Couldn't constant fold 1-C?");
339 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
340 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000341 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000342
Chris Lattner57c8d992003-02-18 19:57:07 +0000343 // X*C - X --> X * (C-1)
344 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000345 Constant *CP1 =
346 ConstantExpr::get(Instruction::Sub,
347 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
348 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000349 assert(CP1 && "Couldn't constant fold C - 1?");
350 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
351 }
352
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000353 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000354}
355
Chris Lattner113f4f42002-06-25 16:13:24 +0000356Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000357 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000358 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000359
Chris Lattnere6794492002-08-12 21:17:25 +0000360 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000361 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
362 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
363 const Type *Ty = CI->getType();
364 uint64_t Val = Ty->isSigned() ?
365 (uint64_t)cast<ConstantSInt>(CI)->getValue() :
366 cast<ConstantUInt>(CI)->getValue();
367 switch (Val) {
368 case 0:
369 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
370 case 1:
371 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
372 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
373 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
374 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000375
Chris Lattner3082c5a2003-02-18 19:28:33 +0000376 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
377 return new ShiftInst(Instruction::Shl, Op0,
378 ConstantUInt::get(Type::UByteTy, C));
379 } else {
380 ConstantFP *Op1F = cast<ConstantFP>(Op1);
381 if (Op1F->isNullValue())
382 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000383
Chris Lattner3082c5a2003-02-18 19:28:33 +0000384 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
385 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
386 if (Op1F->getValue() == 1.0)
387 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
388 }
Chris Lattner260ab202002-04-18 17:39:14 +0000389 }
390
Chris Lattner934a64cf2003-03-10 23:23:04 +0000391 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
392 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
393 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
394
Chris Lattner113f4f42002-06-25 16:13:24 +0000395 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000396}
397
Chris Lattner113f4f42002-06-25 16:13:24 +0000398Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000399 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000400 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000401 if (RHS->equalsInt(1))
402 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000403
404 // Check to see if this is an unsigned division with an exact power of 2,
405 // if so, convert to a right shift.
406 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
407 if (uint64_t Val = C->getValue()) // Don't break X / 0
408 if (uint64_t C = Log2(Val))
409 return new ShiftInst(Instruction::Shr, I.getOperand(0),
410 ConstantUInt::get(Type::UByteTy, C));
411 }
412
413 // 0 / X == 0, we don't need to preserve faults!
414 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
415 if (LHS->equalsInt(0))
416 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
417
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000418 return 0;
419}
420
421
Chris Lattner113f4f42002-06-25 16:13:24 +0000422Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000423 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
424 if (RHS->equalsInt(1)) // X % 1 == 0
425 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
426
427 // Check to see if this is an unsigned remainder with an exact power of 2,
428 // if so, convert to a bitwise and.
429 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
430 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
431 if (Log2(Val))
432 return BinaryOperator::create(Instruction::And, I.getOperand(0),
433 ConstantUInt::get(I.getType(), Val-1));
434 }
435
436 // 0 % X == 0, we don't need to preserve faults!
437 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
438 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
440
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000441 return 0;
442}
443
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000444// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000445static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000446 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
447 // Calculate -1 casted to the right type...
448 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
449 uint64_t Val = ~0ULL; // All ones
450 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
451 return CU->getValue() == Val-1;
452 }
453
454 const ConstantSInt *CS = cast<ConstantSInt>(C);
455
456 // Calculate 0111111111..11111
457 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
458 int64_t Val = INT64_MAX; // All ones
459 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
460 return CS->getValue() == Val-1;
461}
462
463// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000464static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000465 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
466 return CU->getValue() == 1;
467
468 const ConstantSInt *CS = cast<ConstantSInt>(C);
469
470 // Calculate 1111111111000000000000
471 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
472 int64_t Val = -1; // All ones
473 Val <<= TypeBits-1; // Shift over to the right spot
474 return CS->getValue() == Val+1;
475}
476
477
Chris Lattner113f4f42002-06-25 16:13:24 +0000478Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000479 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000480 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000481
482 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000483 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
484 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000485
486 // and X, -1 == X
Chris Lattner83282632002-08-13 17:50:24 +0000487 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000488 if (RHS->isAllOnesValue())
489 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000490
Chris Lattnerbb74e222003-03-10 23:06:50 +0000491 Value *Op0NotVal = dyn_castNotVal(Op0);
492 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000493
494 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000495 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000496 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
497 Op1NotVal,I.getName()+".demorgan",
498 &I);
Chris Lattner3e327a42003-03-10 23:13:59 +0000499 WorkList.push_back(Or);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000500 return BinaryOperator::createNot(Or);
501 }
502
503 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
504 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000505
Chris Lattner113f4f42002-06-25 16:13:24 +0000506 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000507}
508
509
510
Chris Lattner113f4f42002-06-25 16:13:24 +0000511Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000512 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000513 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000514
515 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000516 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
517 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000518
519 // or X, -1 == -1
Chris Lattner83282632002-08-13 17:50:24 +0000520 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
Chris Lattnere6794492002-08-12 21:17:25 +0000521 if (RHS->isAllOnesValue())
522 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000523
Chris Lattner3e327a42003-03-10 23:13:59 +0000524 Value *Op0NotVal = dyn_castNotVal(Op0);
525 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000526
Chris Lattner3e327a42003-03-10 23:13:59 +0000527 if (Op1 == Op0NotVal) // ~A | A == -1
528 return ReplaceInstUsesWith(I,
529 ConstantIntegral::getAllOnesValue(I.getType()));
530
531 if (Op0 == Op1NotVal) // A | ~A == -1
532 return ReplaceInstUsesWith(I,
533 ConstantIntegral::getAllOnesValue(I.getType()));
534
535 // (~A | ~B) == (~(A & B)) - Demorgan's Law
536 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
537 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
538 Op1NotVal,I.getName()+".demorgan",
539 &I);
540 WorkList.push_back(And);
541 return BinaryOperator::createNot(And);
542 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000543
Chris Lattner113f4f42002-06-25 16:13:24 +0000544 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000545}
546
547
548
Chris Lattner113f4f42002-06-25 16:13:24 +0000549Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000550 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000551 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000552
553 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000554 if (Op0 == Op1)
555 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000556
Chris Lattner83282632002-08-13 17:50:24 +0000557 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000558 // xor X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000559 if (Op1C->isNullValue())
560 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000561
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000562 // Is this a "NOT" instruction?
563 if (Op1C->isAllOnesValue()) {
564 // xor (xor X, -1), -1 = not (not X) = X
Chris Lattnerbb74e222003-03-10 23:06:50 +0000565 if (Value *X = dyn_castNotVal(Op0))
Chris Lattner31ae8632002-08-14 17:51:49 +0000566 return ReplaceInstUsesWith(I, X);
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000567
568 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
569 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
570 if (SCI->use_size() == 1)
571 return new SetCondInst(SCI->getInverseCondition(),
572 SCI->getOperand(0), SCI->getOperand(1));
573 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000574 }
575
Chris Lattnerbb74e222003-03-10 23:06:50 +0000576 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000577 if (X == Op1)
578 return ReplaceInstUsesWith(I,
579 ConstantIntegral::getAllOnesValue(I.getType()));
580
Chris Lattnerbb74e222003-03-10 23:06:50 +0000581 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000582 if (X == Op0)
583 return ReplaceInstUsesWith(I,
584 ConstantIntegral::getAllOnesValue(I.getType()));
585
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000586 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
587 if (Op1I->getOpcode() == Instruction::Or)
588 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
589 cast<BinaryOperator>(Op1I)->swapOperands();
590 I.swapOperands();
591 std::swap(Op0, Op1);
592 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
593 I.swapOperands();
594 std::swap(Op0, Op1);
595 }
596
597 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
598 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
599 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
600 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000601 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000602 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
603 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000604 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
605 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000606 }
607 }
608
Chris Lattner7fb29e12003-03-11 00:12:48 +0000609 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
610 if (Constant *C1 = dyn_castMaskingAnd(Op0))
611 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +0000612 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000613 return BinaryOperator::create(Instruction::Or, Op0, Op1);
614
Chris Lattner113f4f42002-06-25 16:13:24 +0000615 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000616}
617
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000618// AddOne, SubOne - Add or subtract a constant one from an integer constant...
619static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000620 Constant *Result = ConstantExpr::get(Instruction::Add, C,
621 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000622 assert(Result && "Constant folding integer addition failed!");
623 return Result;
624}
625static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000626 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
627 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000628 assert(Result && "Constant folding integer addition failed!");
629 return Result;
630}
631
Chris Lattner1fc23f32002-05-09 20:11:54 +0000632// isTrueWhenEqual - Return true if the specified setcondinst instruction is
633// true when both operands are equal...
634//
Chris Lattner113f4f42002-06-25 16:13:24 +0000635static bool isTrueWhenEqual(Instruction &I) {
636 return I.getOpcode() == Instruction::SetEQ ||
637 I.getOpcode() == Instruction::SetGE ||
638 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000639}
640
Chris Lattner113f4f42002-06-25 16:13:24 +0000641Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000642 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000643 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
644 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000645
646 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000647 if (Op0 == Op1)
648 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000649
650 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000651 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
652 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
653
654 // setcc's with boolean values can always be turned into bitwise operations
655 if (Ty == Type::BoolTy) {
656 // If this is <, >, or !=, we can change this into a simple xor instruction
657 if (!isTrueWhenEqual(I))
658 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
659
660 // Otherwise we need to make a temporary intermediate instruction and insert
661 // it into the instruction stream. This is what we are after:
662 //
663 // seteq bool %A, %B -> ~(A^B)
664 // setle bool %A, %B -> ~A | B
665 // setge bool %A, %B -> A | ~B
666 //
667 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
668 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
669 I.getName()+"tmp");
670 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000671 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000672 }
673
674 // Handle the setXe cases...
675 assert(I.getOpcode() == Instruction::SetGE ||
676 I.getOpcode() == Instruction::SetLE);
677
678 if (I.getOpcode() == Instruction::SetGE)
679 std::swap(Op0, Op1); // Change setge -> setle
680
681 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000682 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000683 InsertNewInstBefore(Not, I);
684 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
685 }
686
687 // Check to see if we are doing one of many comparisons against constant
688 // integers at the end of their ranges...
689 //
690 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere967b342003-06-04 05:10:11 +0000691 if (CI->isNullValue()) {
692 if (I.getOpcode() == Instruction::SetNE)
693 return new CastInst(Op0, Type::BoolTy, I.getName());
694 else if (I.getOpcode() == Instruction::SetEQ) {
695 // seteq X, 0 -> not (cast X to bool)
696 Instruction *Val = new CastInst(Op0, Type::BoolTy, I.getName()+".not");
697 InsertNewInstBefore(Val, I);
698 return BinaryOperator::createNot(Val, I.getName());
699 }
700 }
Chris Lattner791ac1a2003-06-01 03:35:25 +0000701
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000702 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000703 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000704 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
705 return ReplaceInstUsesWith(I, ConstantBool::False);
706 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
707 return ReplaceInstUsesWith(I, ConstantBool::True);
708 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
709 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
710 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
711 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
712
Chris Lattnere6794492002-08-12 21:17:25 +0000713 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000714 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
715 return ReplaceInstUsesWith(I, ConstantBool::False);
716 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
717 return ReplaceInstUsesWith(I, ConstantBool::True);
718 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
719 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
720 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
721 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
722
723 // Comparing against a value really close to min or max?
724 } else if (isMinValuePlusOne(CI)) {
725 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
726 return BinaryOperator::create(Instruction::SetEQ, Op0,
727 SubOne(CI), I.getName());
728 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
729 return BinaryOperator::create(Instruction::SetNE, Op0,
730 SubOne(CI), I.getName());
731
732 } else if (isMaxValueMinusOne(CI)) {
733 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
734 return BinaryOperator::create(Instruction::SetEQ, Op0,
735 AddOne(CI), I.getName());
736 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
737 return BinaryOperator::create(Instruction::SetNE, Op0,
738 AddOne(CI), I.getName());
739 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000740 }
741
Chris Lattner113f4f42002-06-25 16:13:24 +0000742 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000743}
744
745
746
Chris Lattnere8d6c602003-03-10 19:16:08 +0000747Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000748 assert(I.getOperand(1)->getType() == Type::UByteTy);
749 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000750
751 // shl X, 0 == X and shr X, 0 == X
752 // shl 0, X == 0 and shr 0, X == 0
753 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000754 Op0 == Constant::getNullValue(Op0->getType()))
755 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000756
Chris Lattnere8d6c602003-03-10 19:16:08 +0000757 // If this is a shift of a shift, see if we can fold the two together...
758 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
759 if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
760 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
761 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
762 unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
763
764 // Check for (A << c1) << c2 and (A >> c1) >> c2
765 if (I.getOpcode() == Op0SI->getOpcode()) {
766 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
767 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
768 ConstantUInt::get(Type::UByteTy, Amt));
769 }
770
771 if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
772 // Calculate bitmask for what gets shifted off the edge...
773 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
774 if (I.getOpcode() == Instruction::Shr)
Chris Lattner34428442003-05-27 16:40:51 +0000775 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000776 else
Chris Lattner34428442003-05-27 16:40:51 +0000777 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000778
779 Instruction *Mask =
780 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
781 C, Op0SI->getOperand(0)->getName()+".mask",&I);
782 WorkList.push_back(Mask);
783
784 // Figure out what flavor of shift we should use...
785 if (ShiftAmt1 == ShiftAmt2)
786 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
787 else if (ShiftAmt1 < ShiftAmt2) {
788 return new ShiftInst(I.getOpcode(), Mask,
789 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
790 } else {
791 return new ShiftInst(Op0SI->getOpcode(), Mask,
792 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
793 }
794 }
795 }
796 }
797
Chris Lattnere6794492002-08-12 21:17:25 +0000798 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000799 // a signed value.
800 //
801 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattnere8d6c602003-03-10 19:16:08 +0000802 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
803 if (CUI->getValue() >= TypeBits &&
804 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
805 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000806
807 // Check to see if we are shifting left by 1. If so, turn it into an add
808 // instruction.
809 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
Chris Lattner3082c5a2003-02-18 19:28:33 +0000810 // Convert 'shl int %X, 1' to 'add int %X, %X'
Chris Lattner55f3d942002-09-10 23:04:09 +0000811 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
812
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000813 }
Chris Lattner2e0fb392002-10-08 16:16:40 +0000814
815 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
816 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
817 if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
818 return ReplaceInstUsesWith(I, CSI);
819
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000820 return 0;
821}
822
823
Chris Lattner48a44f72002-05-02 17:06:02 +0000824// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
825// instruction.
826//
Chris Lattner113f4f42002-06-25 16:13:24 +0000827static inline bool isEliminableCastOfCast(const CastInst &CI,
Chris Lattner48a44f72002-05-02 17:06:02 +0000828 const CastInst *CSrc) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000829 assert(CI.getOperand(0) == CSrc);
Chris Lattner48a44f72002-05-02 17:06:02 +0000830 const Type *SrcTy = CSrc->getOperand(0)->getType();
831 const Type *MidTy = CSrc->getType();
Chris Lattner113f4f42002-06-25 16:13:24 +0000832 const Type *DstTy = CI.getType();
Chris Lattner48a44f72002-05-02 17:06:02 +0000833
Chris Lattner650b6da2002-08-02 20:00:25 +0000834 // It is legal to eliminate the instruction if casting A->B->A if the sizes
835 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +0000836 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +0000837 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +0000838 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +0000839
840 // Allow free casting and conversion of sizes as long as the sign doesn't
841 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000842 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +0000843 unsigned SrcSize = SrcTy->getPrimitiveSize();
844 unsigned MidSize = MidTy->getPrimitiveSize();
845 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +0000846
Chris Lattner3732aca2002-08-15 16:15:25 +0000847 // Cases where we are monotonically decreasing the size of the type are
848 // always ok, regardless of what sign changes are going on.
849 //
Chris Lattner0bb75912002-08-14 23:21:10 +0000850 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000851 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +0000852
Chris Lattner555518c2002-09-23 23:39:43 +0000853 // Cases where the source and destination type are the same, but the middle
854 // type is bigger are noops.
855 //
856 if (SrcSize == DstSize && MidSize > SrcSize)
857 return true;
858
Chris Lattner3732aca2002-08-15 16:15:25 +0000859 // If we are monotonically growing, things are more complex.
860 //
861 if (SrcSize <= MidSize && MidSize <= DstSize) {
862 // We have eight combinations of signedness to worry about. Here's the
863 // table:
864 static const int SignTable[8] = {
865 // CODE, SrcSigned, MidSigned, DstSigned, Comment
866 1, // U U U Always ok
867 1, // U U S Always ok
868 3, // U S U Ok iff SrcSize != MidSize
869 3, // U S S Ok iff SrcSize != MidSize
870 0, // S U U Never ok
871 2, // S U S Ok iff MidSize == DstSize
872 1, // S S U Always ok
873 1, // S S S Always ok
874 };
875
876 // Choose an action based on the current entry of the signtable that this
877 // cast of cast refers to...
878 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
879 switch (SignTable[Row]) {
880 case 0: return false; // Never ok
881 case 1: return true; // Always ok
882 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
883 case 3: // Ok iff SrcSize != MidSize
884 return SrcSize != MidSize || SrcTy == Type::BoolTy;
885 default: assert(0 && "Bad entry in sign table!");
886 }
Chris Lattner3732aca2002-08-15 16:15:25 +0000887 }
Chris Lattner650b6da2002-08-02 20:00:25 +0000888 }
Chris Lattner48a44f72002-05-02 17:06:02 +0000889
890 // Otherwise, we cannot succeed. Specifically we do not want to allow things
891 // like: short -> ushort -> uint, because this can create wrong results if
892 // the input short is negative!
893 //
894 return false;
895}
896
897
898// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +0000899//
Chris Lattner113f4f42002-06-25 16:13:24 +0000900Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000901 // If the user is casting a value to the same type, eliminate this cast
902 // instruction...
Chris Lattnere6794492002-08-12 21:17:25 +0000903 if (CI.getType() == CI.getOperand(0)->getType())
904 return ReplaceInstUsesWith(CI, CI.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +0000905
Chris Lattner48a44f72002-05-02 17:06:02 +0000906 // If casting the result of another cast instruction, try to eliminate this
907 // one!
908 //
Chris Lattner650b6da2002-08-02 20:00:25 +0000909 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000910 if (isEliminableCastOfCast(CI, CSrc)) {
911 // This instruction now refers directly to the cast's src operand. This
912 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +0000913 CI.setOperand(0, CSrc->getOperand(0));
914 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +0000915 }
916
Chris Lattner650b6da2002-08-02 20:00:25 +0000917 // If this is an A->B->A cast, and we are dealing with integral types, try
918 // to convert this into a logical 'and' instruction.
919 //
920 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000921 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +0000922 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
923 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
924 assert(CSrc->getType() != Type::ULongTy &&
925 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +0000926 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +0000927 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
928 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
929 AndOp);
930 }
931 }
932
Chris Lattnerd0d51602003-06-21 23:12:02 +0000933 // If casting the result of a getelementptr instruction with no offset, turn
934 // this into a cast of the original pointer!
935 //
936 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CI.getOperand(0))) {
937 bool AllZeroOperands = true;
938 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
939 if (!isa<Constant>(GEP->getOperand(i)) ||
940 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
941 AllZeroOperands = false;
942 break;
943 }
944 if (AllZeroOperands) {
945 CI.setOperand(0, GEP->getOperand(0));
946 return &CI;
947 }
948 }
949
Chris Lattner260ab202002-04-18 17:39:14 +0000950 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +0000951}
952
Chris Lattner970c33a2003-06-19 17:00:31 +0000953// CallInst simplification
954//
955Instruction *InstCombiner::visitCallInst(CallInst &CI) {
956 if (transformConstExprCastCall(&CI)) return 0;
957 return 0;
958}
959
960// InvokeInst simplification
961//
962Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
963 if (transformConstExprCastCall(&II)) return 0;
964 return 0;
965}
966
967// getPromotedType - Return the specified type promoted as it would be to pass
968// though a va_arg area...
969static const Type *getPromotedType(const Type *Ty) {
970 switch (Ty->getPrimitiveID()) {
971 case Type::SByteTyID:
972 case Type::ShortTyID: return Type::IntTy;
973 case Type::UByteTyID:
974 case Type::UShortTyID: return Type::UIntTy;
975 case Type::FloatTyID: return Type::DoubleTy;
976 default: return Ty;
977 }
978}
979
980// transformConstExprCastCall - If the callee is a constexpr cast of a function,
981// attempt to move the cast to the arguments of the call/invoke.
982//
983bool InstCombiner::transformConstExprCastCall(CallSite CS) {
984 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
985 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
986 if (CE->getOpcode() != Instruction::Cast ||
987 !isa<ConstantPointerRef>(CE->getOperand(0)))
988 return false;
989 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
990 if (!isa<Function>(CPR->getValue())) return false;
991 Function *Callee = cast<Function>(CPR->getValue());
992 Instruction *Caller = CS.getInstruction();
993
994 // Okay, this is a cast from a function to a different type. Unless doing so
995 // would cause a type conversion of one of our arguments, change this call to
996 // be a direct call with arguments casted to the appropriate types.
997 //
998 const FunctionType *FT = Callee->getFunctionType();
999 const Type *OldRetTy = Caller->getType();
1000
1001 if (Callee->isExternal() &&
1002 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1003 return false; // Cannot transform this return value...
1004
1005 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1006 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1007
1008 CallSite::arg_iterator AI = CS.arg_begin();
1009 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1010 const Type *ParamTy = FT->getParamType(i);
1011 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1012 if (Callee->isExternal() && !isConvertible) return false;
1013 }
1014
1015 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1016 Callee->isExternal())
1017 return false; // Do not delete arguments unless we have a function body...
1018
1019 // Okay, we decided that this is a safe thing to do: go ahead and start
1020 // inserting cast instructions as necessary...
1021 std::vector<Value*> Args;
1022 Args.reserve(NumActualArgs);
1023
1024 AI = CS.arg_begin();
1025 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1026 const Type *ParamTy = FT->getParamType(i);
1027 if ((*AI)->getType() == ParamTy) {
1028 Args.push_back(*AI);
1029 } else {
1030 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1031 InsertNewInstBefore(Cast, *Caller);
1032 Args.push_back(Cast);
1033 }
1034 }
1035
1036 // If the function takes more arguments than the call was taking, add them
1037 // now...
1038 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1039 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1040
1041 // If we are removing arguments to the function, emit an obnoxious warning...
1042 if (FT->getNumParams() < NumActualArgs)
1043 if (!FT->isVarArg()) {
1044 std::cerr << "WARNING: While resolving call to function '"
1045 << Callee->getName() << "' arguments were dropped!\n";
1046 } else {
1047 // Add all of the arguments in their promoted form to the arg list...
1048 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1049 const Type *PTy = getPromotedType((*AI)->getType());
1050 if (PTy != (*AI)->getType()) {
1051 // Must promote to pass through va_arg area!
1052 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1053 InsertNewInstBefore(Cast, *Caller);
1054 Args.push_back(Cast);
1055 } else {
1056 Args.push_back(*AI);
1057 }
1058 }
1059 }
1060
1061 if (FT->getReturnType() == Type::VoidTy)
1062 Caller->setName(""); // Void type should not have a name...
1063
1064 Instruction *NC;
1065 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1066 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1067 Args, Caller->getName(), Caller);
1068 } else {
1069 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1070 }
1071
1072 // Insert a cast of the return type as necessary...
1073 Value *NV = NC;
1074 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1075 if (NV->getType() != Type::VoidTy) {
1076 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1077 InsertNewInstBefore(NC, *Caller);
1078 AddUsesToWorkList(*Caller);
1079 } else {
1080 NV = Constant::getNullValue(Caller->getType());
1081 }
1082 }
1083
1084 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1085 Caller->replaceAllUsesWith(NV);
1086 Caller->getParent()->getInstList().erase(Caller);
1087 removeFromWorkList(Caller);
1088 return true;
1089}
1090
1091
Chris Lattner48a44f72002-05-02 17:06:02 +00001092
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001093// PHINode simplification
1094//
Chris Lattner113f4f42002-06-25 16:13:24 +00001095Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001096 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +00001097 if (PN.getNumIncomingValues() == 1)
1098 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +00001099
1100 // Otherwise if all of the incoming values are the same for the PHI, replace
1101 // the PHI node with the incoming value.
1102 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +00001103 Value *InVal = 0;
1104 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1105 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1106 if (InVal && PN.getIncomingValue(i) != InVal)
1107 return 0; // Not the same, bail out.
1108 else
1109 InVal = PN.getIncomingValue(i);
1110
1111 // The only case that could cause InVal to be null is if we have a PHI node
1112 // that only has entries for itself. In this case, there is no entry into the
1113 // loop, so kill the PHI.
1114 //
1115 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001116
Chris Lattner9cd1e662002-08-20 15:35:35 +00001117 // All of the incoming values are the same, replace the PHI node now.
1118 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001119}
1120
Chris Lattner48a44f72002-05-02 17:06:02 +00001121
Chris Lattner113f4f42002-06-25 16:13:24 +00001122Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +00001123 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00001124 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001125 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +00001126 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001127 GEP.getNumOperands() == 1)
1128 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +00001129
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001130 // Combine Indices - If the source pointer to this getelementptr instruction
1131 // is a getelementptr instruction, combine the indices of the two
1132 // getelementptr instructions into a single instruction.
1133 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001134 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001135 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +00001136
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001137 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +00001138 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1139 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +00001140 // Replace: gep (gep %P, long C1), long C2, ...
1141 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +00001142 Value *Sum = ConstantExpr::get(Instruction::Add,
1143 cast<Constant>(Src->getOperand(1)),
1144 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +00001145 assert(Sum && "Constant folding of longs failed!?");
1146 GEP.setOperand(0, Src->getOperand(0));
1147 GEP.setOperand(1, Sum);
1148 AddUsesToWorkList(*Src); // Reduce use count of Src
1149 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +00001150 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +00001151 // Replace: gep (gep %P, long B), long A, ...
1152 // With: T = long A+B; gep %P, T, ...
1153 //
1154 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1155 GEP.getOperand(1),
1156 Src->getName()+".sum", &GEP);
1157 GEP.setOperand(0, Src->getOperand(0));
1158 GEP.setOperand(1, Sum);
1159 WorkList.push_back(cast<Instruction>(Sum));
1160 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00001161 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00001162 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001163 // Otherwise we can do the fold if the first index of the GEP is a zero
1164 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1165 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00001166 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1167 Constant::getNullValue(Type::LongTy)) {
1168 // If the src gep ends with a constant array index, merge this get into
1169 // it, even if we have a non-zero array index.
1170 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1171 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001172 }
1173
1174 if (!Indices.empty())
1175 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001176
1177 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1178 // GEP of global variable. If all of the indices for this GEP are
1179 // constants, we can promote this to a constexpr instead of an instruction.
1180
1181 // Scan for nonconstants...
1182 std::vector<Constant*> Indices;
1183 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1184 for (; I != E && isa<Constant>(*I); ++I)
1185 Indices.push_back(cast<Constant>(*I));
1186
1187 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001188 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001189 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1190
1191 // Replace all uses of the GEP with the new constexpr...
1192 return ReplaceInstUsesWith(GEP, CE);
1193 }
Chris Lattnerca081252001-12-14 16:52:21 +00001194 }
1195
Chris Lattnerca081252001-12-14 16:52:21 +00001196 return 0;
1197}
1198
Chris Lattner1085bdf2002-11-04 16:18:53 +00001199Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1200 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1201 if (AI.isArrayAllocation()) // Check C != 1
1202 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1203 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001204 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001205
1206 // Create and insert the replacement instruction...
1207 if (isa<MallocInst>(AI))
1208 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001209 else {
1210 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001211 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001212 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001213
1214 // Scan to the end of the allocation instructions, to skip over a block of
1215 // allocas if possible...
1216 //
1217 BasicBlock::iterator It = New;
1218 while (isa<AllocationInst>(*It)) ++It;
1219
1220 // Now that I is pointing to the first non-allocation-inst in the block,
1221 // insert our getelementptr instruction...
1222 //
1223 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1224 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1225
1226 // Now make everything use the getelementptr instead of the original
1227 // allocation.
1228 ReplaceInstUsesWith(AI, V);
1229 return &AI;
1230 }
1231 return 0;
1232}
1233
Chris Lattner9eef8a72003-06-04 04:46:00 +00001234Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1235 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner45789ac2003-06-05 20:12:51 +00001236 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
Chris Lattnere967b342003-06-04 05:10:11 +00001237 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1238 BasicBlock *TrueDest = BI.getSuccessor(0);
1239 BasicBlock *FalseDest = BI.getSuccessor(1);
1240 // Swap Destinations and condition...
1241 BI.setCondition(V);
1242 BI.setSuccessor(0, FalseDest);
1243 BI.setSuccessor(1, TrueDest);
1244 return &BI;
1245 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00001246 return 0;
1247}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001248
Chris Lattnerca081252001-12-14 16:52:21 +00001249
Chris Lattner99f48c62002-09-02 04:59:56 +00001250void InstCombiner::removeFromWorkList(Instruction *I) {
1251 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1252 WorkList.end());
1253}
1254
Chris Lattner113f4f42002-06-25 16:13:24 +00001255bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001256 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001257
Chris Lattner260ab202002-04-18 17:39:14 +00001258 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001259
1260 while (!WorkList.empty()) {
1261 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1262 WorkList.pop_back();
1263
Misha Brukman632df282002-10-29 23:06:16 +00001264 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001265 // Check to see if we can DIE the instruction...
1266 if (isInstructionTriviallyDead(I)) {
1267 // Add operands to the worklist...
1268 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1269 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1270 WorkList.push_back(Op);
1271
1272 ++NumDeadInst;
1273 BasicBlock::iterator BBI = I;
1274 if (dceInstruction(BBI)) {
1275 removeFromWorkList(I);
1276 continue;
1277 }
1278 }
1279
Misha Brukman632df282002-10-29 23:06:16 +00001280 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001281 if (Constant *C = ConstantFoldInstruction(I)) {
1282 // Add operands to the worklist...
1283 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1284 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1285 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001286 ReplaceInstUsesWith(*I, C);
1287
Chris Lattner99f48c62002-09-02 04:59:56 +00001288 ++NumConstProp;
1289 BasicBlock::iterator BBI = I;
1290 if (dceInstruction(BBI)) {
1291 removeFromWorkList(I);
1292 continue;
1293 }
1294 }
1295
Chris Lattnerca081252001-12-14 16:52:21 +00001296 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001297 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001298 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001299 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001300 if (Result != I) {
1301 // Instructions can end up on the worklist more than once. Make sure
1302 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001303 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001304 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001305 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001306 BasicBlock::iterator II = I;
1307
1308 // If the instruction was modified, it's possible that it is now dead.
1309 // if so, remove it.
1310 if (dceInstruction(II)) {
1311 // Instructions may end up in the worklist more than once. Erase them
1312 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001313 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001314 Result = 0;
1315 }
Chris Lattner053c0932002-05-14 15:24:07 +00001316 }
Chris Lattner260ab202002-04-18 17:39:14 +00001317
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001318 if (Result) {
1319 WorkList.push_back(Result);
1320 AddUsesToWorkList(*Result);
1321 }
Chris Lattner260ab202002-04-18 17:39:14 +00001322 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001323 }
1324 }
1325
Chris Lattner260ab202002-04-18 17:39:14 +00001326 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001327}
1328
1329Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001330 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001331}