blob: 15b0bbcdfc88627678716f07f833344231ef5347 [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//
Chris Lattnerbfb1d032003-07-23 21:41:57 +000015// This pass guarantees that the following cannonicalizations are performed on
16// the program:
17// 1. If a binary operator has a constant operand, it is moved to the RHS
18// 2. Logical operators with constant operands are always grouped so that
19// 'or's are performed first, then 'and's, then 'xor's.
20// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
21// 4. All SetCC instructions on boolean values are replaced with logical ops
22// N. This list is incomplete
23//
Chris Lattnerca081252001-12-14 16:52:21 +000024//===----------------------------------------------------------------------===//
25
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000026#include "llvm/Transforms/Scalar.h"
Chris Lattner9b55e5a2002-05-07 18:12:18 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerae7a0d32002-08-02 19:29:35 +000028#include "llvm/Transforms/Utils/Local.h"
Chris Lattner471bd762003-05-22 19:07:21 +000029#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000030#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000031#include "llvm/Constants.h"
32#include "llvm/ConstantHandling.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000033#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000034#include "llvm/GlobalVariable.h"
Chris Lattner60a65912002-02-12 21:07:25 +000035#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000036#include "llvm/Support/InstVisitor.h"
Chris Lattner970c33a2003-06-19 17:00:31 +000037#include "llvm/Support/CallSite.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000038#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000039#include <algorithm>
Chris Lattnerca081252001-12-14 16:52:21 +000040
Chris Lattner260ab202002-04-18 17:39:14 +000041namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000042 Statistic<> NumCombined ("instcombine", "Number of insts combined");
43 Statistic<> NumConstProp("instcombine", "Number of constant folds");
44 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
45
Chris Lattnerc8e66542002-04-27 06:56:12 +000046 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000047 public InstVisitor<InstCombiner, Instruction*> {
48 // Worklist of all of the instructions that need to be simplified.
49 std::vector<Instruction*> WorkList;
50
Chris Lattner113f4f42002-06-25 16:13:24 +000051 void AddUsesToWorkList(Instruction &I) {
Chris Lattner260ab202002-04-18 17:39:14 +000052 // The instruction was simplified, add all users of the instruction to
53 // the work lists because they might get more simplified now...
54 //
Chris Lattner113f4f42002-06-25 16:13:24 +000055 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000056 UI != UE; ++UI)
57 WorkList.push_back(cast<Instruction>(*UI));
58 }
59
Chris Lattner99f48c62002-09-02 04:59:56 +000060 // removeFromWorkList - remove all instances of I from the worklist.
61 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000062 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000063 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000064
Chris Lattnerf12cc842002-04-28 21:27:06 +000065 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000066 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000067 }
68
Chris Lattner260ab202002-04-18 17:39:14 +000069 // Visitation implementation - Implement instruction combining for different
70 // instruction types. The semantics are as follows:
71 // Return Value:
72 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000073 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000074 // otherwise - Change was made, replace I with returned instruction
75 //
Chris Lattner113f4f42002-06-25 16:13:24 +000076 Instruction *visitAdd(BinaryOperator &I);
77 Instruction *visitSub(BinaryOperator &I);
78 Instruction *visitMul(BinaryOperator &I);
79 Instruction *visitDiv(BinaryOperator &I);
80 Instruction *visitRem(BinaryOperator &I);
81 Instruction *visitAnd(BinaryOperator &I);
82 Instruction *visitOr (BinaryOperator &I);
83 Instruction *visitXor(BinaryOperator &I);
84 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +000085 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +000086 Instruction *visitCastInst(CastInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +000087 Instruction *visitCallInst(CallInst &CI);
88 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +000089 Instruction *visitPHINode(PHINode &PN);
90 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +000091 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +000092 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +000093 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner260ab202002-04-18 17:39:14 +000094
95 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +000096 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +000097
Chris Lattner970c33a2003-06-19 17:00:31 +000098 private:
99 bool transformConstExprCastCall(CallSite CS);
100
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000101 // InsertNewInstBefore - insert an instruction New before instruction Old
102 // in the program. Add the new instruction to the worklist.
103 //
104 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000105 assert(New && New->getParent() == 0 &&
106 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000107 BasicBlock *BB = Old.getParent();
108 BB->getInstList().insert(&Old, New); // Insert inst
109 WorkList.push_back(New); // Add to worklist
110 }
111
112 // ReplaceInstUsesWith - This method is to be used when an instruction is
113 // found to be dead, replacable with another preexisting expression. Here
114 // we add all uses of I to the worklist, replace all uses of I with the new
115 // value, then return I, so that the inst combiner will know that I was
116 // modified.
117 //
118 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
119 AddUsesToWorkList(I); // Add all modified instrs to worklist
120 I.replaceAllUsesWith(V);
121 return &I;
122 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000123
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000124 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
125 /// InsertBefore instruction. This is specialized a bit to avoid inserting
126 /// casts that are known to not do anything...
127 ///
128 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
129 Instruction *InsertBefore);
130
Chris Lattner7fb29e12003-03-11 00:12:48 +0000131 // SimplifyCommutative - This performs a few simplifications for commutative
132 // operators...
133 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattner260ab202002-04-18 17:39:14 +0000134 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000135
Chris Lattnerc8b70922002-07-26 21:12:46 +0000136 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000137}
138
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000139// getComplexity: Assign a complexity or rank value to LLVM Values...
140// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
141static unsigned getComplexity(Value *V) {
142 if (isa<Instruction>(V)) {
143 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
144 return 2;
145 return 3;
146 }
147 if (isa<Argument>(V)) return 2;
148 return isa<Constant>(V) ? 0 : 1;
149}
Chris Lattner260ab202002-04-18 17:39:14 +0000150
Chris Lattner7fb29e12003-03-11 00:12:48 +0000151// isOnlyUse - Return true if this instruction will be deleted if we stop using
152// it.
153static bool isOnlyUse(Value *V) {
154 return V->use_size() == 1 || isa<Constant>(V);
155}
156
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000157// SimplifyCommutative - This performs a few simplifications for commutative
158// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000159//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000160// 1. Order operands such that they are listed from right (least complex) to
161// left (most complex). This puts constants before unary operators before
162// binary operators.
163//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000164// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
165// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000166//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000167bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000168 bool Changed = false;
169 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
170 Changed = !I.swapOperands();
171
172 if (!I.isAssociative()) return Changed;
173 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000174 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
175 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
176 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000177 Constant *Folded = ConstantExpr::get(I.getOpcode(),
178 cast<Constant>(I.getOperand(1)),
179 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000180 I.setOperand(0, Op->getOperand(0));
181 I.setOperand(1, Folded);
182 return true;
183 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
184 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
185 isOnlyUse(Op) && isOnlyUse(Op1)) {
186 Constant *C1 = cast<Constant>(Op->getOperand(1));
187 Constant *C2 = cast<Constant>(Op1->getOperand(1));
188
189 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000190 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000191 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
192 Op1->getOperand(0),
193 Op1->getName(), &I);
194 WorkList.push_back(New);
195 I.setOperand(0, New);
196 I.setOperand(1, Folded);
197 return true;
198 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000199 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000200 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000201}
Chris Lattnerca081252001-12-14 16:52:21 +0000202
Chris Lattnerbb74e222003-03-10 23:06:50 +0000203// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
204// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000205//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000206static inline Value *dyn_castNegVal(Value *V) {
207 if (BinaryOperator::isNeg(V))
208 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
209
Chris Lattner9244df62003-04-30 22:19:10 +0000210 // Constants can be considered to be negated values if they can be folded...
211 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000212 return ConstantExpr::get(Instruction::Sub,
213 Constant::getNullValue(V->getType()), C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000214 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000215}
216
Chris Lattnerbb74e222003-03-10 23:06:50 +0000217static inline Value *dyn_castNotVal(Value *V) {
218 if (BinaryOperator::isNot(V))
219 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
220
221 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000222 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000223 return ConstantExpr::get(Instruction::Xor,
224 ConstantIntegral::getAllOnesValue(C->getType()),C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000225 return 0;
226}
227
Chris Lattner7fb29e12003-03-11 00:12:48 +0000228// dyn_castFoldableMul - If this value is a multiply that can be folded into
229// other computations (because it has a constant operand), return the
230// non-constant operand of the multiply.
231//
232static inline Value *dyn_castFoldableMul(Value *V) {
233 if (V->use_size() == 1 && V->getType()->isInteger())
234 if (Instruction *I = dyn_cast<Instruction>(V))
235 if (I->getOpcode() == Instruction::Mul)
236 if (isa<Constant>(I->getOperand(1)))
237 return I->getOperand(0);
238 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000239}
Chris Lattner31ae8632002-08-14 17:51:49 +0000240
Chris Lattner7fb29e12003-03-11 00:12:48 +0000241// dyn_castMaskingAnd - If this value is an And instruction masking a value with
242// a constant, return the constant being anded with.
243//
Chris Lattner01d56392003-08-12 19:17:27 +0000244template<class ValueType>
245static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000246 if (Instruction *I = dyn_cast<Instruction>(V))
247 if (I->getOpcode() == Instruction::And)
248 return dyn_cast<Constant>(I->getOperand(1));
249
250 // If this is a constant, it acts just like we were masking with it.
251 return dyn_cast<Constant>(V);
252}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000253
254// Log2 - Calculate the log base 2 for the specified value if it is exactly a
255// power of 2.
256static unsigned Log2(uint64_t Val) {
257 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
258 unsigned Count = 0;
259 while (Val != 1) {
260 if (Val & 1) return 0; // Multiple bits set?
261 Val >>= 1;
262 ++Count;
263 }
264 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000265}
266
Chris Lattner113f4f42002-06-25 16:13:24 +0000267Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000268 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000269 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000270
271 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000272 if (RHS == Constant::getNullValue(I.getType()))
273 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000274
Chris Lattner147e9752002-05-08 22:46:53 +0000275 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000276 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000277 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000278
279 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000280 if (!isa<Constant>(RHS))
281 if (Value *V = dyn_castNegVal(RHS))
282 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000283
Chris Lattner57c8d992003-02-18 19:57:07 +0000284 // X*C + X --> X * (C+1)
285 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000286 Constant *CP1 =
287 ConstantExpr::get(Instruction::Add,
288 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
289 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000290 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
291 }
292
293 // X + X*C --> X * (C+1)
294 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000295 Constant *CP1 =
296 ConstantExpr::get(Instruction::Add,
297 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
298 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000299 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
300 }
301
Chris Lattner7fb29e12003-03-11 00:12:48 +0000302 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
303 if (Constant *C1 = dyn_castMaskingAnd(LHS))
304 if (Constant *C2 = dyn_castMaskingAnd(RHS))
Chris Lattner34428442003-05-27 16:40:51 +0000305 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000306 return BinaryOperator::create(Instruction::Or, LHS, RHS);
307
Chris Lattner113f4f42002-06-25 16:13:24 +0000308 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000309}
310
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000311// isSignBit - Return true if the value represented by the constant only has the
312// highest order bit set.
313static bool isSignBit(ConstantInt *CI) {
314 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
315 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
316}
317
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000318static unsigned getTypeSizeInBits(const Type *Ty) {
319 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
320}
321
Chris Lattner113f4f42002-06-25 16:13:24 +0000322Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000323 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000324
Chris Lattnere6794492002-08-12 21:17:25 +0000325 if (Op0 == Op1) // sub X, X -> 0
326 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000327
Chris Lattnere6794492002-08-12 21:17:25 +0000328 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000329 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000330 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000331
Chris Lattner3082c5a2003-02-18 19:28:33 +0000332 // Replace (-1 - A) with (~A)...
333 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
334 if (C->isAllOnesValue())
335 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000336
Chris Lattner3082c5a2003-02-18 19:28:33 +0000337 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
338 if (Op1I->use_size() == 1) {
339 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
340 // is not used by anyone else...
341 //
342 if (Op1I->getOpcode() == Instruction::Sub) {
343 // Swap the two operands of the subexpr...
344 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
345 Op1I->setOperand(0, IIOp1);
346 Op1I->setOperand(1, IIOp0);
347
348 // Create the new top level add instruction...
349 return BinaryOperator::create(Instruction::Add, Op0, Op1);
350 }
351
352 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
353 //
354 if (Op1I->getOpcode() == Instruction::And &&
355 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
356 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
357
358 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
359 return BinaryOperator::create(Instruction::And, Op0, NewNot);
360 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000361
362 // X - X*C --> X * (1-C)
363 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000364 Constant *CP1 =
365 ConstantExpr::get(Instruction::Sub,
366 ConstantInt::get(I.getType(), 1),
367 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000368 assert(CP1 && "Couldn't constant fold 1-C?");
369 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
370 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000371 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000372
Chris Lattner57c8d992003-02-18 19:57:07 +0000373 // X*C - X --> X * (C-1)
374 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000375 Constant *CP1 =
376 ConstantExpr::get(Instruction::Sub,
377 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
378 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000379 assert(CP1 && "Couldn't constant fold C - 1?");
380 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
381 }
382
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000383 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000384}
385
Chris Lattner113f4f42002-06-25 16:13:24 +0000386Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000387 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000388 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000389
Chris Lattnere6794492002-08-12 21:17:25 +0000390 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000391 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
392 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
393 const Type *Ty = CI->getType();
Chris Lattner6077c312003-07-23 15:22:26 +0000394 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000395 switch (Val) {
Chris Lattner35236d82003-06-25 17:09:20 +0000396 case -1: // X * -1 -> -X
397 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner3082c5a2003-02-18 19:28:33 +0000398 case 0:
399 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
400 case 1:
401 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
402 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
403 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
404 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000405
Chris Lattner3082c5a2003-02-18 19:28:33 +0000406 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
407 return new ShiftInst(Instruction::Shl, Op0,
408 ConstantUInt::get(Type::UByteTy, C));
409 } else {
410 ConstantFP *Op1F = cast<ConstantFP>(Op1);
411 if (Op1F->isNullValue())
412 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000413
Chris Lattner3082c5a2003-02-18 19:28:33 +0000414 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
415 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
416 if (Op1F->getValue() == 1.0)
417 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
418 }
Chris Lattner260ab202002-04-18 17:39:14 +0000419 }
420
Chris Lattner934a64cf2003-03-10 23:23:04 +0000421 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
422 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
423 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
424
Chris Lattner113f4f42002-06-25 16:13:24 +0000425 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000426}
427
Chris Lattner113f4f42002-06-25 16:13:24 +0000428Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000429 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000430 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000431 if (RHS->equalsInt(1))
432 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000433
434 // Check to see if this is an unsigned division with an exact power of 2,
435 // if so, convert to a right shift.
436 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
437 if (uint64_t Val = C->getValue()) // Don't break X / 0
438 if (uint64_t C = Log2(Val))
439 return new ShiftInst(Instruction::Shr, I.getOperand(0),
440 ConstantUInt::get(Type::UByteTy, C));
441 }
442
443 // 0 / X == 0, we don't need to preserve faults!
444 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
445 if (LHS->equalsInt(0))
446 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
447
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000448 return 0;
449}
450
451
Chris Lattner113f4f42002-06-25 16:13:24 +0000452Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000453 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
454 if (RHS->equalsInt(1)) // X % 1 == 0
455 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
456
457 // Check to see if this is an unsigned remainder with an exact power of 2,
458 // if so, convert to a bitwise and.
459 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
460 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
461 if (Log2(Val))
462 return BinaryOperator::create(Instruction::And, I.getOperand(0),
463 ConstantUInt::get(I.getType(), Val-1));
464 }
465
466 // 0 % X == 0, we don't need to preserve faults!
467 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
468 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000469 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
470
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000471 return 0;
472}
473
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000474// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000475static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000476 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
477 // Calculate -1 casted to the right type...
478 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
479 uint64_t Val = ~0ULL; // All ones
480 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
481 return CU->getValue() == Val-1;
482 }
483
484 const ConstantSInt *CS = cast<ConstantSInt>(C);
485
486 // Calculate 0111111111..11111
487 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
488 int64_t Val = INT64_MAX; // All ones
489 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
490 return CS->getValue() == Val-1;
491}
492
493// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000494static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000495 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
496 return CU->getValue() == 1;
497
498 const ConstantSInt *CS = cast<ConstantSInt>(C);
499
500 // Calculate 1111111111000000000000
501 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
502 int64_t Val = -1; // All ones
503 Val <<= TypeBits-1; // Shift over to the right spot
504 return CS->getValue() == Val+1;
505}
506
507
Chris Lattner113f4f42002-06-25 16:13:24 +0000508Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000509 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000510 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000511
512 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000513 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
514 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000515
516 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +0000517 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000518 if (RHS->isAllOnesValue())
519 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000520
Chris Lattner33217db2003-07-23 19:36:21 +0000521 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
522 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +0000523 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
524 if (Op0I->getOpcode() == Instruction::Xor) {
Chris Lattner33217db2003-07-23 19:36:21 +0000525 if ((*RHS & *Op0CI)->isNullValue()) {
526 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
527 return BinaryOperator::create(Instruction::And, X, RHS);
528 } else if (isOnlyUse(Op0)) {
Chris Lattner16464b32003-07-23 19:25:52 +0000529 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
530 std::string Op0Name = Op0I->getName(); Op0I->setName("");
531 Instruction *And = BinaryOperator::create(Instruction::And,
Chris Lattner33217db2003-07-23 19:36:21 +0000532 X, RHS, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000533 InsertNewInstBefore(And, I);
534 return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
535 }
536 } else if (Op0I->getOpcode() == Instruction::Or) {
537 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
538 if ((*RHS & *Op0CI)->isNullValue())
Chris Lattner33217db2003-07-23 19:36:21 +0000539 return BinaryOperator::create(Instruction::And, X, RHS);
Chris Lattner16464b32003-07-23 19:25:52 +0000540
541 Constant *Together = *RHS & *Op0CI;
542 if (Together == RHS) // (X | C) & C --> C
543 return ReplaceInstUsesWith(I, RHS);
544
545 if (isOnlyUse(Op0)) {
546 if (Together != Op0CI) {
547 // (X | C1) & C2 --> (X | (C1&C2)) & C2
548 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattner33217db2003-07-23 19:36:21 +0000549 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
550 Together, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000551 InsertNewInstBefore(Or, I);
552 return BinaryOperator::create(Instruction::And, Or, RHS);
553 }
554 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000555 }
Chris Lattner33217db2003-07-23 19:36:21 +0000556 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000557 }
558
Chris Lattnerbb74e222003-03-10 23:06:50 +0000559 Value *Op0NotVal = dyn_castNotVal(Op0);
560 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000561
562 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000563 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000564 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
Chris Lattner49b47ae2003-07-23 17:57:01 +0000565 Op1NotVal,I.getName()+".demorgan");
566 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000567 return BinaryOperator::createNot(Or);
568 }
569
570 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
571 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000572
Chris Lattner113f4f42002-06-25 16:13:24 +0000573 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000574}
575
576
577
Chris Lattner113f4f42002-06-25 16:13:24 +0000578Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000579 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000580 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000581
582 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000583 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
584 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000585
586 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +0000587 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000588 if (RHS->isAllOnesValue())
589 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000590
Chris Lattner8f0d1562003-07-23 18:29:44 +0000591 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
592 // (X & C1) | C2 --> (X | C2) & (C1|C2)
593 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
594 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
595 std::string Op0Name = Op0I->getName(); Op0I->setName("");
596 Instruction *Or = BinaryOperator::create(Instruction::Or,
597 Op0I->getOperand(0), RHS,
598 Op0Name);
599 InsertNewInstBefore(Or, I);
600 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
601 }
602
603 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
604 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
605 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
606 std::string Op0Name = Op0I->getName(); Op0I->setName("");
607 Instruction *Or = BinaryOperator::create(Instruction::Or,
608 Op0I->getOperand(0), RHS,
609 Op0Name);
610 InsertNewInstBefore(Or, I);
611 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
612 }
613 }
614 }
615
Chris Lattner812aab72003-08-12 19:11:07 +0000616 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattner01d56392003-08-12 19:17:27 +0000617 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
618 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
619 if (LHS->getOperand(0) == RHS->getOperand(0))
620 if (Constant *C0 = dyn_castMaskingAnd(LHS))
621 if (Constant *C1 = dyn_castMaskingAnd(RHS))
622 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
Chris Lattner812aab72003-08-12 19:11:07 +0000623 *C0 | *C1);
624
Chris Lattner3e327a42003-03-10 23:13:59 +0000625 Value *Op0NotVal = dyn_castNotVal(Op0);
626 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000627
Chris Lattner3e327a42003-03-10 23:13:59 +0000628 if (Op1 == Op0NotVal) // ~A | A == -1
629 return ReplaceInstUsesWith(I,
630 ConstantIntegral::getAllOnesValue(I.getType()));
631
632 if (Op0 == Op1NotVal) // A | ~A == -1
633 return ReplaceInstUsesWith(I,
634 ConstantIntegral::getAllOnesValue(I.getType()));
635
636 // (~A | ~B) == (~(A & B)) - Demorgan's Law
637 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
638 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
639 Op1NotVal,I.getName()+".demorgan",
640 &I);
641 WorkList.push_back(And);
642 return BinaryOperator::createNot(And);
643 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000644
Chris Lattner113f4f42002-06-25 16:13:24 +0000645 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000646}
647
648
649
Chris Lattner113f4f42002-06-25 16:13:24 +0000650Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000651 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000652 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000653
654 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000655 if (Op0 == Op1)
656 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000657
Chris Lattner97638592003-07-23 21:37:07 +0000658 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000659 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +0000660 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +0000661 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000662
Chris Lattner97638592003-07-23 21:37:07 +0000663 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000664 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +0000665 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
666 if (RHS == ConstantBool::True && SCI->use_size() == 1)
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000667 return new SetCondInst(SCI->getInverseCondition(),
668 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattner97638592003-07-23 21:37:07 +0000669
670 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
671 if (Op0I->getOpcode() == Instruction::And) {
672 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
673 if ((*RHS & *Op0CI)->isNullValue())
674 return BinaryOperator::create(Instruction::Or, Op0, RHS);
675 } else if (Op0I->getOpcode() == Instruction::Or) {
676 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
677 if ((*RHS & *Op0CI) == RHS)
678 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
679 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000680 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000681 }
682
Chris Lattnerbb74e222003-03-10 23:06:50 +0000683 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000684 if (X == Op1)
685 return ReplaceInstUsesWith(I,
686 ConstantIntegral::getAllOnesValue(I.getType()));
687
Chris Lattnerbb74e222003-03-10 23:06:50 +0000688 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000689 if (X == Op0)
690 return ReplaceInstUsesWith(I,
691 ConstantIntegral::getAllOnesValue(I.getType()));
692
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000693 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
694 if (Op1I->getOpcode() == Instruction::Or)
695 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
696 cast<BinaryOperator>(Op1I)->swapOperands();
697 I.swapOperands();
698 std::swap(Op0, Op1);
699 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
700 I.swapOperands();
701 std::swap(Op0, Op1);
702 }
703
704 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
705 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
706 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
707 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000708 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000709 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
710 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000711 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
712 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000713 }
714 }
715
Chris Lattner7fb29e12003-03-11 00:12:48 +0000716 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
717 if (Constant *C1 = dyn_castMaskingAnd(Op0))
718 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +0000719 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000720 return BinaryOperator::create(Instruction::Or, Op0, Op1);
721
Chris Lattner113f4f42002-06-25 16:13:24 +0000722 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000723}
724
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000725// AddOne, SubOne - Add or subtract a constant one from an integer constant...
726static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000727 Constant *Result = ConstantExpr::get(Instruction::Add, C,
728 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000729 assert(Result && "Constant folding integer addition failed!");
730 return Result;
731}
732static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000733 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
734 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000735 assert(Result && "Constant folding integer addition failed!");
736 return Result;
737}
738
Chris Lattner1fc23f32002-05-09 20:11:54 +0000739// isTrueWhenEqual - Return true if the specified setcondinst instruction is
740// true when both operands are equal...
741//
Chris Lattner113f4f42002-06-25 16:13:24 +0000742static bool isTrueWhenEqual(Instruction &I) {
743 return I.getOpcode() == Instruction::SetEQ ||
744 I.getOpcode() == Instruction::SetGE ||
745 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000746}
747
Chris Lattner113f4f42002-06-25 16:13:24 +0000748Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000749 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000750 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
751 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000752
753 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000754 if (Op0 == Op1)
755 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000756
757 // setcc <global*>, 0 - Global value addresses are never null!
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000758 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
759 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
760
761 // setcc's with boolean values can always be turned into bitwise operations
762 if (Ty == Type::BoolTy) {
763 // If this is <, >, or !=, we can change this into a simple xor instruction
764 if (!isTrueWhenEqual(I))
765 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
766
767 // Otherwise we need to make a temporary intermediate instruction and insert
768 // it into the instruction stream. This is what we are after:
769 //
770 // seteq bool %A, %B -> ~(A^B)
771 // setle bool %A, %B -> ~A | B
772 // setge bool %A, %B -> A | ~B
773 //
774 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
775 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
776 I.getName()+"tmp");
777 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000778 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000779 }
780
781 // Handle the setXe cases...
782 assert(I.getOpcode() == Instruction::SetGE ||
783 I.getOpcode() == Instruction::SetLE);
784
785 if (I.getOpcode() == Instruction::SetGE)
786 std::swap(Op0, Op1); // Change setge -> setle
787
788 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000789 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000790 InsertNewInstBefore(Not, I);
791 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
792 }
793
794 // Check to see if we are doing one of many comparisons against constant
795 // integers at the end of their ranges...
796 //
797 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000798 // Simplify seteq and setne instructions...
799 if (I.getOpcode() == Instruction::SetEQ ||
800 I.getOpcode() == Instruction::SetNE) {
801 bool isSetNE = I.getOpcode() == Instruction::SetNE;
802
803 if (CI->isNullValue()) { // Simplify [seteq|setne] X, 0
804 CastInst *Val = new CastInst(Op0, Type::BoolTy, I.getName()+".not");
805 if (isSetNE) return Val;
806
Chris Lattnere967b342003-06-04 05:10:11 +0000807 // seteq X, 0 -> not (cast X to bool)
Chris Lattnere967b342003-06-04 05:10:11 +0000808 InsertNewInstBefore(Val, I);
809 return BinaryOperator::createNot(Val, I.getName());
810 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000811
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000812 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000813 // operand is a constant, simplify a bit.
814 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
815 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1)))
816 if (BO->getOpcode() == Instruction::Or) {
817 // If bits are being or'd in that are not present in the constant we
818 // are comparing against, then the comparison could never succeed!
819 if (!(*BOC & *~*CI)->isNullValue())
820 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
821 } else if (BO->getOpcode() == Instruction::And) {
822 // If bits are being compared against that are and'd out, then the
823 // comparison can never succeed!
824 if (!(*CI & *~*BOC)->isNullValue())
825 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000826 } else if (BO->getOpcode() == Instruction::Xor) {
827 // For the xor case, we can always just xor the two constants
828 // together, potentially eliminating the explicit xor.
829 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
830 *CI ^ *BOC);
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000831 }
Chris Lattnere967b342003-06-04 05:10:11 +0000832 }
Chris Lattner791ac1a2003-06-01 03:35:25 +0000833
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000834 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000835 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000836 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
837 return ReplaceInstUsesWith(I, ConstantBool::False);
838 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
839 return ReplaceInstUsesWith(I, ConstantBool::True);
840 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
841 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
842 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
843 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
844
Chris Lattnere6794492002-08-12 21:17:25 +0000845 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000846 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
847 return ReplaceInstUsesWith(I, ConstantBool::False);
848 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
849 return ReplaceInstUsesWith(I, ConstantBool::True);
850 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
851 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
852 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
853 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
854
855 // Comparing against a value really close to min or max?
856 } else if (isMinValuePlusOne(CI)) {
857 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
858 return BinaryOperator::create(Instruction::SetEQ, Op0,
859 SubOne(CI), I.getName());
860 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
861 return BinaryOperator::create(Instruction::SetNE, Op0,
862 SubOne(CI), I.getName());
863
864 } else if (isMaxValueMinusOne(CI)) {
865 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
866 return BinaryOperator::create(Instruction::SetEQ, Op0,
867 AddOne(CI), I.getName());
868 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
869 return BinaryOperator::create(Instruction::SetNE, Op0,
870 AddOne(CI), I.getName());
871 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000872 }
873
Chris Lattner113f4f42002-06-25 16:13:24 +0000874 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000875}
876
877
878
Chris Lattnere8d6c602003-03-10 19:16:08 +0000879Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000880 assert(I.getOperand(1)->getType() == Type::UByteTy);
881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000882
883 // shl X, 0 == X and shr X, 0 == X
884 // shl 0, X == 0 and shr 0, X == 0
885 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000886 Op0 == Constant::getNullValue(Op0->getType()))
887 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000888
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000889 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000890 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
891 // of a signed value.
892 //
Chris Lattnere8d6c602003-03-10 19:16:08 +0000893 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
894 if (CUI->getValue() >= TypeBits &&
895 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
896 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000897
Chris Lattner3204d4e2003-07-24 17:52:58 +0000898 // If this is a shift of a shift, see if we can fold the two together...
899 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
Chris Lattnerab780df2003-07-24 18:38:56 +0000900 if (ConstantUInt *ShiftAmt1C =
901 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000902 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
903 unsigned ShiftAmt2 = CUI->getValue();
904
905 // Check for (A << c1) << c2 and (A >> c1) >> c2
906 if (I.getOpcode() == Op0SI->getOpcode()) {
907 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
908 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
909 ConstantUInt::get(Type::UByteTy, Amt));
910 }
911
Chris Lattnerab780df2003-07-24 18:38:56 +0000912 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
913 // signed types, we can only support the (A >> c1) << c2 configuration,
914 // because it can not turn an arbitrary bit of A into a sign bit.
915 if (I.getType()->isUnsigned() || I.getOpcode() == Instruction::Shl) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000916 // Calculate bitmask for what gets shifted off the edge...
917 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
918 if (I.getOpcode() == Instruction::Shr)
919 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
920 else
921 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
922
923 Instruction *Mask =
924 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
925 C, Op0SI->getOperand(0)->getName()+".mask");
926 InsertNewInstBefore(Mask, I);
927
928 // Figure out what flavor of shift we should use...
929 if (ShiftAmt1 == ShiftAmt2)
930 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
931 else if (ShiftAmt1 < ShiftAmt2) {
932 return new ShiftInst(I.getOpcode(), Mask,
933 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
934 } else {
935 return new ShiftInst(Op0SI->getOpcode(), Mask,
936 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
937 }
938 }
939 }
940 }
Chris Lattnerab780df2003-07-24 18:38:56 +0000941
942 // Check to see if we are shifting left by 1. If so, turn it into an add
943 // instruction.
944 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
945 // Convert 'shl int %X, 1' to 'add int %X, %X'
946 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000947 }
Chris Lattner2e0fb392002-10-08 16:16:40 +0000948
949 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
Chris Lattner3204d4e2003-07-24 17:52:58 +0000950 if (I.getOpcode() == Instruction::Shr)
951 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
952 if (CSI->isAllOnesValue())
953 return ReplaceInstUsesWith(I, CSI);
Chris Lattner2e0fb392002-10-08 16:16:40 +0000954
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000955 return 0;
956}
957
958
Chris Lattner48a44f72002-05-02 17:06:02 +0000959// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
960// instruction.
961//
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000962static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
963 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +0000964
Chris Lattner650b6da2002-08-02 20:00:25 +0000965 // It is legal to eliminate the instruction if casting A->B->A if the sizes
966 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +0000967 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +0000968 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +0000969 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +0000970
971 // Allow free casting and conversion of sizes as long as the sign doesn't
972 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +0000973 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +0000974 unsigned SrcSize = SrcTy->getPrimitiveSize();
975 unsigned MidSize = MidTy->getPrimitiveSize();
976 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +0000977
Chris Lattner3732aca2002-08-15 16:15:25 +0000978 // Cases where we are monotonically decreasing the size of the type are
979 // always ok, regardless of what sign changes are going on.
980 //
Chris Lattner0bb75912002-08-14 23:21:10 +0000981 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +0000982 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +0000983
Chris Lattner555518c2002-09-23 23:39:43 +0000984 // Cases where the source and destination type are the same, but the middle
985 // type is bigger are noops.
986 //
987 if (SrcSize == DstSize && MidSize > SrcSize)
988 return true;
989
Chris Lattner3732aca2002-08-15 16:15:25 +0000990 // If we are monotonically growing, things are more complex.
991 //
992 if (SrcSize <= MidSize && MidSize <= DstSize) {
993 // We have eight combinations of signedness to worry about. Here's the
994 // table:
995 static const int SignTable[8] = {
996 // CODE, SrcSigned, MidSigned, DstSigned, Comment
997 1, // U U U Always ok
998 1, // U U S Always ok
999 3, // U S U Ok iff SrcSize != MidSize
1000 3, // U S S Ok iff SrcSize != MidSize
1001 0, // S U U Never ok
1002 2, // S U S Ok iff MidSize == DstSize
1003 1, // S S U Always ok
1004 1, // S S S Always ok
1005 };
1006
1007 // Choose an action based on the current entry of the signtable that this
1008 // cast of cast refers to...
1009 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1010 switch (SignTable[Row]) {
1011 case 0: return false; // Never ok
1012 case 1: return true; // Always ok
1013 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1014 case 3: // Ok iff SrcSize != MidSize
1015 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1016 default: assert(0 && "Bad entry in sign table!");
1017 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001018 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001019 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001020
1021 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1022 // like: short -> ushort -> uint, because this can create wrong results if
1023 // the input short is negative!
1024 //
1025 return false;
1026}
1027
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001028static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1029 if (V->getType() == Ty || isa<Constant>(V)) return false;
1030 if (const CastInst *CI = dyn_cast<CastInst>(V))
1031 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1032 return false;
1033 return true;
1034}
1035
1036/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1037/// InsertBefore instruction. This is specialized a bit to avoid inserting
1038/// casts that are known to not do anything...
1039///
1040Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1041 Instruction *InsertBefore) {
1042 if (V->getType() == DestTy) return V;
1043 if (Constant *C = dyn_cast<Constant>(V))
1044 return ConstantExpr::getCast(C, DestTy);
1045
1046 CastInst *CI = new CastInst(V, DestTy, V->getName());
1047 InsertNewInstBefore(CI, *InsertBefore);
1048 return CI;
1049}
Chris Lattner48a44f72002-05-02 17:06:02 +00001050
1051// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00001052//
Chris Lattner113f4f42002-06-25 16:13:24 +00001053Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00001054 Value *Src = CI.getOperand(0);
1055
Chris Lattner48a44f72002-05-02 17:06:02 +00001056 // If the user is casting a value to the same type, eliminate this cast
1057 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00001058 if (CI.getType() == Src->getType())
1059 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00001060
Chris Lattner48a44f72002-05-02 17:06:02 +00001061 // If casting the result of another cast instruction, try to eliminate this
1062 // one!
1063 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001064 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001065 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1066 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001067 // This instruction now refers directly to the cast's src operand. This
1068 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00001069 CI.setOperand(0, CSrc->getOperand(0));
1070 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00001071 }
1072
Chris Lattner650b6da2002-08-02 20:00:25 +00001073 // If this is an A->B->A cast, and we are dealing with integral types, try
1074 // to convert this into a logical 'and' instruction.
1075 //
1076 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001077 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00001078 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1079 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1080 assert(CSrc->getType() != Type::ULongTy &&
1081 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00001082 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00001083 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1084 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1085 AndOp);
1086 }
1087 }
1088
Chris Lattnerd0d51602003-06-21 23:12:02 +00001089 // If casting the result of a getelementptr instruction with no offset, turn
1090 // this into a cast of the original pointer!
1091 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001092 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00001093 bool AllZeroOperands = true;
1094 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1095 if (!isa<Constant>(GEP->getOperand(i)) ||
1096 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1097 AllZeroOperands = false;
1098 break;
1099 }
1100 if (AllZeroOperands) {
1101 CI.setOperand(0, GEP->getOperand(0));
1102 return &CI;
1103 }
1104 }
1105
Chris Lattner55d4bda2003-06-23 21:59:52 +00001106 // If this is a cast to bool (which is effectively a "!=0" test), then we can
1107 // perform a few optimizations...
1108 //
1109 if (CI.getType() == Type::BoolTy) {
1110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Src)) {
1111 Value *Op0 = BO->getOperand(0), *Op1 = BO->getOperand(1);
1112
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001113 switch (BO->getOpcode()) {
1114 case Instruction::Sub:
1115 case Instruction::Xor:
1116 // Replace (cast ([sub|xor] A, B) to bool) with (setne A, B)
Chris Lattner55d4bda2003-06-23 21:59:52 +00001117 return new SetCondInst(Instruction::SetNE, Op0, Op1);
1118
1119 // Replace (cast (add A, B) to bool) with (setne A, -B) if B is
1120 // efficiently invertible, or if the add has just this one use.
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001121 case Instruction::Add:
Chris Lattner55d4bda2003-06-23 21:59:52 +00001122 if (Value *NegVal = dyn_castNegVal(Op1))
1123 return new SetCondInst(Instruction::SetNE, Op0, NegVal);
1124 else if (Value *NegVal = dyn_castNegVal(Op0))
1125 return new SetCondInst(Instruction::SetNE, NegVal, Op1);
1126 else if (BO->use_size() == 1) {
1127 Instruction *Neg = BinaryOperator::createNeg(Op1, BO->getName());
1128 BO->setName("");
1129 InsertNewInstBefore(Neg, CI);
1130 return new SetCondInst(Instruction::SetNE, Op0, Neg);
1131 }
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001132 break;
1133
1134 case Instruction::And:
1135 // Replace (cast (and X, (1 << size(X)-1)) to bool) with x < 0,
1136 // converting X to be a signed value as appropriate. Don't worry about
1137 // bool values, as they will be optimized other ways if they occur in
1138 // this configuration.
1139 if (ConstantInt *CInt = dyn_cast<ConstantInt>(Op1))
1140 if (isSignBit(CInt)) {
1141 // If 'X' is not signed, insert a cast now...
1142 if (!CInt->getType()->isSigned()) {
1143 const Type *DestTy;
1144 switch (CInt->getType()->getPrimitiveID()) {
1145 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1146 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1147 case Type::UIntTyID: DestTy = Type::IntTy; break;
1148 case Type::ULongTyID: DestTy = Type::LongTy; break;
1149 default: assert(0 && "Invalid unsigned integer type!"); abort();
1150 }
1151 CastInst *NewCI = new CastInst(Op0, DestTy,
1152 Op0->getName()+".signed");
1153 InsertNewInstBefore(NewCI, CI);
1154 Op0 = NewCI;
1155 }
1156 return new SetCondInst(Instruction::SetLT, Op0,
1157 Constant::getNullValue(Op0->getType()));
1158 }
1159 break;
1160 default: break;
1161 }
Chris Lattner55d4bda2003-06-23 21:59:52 +00001162 }
1163 }
1164
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001165 // If the source value is an instruction with only this use, we can attempt to
1166 // propagate the cast into the instruction. Also, only handle integral types
1167 // for now.
1168 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1169 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1170 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1171 const Type *DestTy = CI.getType();
1172 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1173 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1174
1175 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1176 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1177
1178 switch (SrcI->getOpcode()) {
1179 case Instruction::Add:
1180 case Instruction::Mul:
1181 case Instruction::And:
1182 case Instruction::Or:
1183 case Instruction::Xor:
1184 // If we are discarding information, or just changing the sign, rewrite.
1185 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1186 // Don't insert two casts if they cannot be eliminated. We allow two
1187 // casts to be inserted if the sizes are the same. This could only be
1188 // converting signedness, which is a noop.
1189 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1190 !ValueRequiresCast(Op0, DestTy)) {
1191 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1192 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1193 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1194 ->getOpcode(), Op0c, Op1c);
1195 }
1196 }
1197 break;
1198 case Instruction::Shl:
1199 // Allow changing the sign of the source operand. Do not allow changing
1200 // the size of the shift, UNLESS the shift amount is a constant. We
1201 // mush not change variable sized shifts to a smaller size, because it
1202 // is undefined to shift more bits out than exist in the value.
1203 if (DestBitSize == SrcBitSize ||
1204 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1205 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1206 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1207 }
1208 break;
1209 }
1210 }
1211
Chris Lattner260ab202002-04-18 17:39:14 +00001212 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00001213}
1214
Chris Lattner970c33a2003-06-19 17:00:31 +00001215// CallInst simplification
1216//
1217Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1218 if (transformConstExprCastCall(&CI)) return 0;
1219 return 0;
1220}
1221
1222// InvokeInst simplification
1223//
1224Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1225 if (transformConstExprCastCall(&II)) return 0;
1226 return 0;
1227}
1228
1229// getPromotedType - Return the specified type promoted as it would be to pass
1230// though a va_arg area...
1231static const Type *getPromotedType(const Type *Ty) {
1232 switch (Ty->getPrimitiveID()) {
1233 case Type::SByteTyID:
1234 case Type::ShortTyID: return Type::IntTy;
1235 case Type::UByteTyID:
1236 case Type::UShortTyID: return Type::UIntTy;
1237 case Type::FloatTyID: return Type::DoubleTy;
1238 default: return Ty;
1239 }
1240}
1241
1242// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1243// attempt to move the cast to the arguments of the call/invoke.
1244//
1245bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1246 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1247 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1248 if (CE->getOpcode() != Instruction::Cast ||
1249 !isa<ConstantPointerRef>(CE->getOperand(0)))
1250 return false;
1251 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1252 if (!isa<Function>(CPR->getValue())) return false;
1253 Function *Callee = cast<Function>(CPR->getValue());
1254 Instruction *Caller = CS.getInstruction();
1255
1256 // Okay, this is a cast from a function to a different type. Unless doing so
1257 // would cause a type conversion of one of our arguments, change this call to
1258 // be a direct call with arguments casted to the appropriate types.
1259 //
1260 const FunctionType *FT = Callee->getFunctionType();
1261 const Type *OldRetTy = Caller->getType();
1262
1263 if (Callee->isExternal() &&
1264 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1265 return false; // Cannot transform this return value...
1266
1267 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1268 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1269
1270 CallSite::arg_iterator AI = CS.arg_begin();
1271 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1272 const Type *ParamTy = FT->getParamType(i);
1273 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1274 if (Callee->isExternal() && !isConvertible) return false;
1275 }
1276
1277 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1278 Callee->isExternal())
1279 return false; // Do not delete arguments unless we have a function body...
1280
1281 // Okay, we decided that this is a safe thing to do: go ahead and start
1282 // inserting cast instructions as necessary...
1283 std::vector<Value*> Args;
1284 Args.reserve(NumActualArgs);
1285
1286 AI = CS.arg_begin();
1287 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1288 const Type *ParamTy = FT->getParamType(i);
1289 if ((*AI)->getType() == ParamTy) {
1290 Args.push_back(*AI);
1291 } else {
1292 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1293 InsertNewInstBefore(Cast, *Caller);
1294 Args.push_back(Cast);
1295 }
1296 }
1297
1298 // If the function takes more arguments than the call was taking, add them
1299 // now...
1300 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1301 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1302
1303 // If we are removing arguments to the function, emit an obnoxious warning...
1304 if (FT->getNumParams() < NumActualArgs)
1305 if (!FT->isVarArg()) {
1306 std::cerr << "WARNING: While resolving call to function '"
1307 << Callee->getName() << "' arguments were dropped!\n";
1308 } else {
1309 // Add all of the arguments in their promoted form to the arg list...
1310 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1311 const Type *PTy = getPromotedType((*AI)->getType());
1312 if (PTy != (*AI)->getType()) {
1313 // Must promote to pass through va_arg area!
1314 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1315 InsertNewInstBefore(Cast, *Caller);
1316 Args.push_back(Cast);
1317 } else {
1318 Args.push_back(*AI);
1319 }
1320 }
1321 }
1322
1323 if (FT->getReturnType() == Type::VoidTy)
1324 Caller->setName(""); // Void type should not have a name...
1325
1326 Instruction *NC;
1327 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1328 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1329 Args, Caller->getName(), Caller);
1330 } else {
1331 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1332 }
1333
1334 // Insert a cast of the return type as necessary...
1335 Value *NV = NC;
1336 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1337 if (NV->getType() != Type::VoidTy) {
1338 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1339 InsertNewInstBefore(NC, *Caller);
1340 AddUsesToWorkList(*Caller);
1341 } else {
1342 NV = Constant::getNullValue(Caller->getType());
1343 }
1344 }
1345
1346 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1347 Caller->replaceAllUsesWith(NV);
1348 Caller->getParent()->getInstList().erase(Caller);
1349 removeFromWorkList(Caller);
1350 return true;
1351}
1352
1353
Chris Lattner48a44f72002-05-02 17:06:02 +00001354
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001355// PHINode simplification
1356//
Chris Lattner113f4f42002-06-25 16:13:24 +00001357Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001358 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +00001359 if (PN.getNumIncomingValues() == 1)
1360 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +00001361
1362 // Otherwise if all of the incoming values are the same for the PHI, replace
1363 // the PHI node with the incoming value.
1364 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +00001365 Value *InVal = 0;
1366 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1367 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1368 if (InVal && PN.getIncomingValue(i) != InVal)
1369 return 0; // Not the same, bail out.
1370 else
1371 InVal = PN.getIncomingValue(i);
1372
1373 // The only case that could cause InVal to be null is if we have a PHI node
1374 // that only has entries for itself. In this case, there is no entry into the
1375 // loop, so kill the PHI.
1376 //
1377 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001378
Chris Lattner9cd1e662002-08-20 15:35:35 +00001379 // All of the incoming values are the same, replace the PHI node now.
1380 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001381}
1382
Chris Lattner48a44f72002-05-02 17:06:02 +00001383
Chris Lattner113f4f42002-06-25 16:13:24 +00001384Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +00001385 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00001386 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001387 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +00001388 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001389 GEP.getNumOperands() == 1)
1390 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +00001391
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001392 // Combine Indices - If the source pointer to this getelementptr instruction
1393 // is a getelementptr instruction, combine the indices of the two
1394 // getelementptr instructions into a single instruction.
1395 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001396 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001397 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +00001398
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001399 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +00001400 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1401 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +00001402 // Replace: gep (gep %P, long C1), long C2, ...
1403 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +00001404 Value *Sum = ConstantExpr::get(Instruction::Add,
1405 cast<Constant>(Src->getOperand(1)),
1406 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +00001407 assert(Sum && "Constant folding of longs failed!?");
1408 GEP.setOperand(0, Src->getOperand(0));
1409 GEP.setOperand(1, Sum);
1410 AddUsesToWorkList(*Src); // Reduce use count of Src
1411 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +00001412 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +00001413 // Replace: gep (gep %P, long B), long A, ...
1414 // With: T = long A+B; gep %P, T, ...
1415 //
1416 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1417 GEP.getOperand(1),
1418 Src->getName()+".sum", &GEP);
1419 GEP.setOperand(0, Src->getOperand(0));
1420 GEP.setOperand(1, Sum);
1421 WorkList.push_back(cast<Instruction>(Sum));
1422 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00001423 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00001424 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001425 // Otherwise we can do the fold if the first index of the GEP is a zero
1426 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1427 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00001428 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1429 Constant::getNullValue(Type::LongTy)) {
1430 // If the src gep ends with a constant array index, merge this get into
1431 // it, even if we have a non-zero array index.
1432 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1433 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001434 }
1435
1436 if (!Indices.empty())
1437 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001438
1439 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1440 // GEP of global variable. If all of the indices for this GEP are
1441 // constants, we can promote this to a constexpr instead of an instruction.
1442
1443 // Scan for nonconstants...
1444 std::vector<Constant*> Indices;
1445 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1446 for (; I != E && isa<Constant>(*I); ++I)
1447 Indices.push_back(cast<Constant>(*I));
1448
1449 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001450 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001451 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1452
1453 // Replace all uses of the GEP with the new constexpr...
1454 return ReplaceInstUsesWith(GEP, CE);
1455 }
Chris Lattnerca081252001-12-14 16:52:21 +00001456 }
1457
Chris Lattnerca081252001-12-14 16:52:21 +00001458 return 0;
1459}
1460
Chris Lattner1085bdf2002-11-04 16:18:53 +00001461Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1462 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1463 if (AI.isArrayAllocation()) // Check C != 1
1464 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1465 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001466 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001467
1468 // Create and insert the replacement instruction...
1469 if (isa<MallocInst>(AI))
1470 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001471 else {
1472 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001473 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001474 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001475
1476 // Scan to the end of the allocation instructions, to skip over a block of
1477 // allocas if possible...
1478 //
1479 BasicBlock::iterator It = New;
1480 while (isa<AllocationInst>(*It)) ++It;
1481
1482 // Now that I is pointing to the first non-allocation-inst in the block,
1483 // insert our getelementptr instruction...
1484 //
1485 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1486 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1487
1488 // Now make everything use the getelementptr instead of the original
1489 // allocation.
1490 ReplaceInstUsesWith(AI, V);
1491 return &AI;
1492 }
1493 return 0;
1494}
1495
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001496/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1497/// constantexpr, return the constant value being addressed by the constant
1498/// expression, or null if something is funny.
1499///
1500static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1501 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1502 return 0; // Do not allow stepping over the value!
1503
1504 // Loop over all of the operands, tracking down which value we are
1505 // addressing...
1506 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1507 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1508 ConstantStruct *CS = cast<ConstantStruct>(C);
1509 if (CU->getValue() >= CS->getValues().size()) return 0;
1510 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1511 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1512 ConstantArray *CA = cast<ConstantArray>(C);
1513 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1514 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1515 } else
1516 return 0;
1517 return C;
1518}
1519
1520Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1521 Value *Op = LI.getOperand(0);
1522 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1523 Op = CPR->getValue();
1524
1525 // Instcombine load (constant global) into the value loaded...
1526 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001527 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001528 return ReplaceInstUsesWith(LI, GV->getInitializer());
1529
1530 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1531 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1532 if (CE->getOpcode() == Instruction::GetElementPtr)
1533 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1534 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001535 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001536 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1537 return ReplaceInstUsesWith(LI, V);
1538 return 0;
1539}
1540
1541
Chris Lattner9eef8a72003-06-04 04:46:00 +00001542Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1543 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner45789ac2003-06-05 20:12:51 +00001544 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
Chris Lattnere967b342003-06-04 05:10:11 +00001545 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1546 BasicBlock *TrueDest = BI.getSuccessor(0);
1547 BasicBlock *FalseDest = BI.getSuccessor(1);
1548 // Swap Destinations and condition...
1549 BI.setCondition(V);
1550 BI.setSuccessor(0, FalseDest);
1551 BI.setSuccessor(1, TrueDest);
1552 return &BI;
1553 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00001554 return 0;
1555}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001556
Chris Lattnerca081252001-12-14 16:52:21 +00001557
Chris Lattner99f48c62002-09-02 04:59:56 +00001558void InstCombiner::removeFromWorkList(Instruction *I) {
1559 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1560 WorkList.end());
1561}
1562
Chris Lattner113f4f42002-06-25 16:13:24 +00001563bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001564 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001565
Chris Lattner260ab202002-04-18 17:39:14 +00001566 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001567
1568 while (!WorkList.empty()) {
1569 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1570 WorkList.pop_back();
1571
Misha Brukman632df282002-10-29 23:06:16 +00001572 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001573 // Check to see if we can DIE the instruction...
1574 if (isInstructionTriviallyDead(I)) {
1575 // Add operands to the worklist...
1576 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1577 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1578 WorkList.push_back(Op);
1579
1580 ++NumDeadInst;
1581 BasicBlock::iterator BBI = I;
1582 if (dceInstruction(BBI)) {
1583 removeFromWorkList(I);
1584 continue;
1585 }
1586 }
1587
Misha Brukman632df282002-10-29 23:06:16 +00001588 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001589 if (Constant *C = ConstantFoldInstruction(I)) {
1590 // Add operands to the worklist...
1591 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1592 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1593 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001594 ReplaceInstUsesWith(*I, C);
1595
Chris Lattner99f48c62002-09-02 04:59:56 +00001596 ++NumConstProp;
1597 BasicBlock::iterator BBI = I;
1598 if (dceInstruction(BBI)) {
1599 removeFromWorkList(I);
1600 continue;
1601 }
1602 }
1603
Chris Lattnerca081252001-12-14 16:52:21 +00001604 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001605 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001606 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001607 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001608 if (Result != I) {
1609 // Instructions can end up on the worklist more than once. Make sure
1610 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001611 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001612 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001613 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001614 BasicBlock::iterator II = I;
1615
1616 // If the instruction was modified, it's possible that it is now dead.
1617 // if so, remove it.
1618 if (dceInstruction(II)) {
1619 // Instructions may end up in the worklist more than once. Erase them
1620 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001621 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001622 Result = 0;
1623 }
Chris Lattner053c0932002-05-14 15:24:07 +00001624 }
Chris Lattner260ab202002-04-18 17:39:14 +00001625
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001626 if (Result) {
1627 WorkList.push_back(Result);
1628 AddUsesToWorkList(*Result);
1629 }
Chris Lattner260ab202002-04-18 17:39:14 +00001630 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001631 }
1632 }
1633
Chris Lattner260ab202002-04-18 17:39:14 +00001634 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001635}
1636
1637Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001638 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001639}