blob: 7054661244962aeee874b9fc2751156b43b6c3b5 [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 Lattner0f1d8a32003-06-26 05:06:25 +000025#include "llvm/GlobalVariable.h"
Chris Lattner60a65912002-02-12 21:07:25 +000026#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000027#include "llvm/Support/InstVisitor.h"
Chris Lattner970c33a2003-06-19 17:00:31 +000028#include "llvm/Support/CallSite.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000029#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000030#include <algorithm>
Chris Lattnerca081252001-12-14 16:52:21 +000031
Chris Lattner260ab202002-04-18 17:39:14 +000032namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000033 Statistic<> NumCombined ("instcombine", "Number of insts combined");
34 Statistic<> NumConstProp("instcombine", "Number of constant folds");
35 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
36
Chris Lattnerc8e66542002-04-27 06:56:12 +000037 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000038 public InstVisitor<InstCombiner, Instruction*> {
39 // Worklist of all of the instructions that need to be simplified.
40 std::vector<Instruction*> WorkList;
41
Chris Lattner113f4f42002-06-25 16:13:24 +000042 void AddUsesToWorkList(Instruction &I) {
Chris Lattner260ab202002-04-18 17:39:14 +000043 // The instruction was simplified, add all users of the instruction to
44 // the work lists because they might get more simplified now...
45 //
Chris Lattner113f4f42002-06-25 16:13:24 +000046 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000047 UI != UE; ++UI)
48 WorkList.push_back(cast<Instruction>(*UI));
49 }
50
Chris Lattner99f48c62002-09-02 04:59:56 +000051 // removeFromWorkList - remove all instances of I from the worklist.
52 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000053 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000054 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000055
Chris Lattnerf12cc842002-04-28 21:27:06 +000056 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000057 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000058 }
59
Chris Lattner260ab202002-04-18 17:39:14 +000060 // Visitation implementation - Implement instruction combining for different
61 // instruction types. The semantics are as follows:
62 // Return Value:
63 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000064 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000065 // otherwise - Change was made, replace I with returned instruction
66 //
Chris Lattner113f4f42002-06-25 16:13:24 +000067 Instruction *visitAdd(BinaryOperator &I);
68 Instruction *visitSub(BinaryOperator &I);
69 Instruction *visitMul(BinaryOperator &I);
70 Instruction *visitDiv(BinaryOperator &I);
71 Instruction *visitRem(BinaryOperator &I);
72 Instruction *visitAnd(BinaryOperator &I);
73 Instruction *visitOr (BinaryOperator &I);
74 Instruction *visitXor(BinaryOperator &I);
75 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +000076 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +000077 Instruction *visitCastInst(CastInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +000078 Instruction *visitCallInst(CallInst &CI);
79 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +000080 Instruction *visitPHINode(PHINode &PN);
81 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +000082 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +000083 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +000084 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner260ab202002-04-18 17:39:14 +000085
86 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +000087 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +000088
Chris Lattner970c33a2003-06-19 17:00:31 +000089 private:
90 bool transformConstExprCastCall(CallSite CS);
91
Chris Lattner6d14f2a2002-08-09 23:47:40 +000092 // InsertNewInstBefore - insert an instruction New before instruction Old
93 // in the program. Add the new instruction to the worklist.
94 //
95 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +000096 assert(New && New->getParent() == 0 &&
97 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +000098 BasicBlock *BB = Old.getParent();
99 BB->getInstList().insert(&Old, New); // Insert inst
100 WorkList.push_back(New); // Add to worklist
101 }
102
103 // ReplaceInstUsesWith - This method is to be used when an instruction is
104 // found to be dead, replacable with another preexisting expression. Here
105 // we add all uses of I to the worklist, replace all uses of I with the new
106 // value, then return I, so that the inst combiner will know that I was
107 // modified.
108 //
109 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
110 AddUsesToWorkList(I); // Add all modified instrs to worklist
111 I.replaceAllUsesWith(V);
112 return &I;
113 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000114
115 // SimplifyCommutative - This performs a few simplifications for commutative
116 // operators...
117 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattner260ab202002-04-18 17:39:14 +0000118 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000119
Chris Lattnerc8b70922002-07-26 21:12:46 +0000120 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000121}
122
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000123// getComplexity: Assign a complexity or rank value to LLVM Values...
124// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
125static unsigned getComplexity(Value *V) {
126 if (isa<Instruction>(V)) {
127 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
128 return 2;
129 return 3;
130 }
131 if (isa<Argument>(V)) return 2;
132 return isa<Constant>(V) ? 0 : 1;
133}
Chris Lattner260ab202002-04-18 17:39:14 +0000134
Chris Lattner7fb29e12003-03-11 00:12:48 +0000135// isOnlyUse - Return true if this instruction will be deleted if we stop using
136// it.
137static bool isOnlyUse(Value *V) {
138 return V->use_size() == 1 || isa<Constant>(V);
139}
140
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000141// SimplifyCommutative - This performs a few simplifications for commutative
142// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000143//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000144// 1. Order operands such that they are listed from right (least complex) to
145// left (most complex). This puts constants before unary operators before
146// binary operators.
147//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000148// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
149// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000150//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000151bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000152 bool Changed = false;
153 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
154 Changed = !I.swapOperands();
155
156 if (!I.isAssociative()) return Changed;
157 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000158 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
159 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
160 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000161 Constant *Folded = ConstantExpr::get(I.getOpcode(),
162 cast<Constant>(I.getOperand(1)),
163 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000164 I.setOperand(0, Op->getOperand(0));
165 I.setOperand(1, Folded);
166 return true;
167 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
168 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
169 isOnlyUse(Op) && isOnlyUse(Op1)) {
170 Constant *C1 = cast<Constant>(Op->getOperand(1));
171 Constant *C2 = cast<Constant>(Op1->getOperand(1));
172
173 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000174 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000175 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
176 Op1->getOperand(0),
177 Op1->getName(), &I);
178 WorkList.push_back(New);
179 I.setOperand(0, New);
180 I.setOperand(1, Folded);
181 return true;
182 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000183 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000184 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000185}
Chris Lattnerca081252001-12-14 16:52:21 +0000186
Chris Lattnerbb74e222003-03-10 23:06:50 +0000187// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
188// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000189//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000190static inline Value *dyn_castNegVal(Value *V) {
191 if (BinaryOperator::isNeg(V))
192 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
193
Chris Lattner9244df62003-04-30 22:19:10 +0000194 // Constants can be considered to be negated values if they can be folded...
195 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000196 return ConstantExpr::get(Instruction::Sub,
197 Constant::getNullValue(V->getType()), C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000198 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000199}
200
Chris Lattnerbb74e222003-03-10 23:06:50 +0000201static inline Value *dyn_castNotVal(Value *V) {
202 if (BinaryOperator::isNot(V))
203 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
204
205 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000206 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000207 return ConstantExpr::get(Instruction::Xor,
208 ConstantIntegral::getAllOnesValue(C->getType()),C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000209 return 0;
210}
211
Chris Lattner7fb29e12003-03-11 00:12:48 +0000212// dyn_castFoldableMul - If this value is a multiply that can be folded into
213// other computations (because it has a constant operand), return the
214// non-constant operand of the multiply.
215//
216static inline Value *dyn_castFoldableMul(Value *V) {
217 if (V->use_size() == 1 && V->getType()->isInteger())
218 if (Instruction *I = dyn_cast<Instruction>(V))
219 if (I->getOpcode() == Instruction::Mul)
220 if (isa<Constant>(I->getOperand(1)))
221 return I->getOperand(0);
222 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000223}
Chris Lattner31ae8632002-08-14 17:51:49 +0000224
Chris Lattner7fb29e12003-03-11 00:12:48 +0000225// dyn_castMaskingAnd - If this value is an And instruction masking a value with
226// a constant, return the constant being anded with.
227//
228static inline Constant *dyn_castMaskingAnd(Value *V) {
229 if (Instruction *I = dyn_cast<Instruction>(V))
230 if (I->getOpcode() == Instruction::And)
231 return dyn_cast<Constant>(I->getOperand(1));
232
233 // If this is a constant, it acts just like we were masking with it.
234 return dyn_cast<Constant>(V);
235}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000236
237// Log2 - Calculate the log base 2 for the specified value if it is exactly a
238// power of 2.
239static unsigned Log2(uint64_t Val) {
240 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
241 unsigned Count = 0;
242 while (Val != 1) {
243 if (Val & 1) return 0; // Multiple bits set?
244 Val >>= 1;
245 ++Count;
246 }
247 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000248}
249
Chris Lattner113f4f42002-06-25 16:13:24 +0000250Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000251 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000252 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000253
254 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000255 if (RHS == Constant::getNullValue(I.getType()))
256 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000257
Chris Lattner147e9752002-05-08 22:46:53 +0000258 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000259 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000260 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000261
262 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000263 if (!isa<Constant>(RHS))
264 if (Value *V = dyn_castNegVal(RHS))
265 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000266
Chris Lattner57c8d992003-02-18 19:57:07 +0000267 // X*C + X --> X * (C+1)
268 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000269 Constant *CP1 =
270 ConstantExpr::get(Instruction::Add,
271 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
272 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000273 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
274 }
275
276 // X + X*C --> X * (C+1)
277 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000278 Constant *CP1 =
279 ConstantExpr::get(Instruction::Add,
280 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
281 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000282 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
283 }
284
Chris Lattner7fb29e12003-03-11 00:12:48 +0000285 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
286 if (Constant *C1 = dyn_castMaskingAnd(LHS))
287 if (Constant *C2 = dyn_castMaskingAnd(RHS))
Chris Lattner34428442003-05-27 16:40:51 +0000288 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000289 return BinaryOperator::create(Instruction::Or, LHS, RHS);
290
Chris Lattner113f4f42002-06-25 16:13:24 +0000291 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000292}
293
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000294// isSignBit - Return true if the value represented by the constant only has the
295// highest order bit set.
296static bool isSignBit(ConstantInt *CI) {
297 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
298 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
299}
300
Chris Lattner113f4f42002-06-25 16:13:24 +0000301Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000302 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000303
Chris Lattnere6794492002-08-12 21:17:25 +0000304 if (Op0 == Op1) // sub X, X -> 0
305 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000306
Chris Lattnere6794492002-08-12 21:17:25 +0000307 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000308 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000309 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000310
Chris Lattner3082c5a2003-02-18 19:28:33 +0000311 // Replace (-1 - A) with (~A)...
312 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
313 if (C->isAllOnesValue())
314 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000315
Chris Lattner3082c5a2003-02-18 19:28:33 +0000316 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
317 if (Op1I->use_size() == 1) {
318 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
319 // is not used by anyone else...
320 //
321 if (Op1I->getOpcode() == Instruction::Sub) {
322 // Swap the two operands of the subexpr...
323 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
324 Op1I->setOperand(0, IIOp1);
325 Op1I->setOperand(1, IIOp0);
326
327 // Create the new top level add instruction...
328 return BinaryOperator::create(Instruction::Add, Op0, Op1);
329 }
330
331 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
332 //
333 if (Op1I->getOpcode() == Instruction::And &&
334 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
335 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
336
337 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
338 return BinaryOperator::create(Instruction::And, Op0, NewNot);
339 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000340
341 // X - X*C --> X * (1-C)
342 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000343 Constant *CP1 =
344 ConstantExpr::get(Instruction::Sub,
345 ConstantInt::get(I.getType(), 1),
346 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000347 assert(CP1 && "Couldn't constant fold 1-C?");
348 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
349 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000350 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000351
Chris Lattner57c8d992003-02-18 19:57:07 +0000352 // X*C - X --> X * (C-1)
353 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000354 Constant *CP1 =
355 ConstantExpr::get(Instruction::Sub,
356 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
357 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000358 assert(CP1 && "Couldn't constant fold C - 1?");
359 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
360 }
361
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000362 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000363}
364
Chris Lattner113f4f42002-06-25 16:13:24 +0000365Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000366 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000367 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000368
Chris Lattnere6794492002-08-12 21:17:25 +0000369 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000370 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
371 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
372 const Type *Ty = CI->getType();
Chris Lattner6077c312003-07-23 15:22:26 +0000373 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000374 switch (Val) {
Chris Lattner35236d82003-06-25 17:09:20 +0000375 case -1: // X * -1 -> -X
376 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner3082c5a2003-02-18 19:28:33 +0000377 case 0:
378 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
379 case 1:
380 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
381 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
382 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
383 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000384
Chris Lattner3082c5a2003-02-18 19:28:33 +0000385 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
386 return new ShiftInst(Instruction::Shl, Op0,
387 ConstantUInt::get(Type::UByteTy, C));
388 } else {
389 ConstantFP *Op1F = cast<ConstantFP>(Op1);
390 if (Op1F->isNullValue())
391 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000392
Chris Lattner3082c5a2003-02-18 19:28:33 +0000393 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
394 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
395 if (Op1F->getValue() == 1.0)
396 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
397 }
Chris Lattner260ab202002-04-18 17:39:14 +0000398 }
399
Chris Lattner934a64cf2003-03-10 23:23:04 +0000400 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
401 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
402 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
403
Chris Lattner113f4f42002-06-25 16:13:24 +0000404 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000405}
406
Chris Lattner113f4f42002-06-25 16:13:24 +0000407Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000408 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000409 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000410 if (RHS->equalsInt(1))
411 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000412
413 // Check to see if this is an unsigned division with an exact power of 2,
414 // if so, convert to a right shift.
415 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
416 if (uint64_t Val = C->getValue()) // Don't break X / 0
417 if (uint64_t C = Log2(Val))
418 return new ShiftInst(Instruction::Shr, I.getOperand(0),
419 ConstantUInt::get(Type::UByteTy, C));
420 }
421
422 // 0 / X == 0, we don't need to preserve faults!
423 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
424 if (LHS->equalsInt(0))
425 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
426
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000427 return 0;
428}
429
430
Chris Lattner113f4f42002-06-25 16:13:24 +0000431Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000432 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
433 if (RHS->equalsInt(1)) // X % 1 == 0
434 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
435
436 // Check to see if this is an unsigned remainder with an exact power of 2,
437 // if so, convert to a bitwise and.
438 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
439 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
440 if (Log2(Val))
441 return BinaryOperator::create(Instruction::And, I.getOperand(0),
442 ConstantUInt::get(I.getType(), Val-1));
443 }
444
445 // 0 % X == 0, we don't need to preserve faults!
446 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
447 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000448 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
449
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000450 return 0;
451}
452
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000453// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000454static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000455 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
456 // Calculate -1 casted to the right type...
457 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
458 uint64_t Val = ~0ULL; // All ones
459 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
460 return CU->getValue() == Val-1;
461 }
462
463 const ConstantSInt *CS = cast<ConstantSInt>(C);
464
465 // Calculate 0111111111..11111
466 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
467 int64_t Val = INT64_MAX; // All ones
468 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
469 return CS->getValue() == Val-1;
470}
471
472// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000473static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000474 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
475 return CU->getValue() == 1;
476
477 const ConstantSInt *CS = cast<ConstantSInt>(C);
478
479 // Calculate 1111111111000000000000
480 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
481 int64_t Val = -1; // All ones
482 Val <<= TypeBits-1; // Shift over to the right spot
483 return CS->getValue() == Val+1;
484}
485
486
Chris Lattner113f4f42002-06-25 16:13:24 +0000487Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000488 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000489 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000490
491 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000492 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
493 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000494
495 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +0000496 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000497 if (RHS->isAllOnesValue())
498 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000499
Chris Lattner16464b32003-07-23 19:25:52 +0000500 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
501 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
502 if (Op0I->getOpcode() == Instruction::Xor) {
503 if (isOnlyUse(Op0)) {
504 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
505 std::string Op0Name = Op0I->getName(); Op0I->setName("");
506 Instruction *And = BinaryOperator::create(Instruction::And,
507 Op0I->getOperand(0), RHS,
508 Op0Name);
509 InsertNewInstBefore(And, I);
510 return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
511 }
512 } else if (Op0I->getOpcode() == Instruction::Or) {
513 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
514 if ((*RHS & *Op0CI)->isNullValue())
515 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
516 RHS);
517
518 Constant *Together = *RHS & *Op0CI;
519 if (Together == RHS) // (X | C) & C --> C
520 return ReplaceInstUsesWith(I, RHS);
521
522 if (isOnlyUse(Op0)) {
523 if (Together != Op0CI) {
524 // (X | C1) & C2 --> (X | (C1&C2)) & C2
525 std::string Op0Name = Op0I->getName(); Op0I->setName("");
526 Instruction *Or = BinaryOperator::create(Instruction::Or,
527 Op0I->getOperand(0),
528 Together, Op0Name);
529 InsertNewInstBefore(Or, I);
530 return BinaryOperator::create(Instruction::And, Or, RHS);
531 }
532 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000533 }
534 }
535
Chris Lattnerbb74e222003-03-10 23:06:50 +0000536 Value *Op0NotVal = dyn_castNotVal(Op0);
537 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000538
539 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000540 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000541 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
Chris Lattner49b47ae2003-07-23 17:57:01 +0000542 Op1NotVal,I.getName()+".demorgan");
543 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000544 return BinaryOperator::createNot(Or);
545 }
546
547 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
548 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000549
Chris Lattner113f4f42002-06-25 16:13:24 +0000550 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000551}
552
553
554
Chris Lattner113f4f42002-06-25 16:13:24 +0000555Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000556 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000557 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000558
559 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000560 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
561 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000562
563 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +0000564 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000565 if (RHS->isAllOnesValue())
566 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000567
Chris Lattner8f0d1562003-07-23 18:29:44 +0000568 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
569 // (X & C1) | C2 --> (X | C2) & (C1|C2)
570 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
571 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
572 std::string Op0Name = Op0I->getName(); Op0I->setName("");
573 Instruction *Or = BinaryOperator::create(Instruction::Or,
574 Op0I->getOperand(0), RHS,
575 Op0Name);
576 InsertNewInstBefore(Or, I);
577 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
578 }
579
580 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
581 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
582 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
583 std::string Op0Name = Op0I->getName(); Op0I->setName("");
584 Instruction *Or = BinaryOperator::create(Instruction::Or,
585 Op0I->getOperand(0), RHS,
586 Op0Name);
587 InsertNewInstBefore(Or, I);
588 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
589 }
590 }
591 }
592
Chris Lattner3e327a42003-03-10 23:13:59 +0000593 Value *Op0NotVal = dyn_castNotVal(Op0);
594 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000595
Chris Lattner3e327a42003-03-10 23:13:59 +0000596 if (Op1 == Op0NotVal) // ~A | A == -1
597 return ReplaceInstUsesWith(I,
598 ConstantIntegral::getAllOnesValue(I.getType()));
599
600 if (Op0 == Op1NotVal) // A | ~A == -1
601 return ReplaceInstUsesWith(I,
602 ConstantIntegral::getAllOnesValue(I.getType()));
603
604 // (~A | ~B) == (~(A & B)) - Demorgan's Law
605 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
606 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
607 Op1NotVal,I.getName()+".demorgan",
608 &I);
609 WorkList.push_back(And);
610 return BinaryOperator::createNot(And);
611 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000612
Chris Lattner113f4f42002-06-25 16:13:24 +0000613 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000614}
615
616
617
Chris Lattner113f4f42002-06-25 16:13:24 +0000618Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000619 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000621
622 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000623 if (Op0 == Op1)
624 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000625
Chris Lattner83282632002-08-13 17:50:24 +0000626 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000627 // xor X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000628 if (Op1C->isNullValue())
629 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000630
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000631 // Is this a "NOT" instruction?
632 if (Op1C->isAllOnesValue()) {
633 // xor (xor X, -1), -1 = not (not X) = X
Chris Lattnerbb74e222003-03-10 23:06:50 +0000634 if (Value *X = dyn_castNotVal(Op0))
Chris Lattner31ae8632002-08-14 17:51:49 +0000635 return ReplaceInstUsesWith(I, X);
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000636
637 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
638 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
639 if (SCI->use_size() == 1)
640 return new SetCondInst(SCI->getInverseCondition(),
641 SCI->getOperand(0), SCI->getOperand(1));
642 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000643 }
644
Chris Lattnerbb74e222003-03-10 23:06:50 +0000645 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000646 if (X == Op1)
647 return ReplaceInstUsesWith(I,
648 ConstantIntegral::getAllOnesValue(I.getType()));
649
Chris Lattnerbb74e222003-03-10 23:06:50 +0000650 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000651 if (X == Op0)
652 return ReplaceInstUsesWith(I,
653 ConstantIntegral::getAllOnesValue(I.getType()));
654
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000655 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
656 if (Op1I->getOpcode() == Instruction::Or)
657 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
658 cast<BinaryOperator>(Op1I)->swapOperands();
659 I.swapOperands();
660 std::swap(Op0, Op1);
661 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
662 I.swapOperands();
663 std::swap(Op0, Op1);
664 }
665
666 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
667 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
668 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
669 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000670 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000671 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
672 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000673 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
674 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000675 }
676 }
677
Chris Lattner7fb29e12003-03-11 00:12:48 +0000678 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
679 if (Constant *C1 = dyn_castMaskingAnd(Op0))
680 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +0000681 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000682 return BinaryOperator::create(Instruction::Or, Op0, Op1);
683
Chris Lattner113f4f42002-06-25 16:13:24 +0000684 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000685}
686
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000687// AddOne, SubOne - Add or subtract a constant one from an integer constant...
688static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000689 Constant *Result = ConstantExpr::get(Instruction::Add, C,
690 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000691 assert(Result && "Constant folding integer addition failed!");
692 return Result;
693}
694static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000695 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
696 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000697 assert(Result && "Constant folding integer addition failed!");
698 return Result;
699}
700
Chris Lattner1fc23f32002-05-09 20:11:54 +0000701// isTrueWhenEqual - Return true if the specified setcondinst instruction is
702// true when both operands are equal...
703//
Chris Lattner113f4f42002-06-25 16:13:24 +0000704static bool isTrueWhenEqual(Instruction &I) {
705 return I.getOpcode() == Instruction::SetEQ ||
706 I.getOpcode() == Instruction::SetGE ||
707 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000708}
709
Chris Lattner113f4f42002-06-25 16:13:24 +0000710Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000711 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000712 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
713 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000714
715 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000716 if (Op0 == Op1)
717 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000718
719 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000720 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
721 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
722
723 // setcc's with boolean values can always be turned into bitwise operations
724 if (Ty == Type::BoolTy) {
725 // If this is <, >, or !=, we can change this into a simple xor instruction
726 if (!isTrueWhenEqual(I))
727 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
728
729 // Otherwise we need to make a temporary intermediate instruction and insert
730 // it into the instruction stream. This is what we are after:
731 //
732 // seteq bool %A, %B -> ~(A^B)
733 // setle bool %A, %B -> ~A | B
734 // setge bool %A, %B -> A | ~B
735 //
736 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
737 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
738 I.getName()+"tmp");
739 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000740 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000741 }
742
743 // Handle the setXe cases...
744 assert(I.getOpcode() == Instruction::SetGE ||
745 I.getOpcode() == Instruction::SetLE);
746
747 if (I.getOpcode() == Instruction::SetGE)
748 std::swap(Op0, Op1); // Change setge -> setle
749
750 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000751 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000752 InsertNewInstBefore(Not, I);
753 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
754 }
755
756 // Check to see if we are doing one of many comparisons against constant
757 // integers at the end of their ranges...
758 //
759 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000760 // Simplify seteq and setne instructions...
761 if (I.getOpcode() == Instruction::SetEQ ||
762 I.getOpcode() == Instruction::SetNE) {
763 bool isSetNE = I.getOpcode() == Instruction::SetNE;
764
765 if (CI->isNullValue()) { // Simplify [seteq|setne] X, 0
766 CastInst *Val = new CastInst(Op0, Type::BoolTy, I.getName()+".not");
767 if (isSetNE) return Val;
768
Chris Lattnere967b342003-06-04 05:10:11 +0000769 // seteq X, 0 -> not (cast X to bool)
Chris Lattnere967b342003-06-04 05:10:11 +0000770 InsertNewInstBefore(Val, I);
771 return BinaryOperator::createNot(Val, I.getName());
772 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000773
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000774 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000775 // operand is a constant, simplify a bit.
776 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
777 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1)))
778 if (BO->getOpcode() == Instruction::Or) {
779 // If bits are being or'd in that are not present in the constant we
780 // are comparing against, then the comparison could never succeed!
781 if (!(*BOC & *~*CI)->isNullValue())
782 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
783 } else if (BO->getOpcode() == Instruction::And) {
784 // If bits are being compared against that are and'd out, then the
785 // comparison can never succeed!
786 if (!(*CI & *~*BOC)->isNullValue())
787 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000788 } else if (BO->getOpcode() == Instruction::Xor) {
789 // For the xor case, we can always just xor the two constants
790 // together, potentially eliminating the explicit xor.
791 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
792 *CI ^ *BOC);
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000793 }
Chris Lattnere967b342003-06-04 05:10:11 +0000794 }
Chris Lattner791ac1a2003-06-01 03:35:25 +0000795
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000796 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000797 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000798 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
799 return ReplaceInstUsesWith(I, ConstantBool::False);
800 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
801 return ReplaceInstUsesWith(I, ConstantBool::True);
802 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
803 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
804 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
805 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
806
Chris Lattnere6794492002-08-12 21:17:25 +0000807 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000808 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
809 return ReplaceInstUsesWith(I, ConstantBool::False);
810 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
811 return ReplaceInstUsesWith(I, ConstantBool::True);
812 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
813 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
814 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
815 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
816
817 // Comparing against a value really close to min or max?
818 } else if (isMinValuePlusOne(CI)) {
819 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
820 return BinaryOperator::create(Instruction::SetEQ, Op0,
821 SubOne(CI), I.getName());
822 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
823 return BinaryOperator::create(Instruction::SetNE, Op0,
824 SubOne(CI), I.getName());
825
826 } else if (isMaxValueMinusOne(CI)) {
827 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
828 return BinaryOperator::create(Instruction::SetEQ, Op0,
829 AddOne(CI), I.getName());
830 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
831 return BinaryOperator::create(Instruction::SetNE, Op0,
832 AddOne(CI), I.getName());
833 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000834 }
835
Chris Lattner113f4f42002-06-25 16:13:24 +0000836 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000837}
838
839
840
Chris Lattnere8d6c602003-03-10 19:16:08 +0000841Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000842 assert(I.getOperand(1)->getType() == Type::UByteTy);
843 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000844
845 // shl X, 0 == X and shr X, 0 == X
846 // shl 0, X == 0 and shr 0, X == 0
847 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000848 Op0 == Constant::getNullValue(Op0->getType()))
849 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000850
Chris Lattnere8d6c602003-03-10 19:16:08 +0000851 // If this is a shift of a shift, see if we can fold the two together...
852 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
853 if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
854 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
855 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
856 unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
857
858 // Check for (A << c1) << c2 and (A >> c1) >> c2
859 if (I.getOpcode() == Op0SI->getOpcode()) {
860 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
861 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
862 ConstantUInt::get(Type::UByteTy, Amt));
863 }
864
865 if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
866 // Calculate bitmask for what gets shifted off the edge...
867 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
868 if (I.getOpcode() == Instruction::Shr)
Chris Lattner34428442003-05-27 16:40:51 +0000869 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000870 else
Chris Lattner34428442003-05-27 16:40:51 +0000871 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000872
873 Instruction *Mask =
874 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
875 C, Op0SI->getOperand(0)->getName()+".mask",&I);
876 WorkList.push_back(Mask);
877
878 // Figure out what flavor of shift we should use...
879 if (ShiftAmt1 == ShiftAmt2)
880 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
881 else if (ShiftAmt1 < ShiftAmt2) {
882 return new ShiftInst(I.getOpcode(), Mask,
883 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
884 } else {
885 return new ShiftInst(Op0SI->getOpcode(), Mask,
886 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
887 }
888 }
889 }
890 }
891
Chris Lattnere6794492002-08-12 21:17:25 +0000892 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000893 // a signed value.
894 //
895 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattnere8d6c602003-03-10 19:16:08 +0000896 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
897 if (CUI->getValue() >= TypeBits &&
898 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
899 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000900
901 // Check to see if we are shifting left by 1. If so, turn it into an add
902 // instruction.
903 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
Chris Lattner3082c5a2003-02-18 19:28:33 +0000904 // Convert 'shl int %X, 1' to 'add int %X, %X'
Chris Lattner55f3d942002-09-10 23:04:09 +0000905 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
906
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000907 }
Chris Lattner2e0fb392002-10-08 16:16:40 +0000908
909 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
910 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
911 if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
912 return ReplaceInstUsesWith(I, CSI);
913
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000914 return 0;
915}
916
917
Chris Lattner48a44f72002-05-02 17:06:02 +0000918// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
919// instruction.
920//
Chris Lattner113f4f42002-06-25 16:13:24 +0000921static inline bool isEliminableCastOfCast(const CastInst &CI,
Chris Lattner48a44f72002-05-02 17:06:02 +0000922 const CastInst *CSrc) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000923 assert(CI.getOperand(0) == CSrc);
Chris Lattner48a44f72002-05-02 17:06:02 +0000924 const Type *SrcTy = CSrc->getOperand(0)->getType();
925 const Type *MidTy = CSrc->getType();
Chris Lattner113f4f42002-06-25 16:13:24 +0000926 const Type *DstTy = CI.getType();
Chris Lattner48a44f72002-05-02 17:06:02 +0000927
Chris Lattner650b6da2002-08-02 20:00:25 +0000928 // It is legal to eliminate the instruction if casting A->B->A if the sizes
929 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +0000930 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +0000931 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +0000932 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +0000933
934 // Allow free casting and conversion of sizes as long as the sign doesn't
935 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000936 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +0000937 unsigned SrcSize = SrcTy->getPrimitiveSize();
938 unsigned MidSize = MidTy->getPrimitiveSize();
939 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +0000940
Chris Lattner3732aca2002-08-15 16:15:25 +0000941 // Cases where we are monotonically decreasing the size of the type are
942 // always ok, regardless of what sign changes are going on.
943 //
Chris Lattner0bb75912002-08-14 23:21:10 +0000944 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000945 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +0000946
Chris Lattner555518c2002-09-23 23:39:43 +0000947 // Cases where the source and destination type are the same, but the middle
948 // type is bigger are noops.
949 //
950 if (SrcSize == DstSize && MidSize > SrcSize)
951 return true;
952
Chris Lattner3732aca2002-08-15 16:15:25 +0000953 // If we are monotonically growing, things are more complex.
954 //
955 if (SrcSize <= MidSize && MidSize <= DstSize) {
956 // We have eight combinations of signedness to worry about. Here's the
957 // table:
958 static const int SignTable[8] = {
959 // CODE, SrcSigned, MidSigned, DstSigned, Comment
960 1, // U U U Always ok
961 1, // U U S Always ok
962 3, // U S U Ok iff SrcSize != MidSize
963 3, // U S S Ok iff SrcSize != MidSize
964 0, // S U U Never ok
965 2, // S U S Ok iff MidSize == DstSize
966 1, // S S U Always ok
967 1, // S S S Always ok
968 };
969
970 // Choose an action based on the current entry of the signtable that this
971 // cast of cast refers to...
972 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
973 switch (SignTable[Row]) {
974 case 0: return false; // Never ok
975 case 1: return true; // Always ok
976 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
977 case 3: // Ok iff SrcSize != MidSize
978 return SrcSize != MidSize || SrcTy == Type::BoolTy;
979 default: assert(0 && "Bad entry in sign table!");
980 }
Chris Lattner3732aca2002-08-15 16:15:25 +0000981 }
Chris Lattner650b6da2002-08-02 20:00:25 +0000982 }
Chris Lattner48a44f72002-05-02 17:06:02 +0000983
984 // Otherwise, we cannot succeed. Specifically we do not want to allow things
985 // like: short -> ushort -> uint, because this can create wrong results if
986 // the input short is negative!
987 //
988 return false;
989}
990
991
992// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +0000993//
Chris Lattner113f4f42002-06-25 16:13:24 +0000994Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +0000995 Value *Src = CI.getOperand(0);
996
Chris Lattner48a44f72002-05-02 17:06:02 +0000997 // If the user is casting a value to the same type, eliminate this cast
998 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +0000999 if (CI.getType() == Src->getType())
1000 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00001001
Chris Lattner48a44f72002-05-02 17:06:02 +00001002 // If casting the result of another cast instruction, try to eliminate this
1003 // one!
1004 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001005 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001006 if (isEliminableCastOfCast(CI, CSrc)) {
1007 // This instruction now refers directly to the cast's src operand. This
1008 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00001009 CI.setOperand(0, CSrc->getOperand(0));
1010 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00001011 }
1012
Chris Lattner650b6da2002-08-02 20:00:25 +00001013 // If this is an A->B->A cast, and we are dealing with integral types, try
1014 // to convert this into a logical 'and' instruction.
1015 //
1016 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001017 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00001018 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1019 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1020 assert(CSrc->getType() != Type::ULongTy &&
1021 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00001022 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00001023 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1024 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1025 AndOp);
1026 }
1027 }
1028
Chris Lattnerd0d51602003-06-21 23:12:02 +00001029 // If casting the result of a getelementptr instruction with no offset, turn
1030 // this into a cast of the original pointer!
1031 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001032 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00001033 bool AllZeroOperands = true;
1034 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1035 if (!isa<Constant>(GEP->getOperand(i)) ||
1036 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1037 AllZeroOperands = false;
1038 break;
1039 }
1040 if (AllZeroOperands) {
1041 CI.setOperand(0, GEP->getOperand(0));
1042 return &CI;
1043 }
1044 }
1045
Chris Lattner55d4bda2003-06-23 21:59:52 +00001046 // If this is a cast to bool (which is effectively a "!=0" test), then we can
1047 // perform a few optimizations...
1048 //
1049 if (CI.getType() == Type::BoolTy) {
1050 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Src)) {
1051 Value *Op0 = BO->getOperand(0), *Op1 = BO->getOperand(1);
1052
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001053 switch (BO->getOpcode()) {
1054 case Instruction::Sub:
1055 case Instruction::Xor:
1056 // Replace (cast ([sub|xor] A, B) to bool) with (setne A, B)
Chris Lattner55d4bda2003-06-23 21:59:52 +00001057 return new SetCondInst(Instruction::SetNE, Op0, Op1);
1058
1059 // Replace (cast (add A, B) to bool) with (setne A, -B) if B is
1060 // efficiently invertible, or if the add has just this one use.
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001061 case Instruction::Add:
Chris Lattner55d4bda2003-06-23 21:59:52 +00001062 if (Value *NegVal = dyn_castNegVal(Op1))
1063 return new SetCondInst(Instruction::SetNE, Op0, NegVal);
1064 else if (Value *NegVal = dyn_castNegVal(Op0))
1065 return new SetCondInst(Instruction::SetNE, NegVal, Op1);
1066 else if (BO->use_size() == 1) {
1067 Instruction *Neg = BinaryOperator::createNeg(Op1, BO->getName());
1068 BO->setName("");
1069 InsertNewInstBefore(Neg, CI);
1070 return new SetCondInst(Instruction::SetNE, Op0, Neg);
1071 }
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001072 break;
1073
1074 case Instruction::And:
1075 // Replace (cast (and X, (1 << size(X)-1)) to bool) with x < 0,
1076 // converting X to be a signed value as appropriate. Don't worry about
1077 // bool values, as they will be optimized other ways if they occur in
1078 // this configuration.
1079 if (ConstantInt *CInt = dyn_cast<ConstantInt>(Op1))
1080 if (isSignBit(CInt)) {
1081 // If 'X' is not signed, insert a cast now...
1082 if (!CInt->getType()->isSigned()) {
1083 const Type *DestTy;
1084 switch (CInt->getType()->getPrimitiveID()) {
1085 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1086 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1087 case Type::UIntTyID: DestTy = Type::IntTy; break;
1088 case Type::ULongTyID: DestTy = Type::LongTy; break;
1089 default: assert(0 && "Invalid unsigned integer type!"); abort();
1090 }
1091 CastInst *NewCI = new CastInst(Op0, DestTy,
1092 Op0->getName()+".signed");
1093 InsertNewInstBefore(NewCI, CI);
1094 Op0 = NewCI;
1095 }
1096 return new SetCondInst(Instruction::SetLT, Op0,
1097 Constant::getNullValue(Op0->getType()));
1098 }
1099 break;
1100 default: break;
1101 }
Chris Lattner55d4bda2003-06-23 21:59:52 +00001102 }
1103 }
1104
Chris Lattner260ab202002-04-18 17:39:14 +00001105 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00001106}
1107
Chris Lattner970c33a2003-06-19 17:00:31 +00001108// CallInst simplification
1109//
1110Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1111 if (transformConstExprCastCall(&CI)) return 0;
1112 return 0;
1113}
1114
1115// InvokeInst simplification
1116//
1117Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1118 if (transformConstExprCastCall(&II)) return 0;
1119 return 0;
1120}
1121
1122// getPromotedType - Return the specified type promoted as it would be to pass
1123// though a va_arg area...
1124static const Type *getPromotedType(const Type *Ty) {
1125 switch (Ty->getPrimitiveID()) {
1126 case Type::SByteTyID:
1127 case Type::ShortTyID: return Type::IntTy;
1128 case Type::UByteTyID:
1129 case Type::UShortTyID: return Type::UIntTy;
1130 case Type::FloatTyID: return Type::DoubleTy;
1131 default: return Ty;
1132 }
1133}
1134
1135// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1136// attempt to move the cast to the arguments of the call/invoke.
1137//
1138bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1139 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1140 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1141 if (CE->getOpcode() != Instruction::Cast ||
1142 !isa<ConstantPointerRef>(CE->getOperand(0)))
1143 return false;
1144 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1145 if (!isa<Function>(CPR->getValue())) return false;
1146 Function *Callee = cast<Function>(CPR->getValue());
1147 Instruction *Caller = CS.getInstruction();
1148
1149 // Okay, this is a cast from a function to a different type. Unless doing so
1150 // would cause a type conversion of one of our arguments, change this call to
1151 // be a direct call with arguments casted to the appropriate types.
1152 //
1153 const FunctionType *FT = Callee->getFunctionType();
1154 const Type *OldRetTy = Caller->getType();
1155
1156 if (Callee->isExternal() &&
1157 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1158 return false; // Cannot transform this return value...
1159
1160 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1161 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1162
1163 CallSite::arg_iterator AI = CS.arg_begin();
1164 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1165 const Type *ParamTy = FT->getParamType(i);
1166 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1167 if (Callee->isExternal() && !isConvertible) return false;
1168 }
1169
1170 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1171 Callee->isExternal())
1172 return false; // Do not delete arguments unless we have a function body...
1173
1174 // Okay, we decided that this is a safe thing to do: go ahead and start
1175 // inserting cast instructions as necessary...
1176 std::vector<Value*> Args;
1177 Args.reserve(NumActualArgs);
1178
1179 AI = CS.arg_begin();
1180 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1181 const Type *ParamTy = FT->getParamType(i);
1182 if ((*AI)->getType() == ParamTy) {
1183 Args.push_back(*AI);
1184 } else {
1185 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1186 InsertNewInstBefore(Cast, *Caller);
1187 Args.push_back(Cast);
1188 }
1189 }
1190
1191 // If the function takes more arguments than the call was taking, add them
1192 // now...
1193 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1194 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1195
1196 // If we are removing arguments to the function, emit an obnoxious warning...
1197 if (FT->getNumParams() < NumActualArgs)
1198 if (!FT->isVarArg()) {
1199 std::cerr << "WARNING: While resolving call to function '"
1200 << Callee->getName() << "' arguments were dropped!\n";
1201 } else {
1202 // Add all of the arguments in their promoted form to the arg list...
1203 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1204 const Type *PTy = getPromotedType((*AI)->getType());
1205 if (PTy != (*AI)->getType()) {
1206 // Must promote to pass through va_arg area!
1207 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1208 InsertNewInstBefore(Cast, *Caller);
1209 Args.push_back(Cast);
1210 } else {
1211 Args.push_back(*AI);
1212 }
1213 }
1214 }
1215
1216 if (FT->getReturnType() == Type::VoidTy)
1217 Caller->setName(""); // Void type should not have a name...
1218
1219 Instruction *NC;
1220 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1221 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1222 Args, Caller->getName(), Caller);
1223 } else {
1224 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1225 }
1226
1227 // Insert a cast of the return type as necessary...
1228 Value *NV = NC;
1229 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1230 if (NV->getType() != Type::VoidTy) {
1231 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1232 InsertNewInstBefore(NC, *Caller);
1233 AddUsesToWorkList(*Caller);
1234 } else {
1235 NV = Constant::getNullValue(Caller->getType());
1236 }
1237 }
1238
1239 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1240 Caller->replaceAllUsesWith(NV);
1241 Caller->getParent()->getInstList().erase(Caller);
1242 removeFromWorkList(Caller);
1243 return true;
1244}
1245
1246
Chris Lattner48a44f72002-05-02 17:06:02 +00001247
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001248// PHINode simplification
1249//
Chris Lattner113f4f42002-06-25 16:13:24 +00001250Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001251 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +00001252 if (PN.getNumIncomingValues() == 1)
1253 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +00001254
1255 // Otherwise if all of the incoming values are the same for the PHI, replace
1256 // the PHI node with the incoming value.
1257 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +00001258 Value *InVal = 0;
1259 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1260 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1261 if (InVal && PN.getIncomingValue(i) != InVal)
1262 return 0; // Not the same, bail out.
1263 else
1264 InVal = PN.getIncomingValue(i);
1265
1266 // The only case that could cause InVal to be null is if we have a PHI node
1267 // that only has entries for itself. In this case, there is no entry into the
1268 // loop, so kill the PHI.
1269 //
1270 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001271
Chris Lattner9cd1e662002-08-20 15:35:35 +00001272 // All of the incoming values are the same, replace the PHI node now.
1273 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001274}
1275
Chris Lattner48a44f72002-05-02 17:06:02 +00001276
Chris Lattner113f4f42002-06-25 16:13:24 +00001277Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +00001278 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00001279 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001280 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +00001281 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001282 GEP.getNumOperands() == 1)
1283 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +00001284
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001285 // Combine Indices - If the source pointer to this getelementptr instruction
1286 // is a getelementptr instruction, combine the indices of the two
1287 // getelementptr instructions into a single instruction.
1288 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001289 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001290 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +00001291
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001292 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +00001293 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1294 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +00001295 // Replace: gep (gep %P, long C1), long C2, ...
1296 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +00001297 Value *Sum = ConstantExpr::get(Instruction::Add,
1298 cast<Constant>(Src->getOperand(1)),
1299 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +00001300 assert(Sum && "Constant folding of longs failed!?");
1301 GEP.setOperand(0, Src->getOperand(0));
1302 GEP.setOperand(1, Sum);
1303 AddUsesToWorkList(*Src); // Reduce use count of Src
1304 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +00001305 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +00001306 // Replace: gep (gep %P, long B), long A, ...
1307 // With: T = long A+B; gep %P, T, ...
1308 //
1309 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1310 GEP.getOperand(1),
1311 Src->getName()+".sum", &GEP);
1312 GEP.setOperand(0, Src->getOperand(0));
1313 GEP.setOperand(1, Sum);
1314 WorkList.push_back(cast<Instruction>(Sum));
1315 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00001316 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00001317 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001318 // Otherwise we can do the fold if the first index of the GEP is a zero
1319 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1320 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00001321 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1322 Constant::getNullValue(Type::LongTy)) {
1323 // If the src gep ends with a constant array index, merge this get into
1324 // it, even if we have a non-zero array index.
1325 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1326 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001327 }
1328
1329 if (!Indices.empty())
1330 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001331
1332 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1333 // GEP of global variable. If all of the indices for this GEP are
1334 // constants, we can promote this to a constexpr instead of an instruction.
1335
1336 // Scan for nonconstants...
1337 std::vector<Constant*> Indices;
1338 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1339 for (; I != E && isa<Constant>(*I); ++I)
1340 Indices.push_back(cast<Constant>(*I));
1341
1342 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001343 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001344 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1345
1346 // Replace all uses of the GEP with the new constexpr...
1347 return ReplaceInstUsesWith(GEP, CE);
1348 }
Chris Lattnerca081252001-12-14 16:52:21 +00001349 }
1350
Chris Lattnerca081252001-12-14 16:52:21 +00001351 return 0;
1352}
1353
Chris Lattner1085bdf2002-11-04 16:18:53 +00001354Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1355 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1356 if (AI.isArrayAllocation()) // Check C != 1
1357 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1358 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001359 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001360
1361 // Create and insert the replacement instruction...
1362 if (isa<MallocInst>(AI))
1363 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001364 else {
1365 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001366 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001367 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001368
1369 // Scan to the end of the allocation instructions, to skip over a block of
1370 // allocas if possible...
1371 //
1372 BasicBlock::iterator It = New;
1373 while (isa<AllocationInst>(*It)) ++It;
1374
1375 // Now that I is pointing to the first non-allocation-inst in the block,
1376 // insert our getelementptr instruction...
1377 //
1378 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1379 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1380
1381 // Now make everything use the getelementptr instead of the original
1382 // allocation.
1383 ReplaceInstUsesWith(AI, V);
1384 return &AI;
1385 }
1386 return 0;
1387}
1388
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001389/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1390/// constantexpr, return the constant value being addressed by the constant
1391/// expression, or null if something is funny.
1392///
1393static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1394 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1395 return 0; // Do not allow stepping over the value!
1396
1397 // Loop over all of the operands, tracking down which value we are
1398 // addressing...
1399 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1400 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1401 ConstantStruct *CS = cast<ConstantStruct>(C);
1402 if (CU->getValue() >= CS->getValues().size()) return 0;
1403 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1404 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1405 ConstantArray *CA = cast<ConstantArray>(C);
1406 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1407 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1408 } else
1409 return 0;
1410 return C;
1411}
1412
1413Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1414 Value *Op = LI.getOperand(0);
1415 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1416 Op = CPR->getValue();
1417
1418 // Instcombine load (constant global) into the value loaded...
1419 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001420 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001421 return ReplaceInstUsesWith(LI, GV->getInitializer());
1422
1423 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1424 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1425 if (CE->getOpcode() == Instruction::GetElementPtr)
1426 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1427 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001428 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001429 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1430 return ReplaceInstUsesWith(LI, V);
1431 return 0;
1432}
1433
1434
Chris Lattner9eef8a72003-06-04 04:46:00 +00001435Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1436 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner45789ac2003-06-05 20:12:51 +00001437 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
Chris Lattnere967b342003-06-04 05:10:11 +00001438 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1439 BasicBlock *TrueDest = BI.getSuccessor(0);
1440 BasicBlock *FalseDest = BI.getSuccessor(1);
1441 // Swap Destinations and condition...
1442 BI.setCondition(V);
1443 BI.setSuccessor(0, FalseDest);
1444 BI.setSuccessor(1, TrueDest);
1445 return &BI;
1446 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00001447 return 0;
1448}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001449
Chris Lattnerca081252001-12-14 16:52:21 +00001450
Chris Lattner99f48c62002-09-02 04:59:56 +00001451void InstCombiner::removeFromWorkList(Instruction *I) {
1452 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1453 WorkList.end());
1454}
1455
Chris Lattner113f4f42002-06-25 16:13:24 +00001456bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001457 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001458
Chris Lattner260ab202002-04-18 17:39:14 +00001459 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001460
1461 while (!WorkList.empty()) {
1462 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1463 WorkList.pop_back();
1464
Misha Brukman632df282002-10-29 23:06:16 +00001465 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001466 // Check to see if we can DIE the instruction...
1467 if (isInstructionTriviallyDead(I)) {
1468 // Add operands to the worklist...
1469 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1470 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1471 WorkList.push_back(Op);
1472
1473 ++NumDeadInst;
1474 BasicBlock::iterator BBI = I;
1475 if (dceInstruction(BBI)) {
1476 removeFromWorkList(I);
1477 continue;
1478 }
1479 }
1480
Misha Brukman632df282002-10-29 23:06:16 +00001481 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001482 if (Constant *C = ConstantFoldInstruction(I)) {
1483 // Add operands to the worklist...
1484 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1485 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1486 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001487 ReplaceInstUsesWith(*I, C);
1488
Chris Lattner99f48c62002-09-02 04:59:56 +00001489 ++NumConstProp;
1490 BasicBlock::iterator BBI = I;
1491 if (dceInstruction(BBI)) {
1492 removeFromWorkList(I);
1493 continue;
1494 }
1495 }
1496
Chris Lattnerca081252001-12-14 16:52:21 +00001497 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001498 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001499 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001500 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001501 if (Result != I) {
1502 // Instructions can end up on the worklist more than once. Make sure
1503 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001504 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001505 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001506 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001507 BasicBlock::iterator II = I;
1508
1509 // If the instruction was modified, it's possible that it is now dead.
1510 // if so, remove it.
1511 if (dceInstruction(II)) {
1512 // Instructions may end up in the worklist more than once. Erase them
1513 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001514 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001515 Result = 0;
1516 }
Chris Lattner053c0932002-05-14 15:24:07 +00001517 }
Chris Lattner260ab202002-04-18 17:39:14 +00001518
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001519 if (Result) {
1520 WorkList.push_back(Result);
1521 AddUsesToWorkList(*Result);
1522 }
Chris Lattner260ab202002-04-18 17:39:14 +00001523 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001524 }
1525 }
1526
Chris Lattner260ab202002-04-18 17:39:14 +00001527 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001528}
1529
1530Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001531 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001532}