blob: 8a3c0d47e97f0b41c51b77244a9203644c240639 [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
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000018// 2. Bitwise operators with constant operands are always grouped so that
19// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000020// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
21// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000022// 5. add X, X is represented as (X*2) => (X << 1)
23// 6. Multiplies with a power-of-two constant argument are transformed into
24// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000025// N. This list is incomplete
26//
Chris Lattnerca081252001-12-14 16:52:21 +000027//===----------------------------------------------------------------------===//
28
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000029#include "llvm/Transforms/Scalar.h"
Chris Lattner9b55e5a2002-05-07 18:12:18 +000030#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnerae7a0d32002-08-02 19:29:35 +000031#include "llvm/Transforms/Utils/Local.h"
Chris Lattner471bd762003-05-22 19:07:21 +000032#include "llvm/Instructions.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000033#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000034#include "llvm/Constants.h"
35#include "llvm/ConstantHandling.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000036#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000037#include "llvm/GlobalVariable.h"
Chris Lattner60a65912002-02-12 21:07:25 +000038#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000039#include "llvm/Support/InstVisitor.h"
Chris Lattner970c33a2003-06-19 17:00:31 +000040#include "llvm/Support/CallSite.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000041#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000042#include <algorithm>
Chris Lattnerca081252001-12-14 16:52:21 +000043
Chris Lattner260ab202002-04-18 17:39:14 +000044namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000045 Statistic<> NumCombined ("instcombine", "Number of insts combined");
46 Statistic<> NumConstProp("instcombine", "Number of constant folds");
47 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
48
Chris Lattnerc8e66542002-04-27 06:56:12 +000049 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000050 public InstVisitor<InstCombiner, Instruction*> {
51 // Worklist of all of the instructions that need to be simplified.
52 std::vector<Instruction*> WorkList;
53
Chris Lattner113f4f42002-06-25 16:13:24 +000054 void AddUsesToWorkList(Instruction &I) {
Chris Lattner260ab202002-04-18 17:39:14 +000055 // The instruction was simplified, add all users of the instruction to
56 // the work lists because they might get more simplified now...
57 //
Chris Lattner113f4f42002-06-25 16:13:24 +000058 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000059 UI != UE; ++UI)
60 WorkList.push_back(cast<Instruction>(*UI));
61 }
62
Chris Lattner99f48c62002-09-02 04:59:56 +000063 // removeFromWorkList - remove all instances of I from the worklist.
64 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000065 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000066 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000067
Chris Lattnerf12cc842002-04-28 21:27:06 +000068 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner820d9712002-10-21 20:00:28 +000069 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000070 }
71
Chris Lattner260ab202002-04-18 17:39:14 +000072 // Visitation implementation - Implement instruction combining for different
73 // instruction types. The semantics are as follows:
74 // Return Value:
75 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +000076 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +000077 // otherwise - Change was made, replace I with returned instruction
78 //
Chris Lattner113f4f42002-06-25 16:13:24 +000079 Instruction *visitAdd(BinaryOperator &I);
80 Instruction *visitSub(BinaryOperator &I);
81 Instruction *visitMul(BinaryOperator &I);
82 Instruction *visitDiv(BinaryOperator &I);
83 Instruction *visitRem(BinaryOperator &I);
84 Instruction *visitAnd(BinaryOperator &I);
85 Instruction *visitOr (BinaryOperator &I);
86 Instruction *visitXor(BinaryOperator &I);
87 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +000088 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +000089 Instruction *visitCastInst(CastInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +000090 Instruction *visitCallInst(CallInst &CI);
91 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +000092 Instruction *visitPHINode(PHINode &PN);
93 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +000094 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +000095 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +000096 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner260ab202002-04-18 17:39:14 +000097
98 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +000099 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000100
Chris Lattner970c33a2003-06-19 17:00:31 +0000101 private:
102 bool transformConstExprCastCall(CallSite CS);
103
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000104 // InsertNewInstBefore - insert an instruction New before instruction Old
105 // in the program. Add the new instruction to the worklist.
106 //
107 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000108 assert(New && New->getParent() == 0 &&
109 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000110 BasicBlock *BB = Old.getParent();
111 BB->getInstList().insert(&Old, New); // Insert inst
112 WorkList.push_back(New); // Add to worklist
113 }
114
115 // ReplaceInstUsesWith - This method is to be used when an instruction is
116 // found to be dead, replacable with another preexisting expression. Here
117 // we add all uses of I to the worklist, replace all uses of I with the new
118 // value, then return I, so that the inst combiner will know that I was
119 // modified.
120 //
121 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
122 AddUsesToWorkList(I); // Add all modified instrs to worklist
123 I.replaceAllUsesWith(V);
124 return &I;
125 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000126
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000127 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
128 /// InsertBefore instruction. This is specialized a bit to avoid inserting
129 /// casts that are known to not do anything...
130 ///
131 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
132 Instruction *InsertBefore);
133
Chris Lattner7fb29e12003-03-11 00:12:48 +0000134 // SimplifyCommutative - This performs a few simplifications for commutative
135 // operators...
136 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattner260ab202002-04-18 17:39:14 +0000137 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000138
Chris Lattnerc8b70922002-07-26 21:12:46 +0000139 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000140}
141
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000142// getComplexity: Assign a complexity or rank value to LLVM Values...
143// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
144static unsigned getComplexity(Value *V) {
145 if (isa<Instruction>(V)) {
146 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
147 return 2;
148 return 3;
149 }
150 if (isa<Argument>(V)) return 2;
151 return isa<Constant>(V) ? 0 : 1;
152}
Chris Lattner260ab202002-04-18 17:39:14 +0000153
Chris Lattner7fb29e12003-03-11 00:12:48 +0000154// isOnlyUse - Return true if this instruction will be deleted if we stop using
155// it.
156static bool isOnlyUse(Value *V) {
157 return V->use_size() == 1 || isa<Constant>(V);
158}
159
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000160// SimplifyCommutative - This performs a few simplifications for commutative
161// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000162//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000163// 1. Order operands such that they are listed from right (least complex) to
164// left (most complex). This puts constants before unary operators before
165// binary operators.
166//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000167// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
168// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000169//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000170bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000171 bool Changed = false;
172 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
173 Changed = !I.swapOperands();
174
175 if (!I.isAssociative()) return Changed;
176 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000177 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
178 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
179 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000180 Constant *Folded = ConstantExpr::get(I.getOpcode(),
181 cast<Constant>(I.getOperand(1)),
182 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000183 I.setOperand(0, Op->getOperand(0));
184 I.setOperand(1, Folded);
185 return true;
186 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
187 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
188 isOnlyUse(Op) && isOnlyUse(Op1)) {
189 Constant *C1 = cast<Constant>(Op->getOperand(1));
190 Constant *C2 = cast<Constant>(Op1->getOperand(1));
191
192 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000193 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000194 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
195 Op1->getOperand(0),
196 Op1->getName(), &I);
197 WorkList.push_back(New);
198 I.setOperand(0, New);
199 I.setOperand(1, Folded);
200 return true;
201 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000202 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000203 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000204}
Chris Lattnerca081252001-12-14 16:52:21 +0000205
Chris Lattnerbb74e222003-03-10 23:06:50 +0000206// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
207// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000208//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000209static inline Value *dyn_castNegVal(Value *V) {
210 if (BinaryOperator::isNeg(V))
211 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
212
Chris Lattner9244df62003-04-30 22:19:10 +0000213 // Constants can be considered to be negated values if they can be folded...
214 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000215 return ConstantExpr::get(Instruction::Sub,
216 Constant::getNullValue(V->getType()), C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000217 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000218}
219
Chris Lattnerbb74e222003-03-10 23:06:50 +0000220static inline Value *dyn_castNotVal(Value *V) {
221 if (BinaryOperator::isNot(V))
222 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
223
224 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000225 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner34428442003-05-27 16:40:51 +0000226 return ConstantExpr::get(Instruction::Xor,
227 ConstantIntegral::getAllOnesValue(C->getType()),C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000228 return 0;
229}
230
Chris Lattner7fb29e12003-03-11 00:12:48 +0000231// dyn_castFoldableMul - If this value is a multiply that can be folded into
232// other computations (because it has a constant operand), return the
233// non-constant operand of the multiply.
234//
235static inline Value *dyn_castFoldableMul(Value *V) {
236 if (V->use_size() == 1 && V->getType()->isInteger())
237 if (Instruction *I = dyn_cast<Instruction>(V))
238 if (I->getOpcode() == Instruction::Mul)
239 if (isa<Constant>(I->getOperand(1)))
240 return I->getOperand(0);
241 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000242}
Chris Lattner31ae8632002-08-14 17:51:49 +0000243
Chris Lattner7fb29e12003-03-11 00:12:48 +0000244// dyn_castMaskingAnd - If this value is an And instruction masking a value with
245// a constant, return the constant being anded with.
246//
Chris Lattner01d56392003-08-12 19:17:27 +0000247template<class ValueType>
248static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000249 if (Instruction *I = dyn_cast<Instruction>(V))
250 if (I->getOpcode() == Instruction::And)
251 return dyn_cast<Constant>(I->getOperand(1));
252
253 // If this is a constant, it acts just like we were masking with it.
254 return dyn_cast<Constant>(V);
255}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000256
257// Log2 - Calculate the log base 2 for the specified value if it is exactly a
258// power of 2.
259static unsigned Log2(uint64_t Val) {
260 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
261 unsigned Count = 0;
262 while (Val != 1) {
263 if (Val & 1) return 0; // Multiple bits set?
264 Val >>= 1;
265 ++Count;
266 }
267 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000268}
269
Chris Lattner113f4f42002-06-25 16:13:24 +0000270Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000271 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000272 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000273
274 // Eliminate 'add int %X, 0'
Chris Lattnere6794492002-08-12 21:17:25 +0000275 if (RHS == Constant::getNullValue(I.getType()))
276 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000277
Chris Lattnerede3fe02003-08-13 04:18:28 +0000278 // Convert 'add X, X' to 'shl X, 1'
279 if (LHS == RHS && I.getType()->isInteger())
280 return new ShiftInst(Instruction::Shl, LHS,
281 ConstantInt::get(Type::UByteTy, 1));
282
Chris Lattner147e9752002-05-08 22:46:53 +0000283 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000284 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000285 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000286
287 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000288 if (!isa<Constant>(RHS))
289 if (Value *V = dyn_castNegVal(RHS))
290 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000291
Chris Lattner57c8d992003-02-18 19:57:07 +0000292 // X*C + X --> X * (C+1)
293 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000294 Constant *CP1 =
295 ConstantExpr::get(Instruction::Add,
296 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
297 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000298 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
299 }
300
301 // X + X*C --> X * (C+1)
302 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000303 Constant *CP1 =
304 ConstantExpr::get(Instruction::Add,
305 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
306 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000307 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
308 }
309
Chris Lattner7fb29e12003-03-11 00:12:48 +0000310 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
311 if (Constant *C1 = dyn_castMaskingAnd(LHS))
312 if (Constant *C2 = dyn_castMaskingAnd(RHS))
Chris Lattner34428442003-05-27 16:40:51 +0000313 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000314 return BinaryOperator::create(Instruction::Or, LHS, RHS);
315
Chris Lattner113f4f42002-06-25 16:13:24 +0000316 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000317}
318
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000319// isSignBit - Return true if the value represented by the constant only has the
320// highest order bit set.
321static bool isSignBit(ConstantInt *CI) {
322 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
323 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
324}
325
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000326static unsigned getTypeSizeInBits(const Type *Ty) {
327 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
328}
329
Chris Lattner113f4f42002-06-25 16:13:24 +0000330Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000331 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000332
Chris Lattnere6794492002-08-12 21:17:25 +0000333 if (Op0 == Op1) // sub X, X -> 0
334 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000335
Chris Lattnere6794492002-08-12 21:17:25 +0000336 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000337 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000338 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000339
Chris Lattner3082c5a2003-02-18 19:28:33 +0000340 // Replace (-1 - A) with (~A)...
341 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
342 if (C->isAllOnesValue())
343 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000344
Chris Lattner3082c5a2003-02-18 19:28:33 +0000345 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
346 if (Op1I->use_size() == 1) {
347 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
348 // is not used by anyone else...
349 //
350 if (Op1I->getOpcode() == Instruction::Sub) {
351 // Swap the two operands of the subexpr...
352 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
353 Op1I->setOperand(0, IIOp1);
354 Op1I->setOperand(1, IIOp0);
355
356 // Create the new top level add instruction...
357 return BinaryOperator::create(Instruction::Add, Op0, Op1);
358 }
359
360 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
361 //
362 if (Op1I->getOpcode() == Instruction::And &&
363 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
364 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
365
366 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
367 return BinaryOperator::create(Instruction::And, Op0, NewNot);
368 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000369
370 // X - X*C --> X * (1-C)
371 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000372 Constant *CP1 =
373 ConstantExpr::get(Instruction::Sub,
374 ConstantInt::get(I.getType(), 1),
375 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000376 assert(CP1 && "Couldn't constant fold 1-C?");
377 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
378 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000379 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000380
Chris Lattner57c8d992003-02-18 19:57:07 +0000381 // X*C - X --> X * (C-1)
382 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000383 Constant *CP1 =
384 ConstantExpr::get(Instruction::Sub,
385 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
386 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000387 assert(CP1 && "Couldn't constant fold C - 1?");
388 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
389 }
390
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000391 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000392}
393
Chris Lattner113f4f42002-06-25 16:13:24 +0000394Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000395 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000396 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000397
Chris Lattnere6794492002-08-12 21:17:25 +0000398 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000399 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
400 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000401
402 // ((X << C1)*C2) == (X * (C2 << C1))
403 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
404 if (SI->getOpcode() == Instruction::Shl)
405 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
406 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
407 *CI << *ShOp);
408
Chris Lattner3082c5a2003-02-18 19:28:33 +0000409 const Type *Ty = CI->getType();
Chris Lattner6077c312003-07-23 15:22:26 +0000410 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000411 switch (Val) {
Chris Lattner35236d82003-06-25 17:09:20 +0000412 case -1: // X * -1 -> -X
413 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner3082c5a2003-02-18 19:28:33 +0000414 case 0:
415 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
416 case 1:
417 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
Chris Lattner3082c5a2003-02-18 19:28:33 +0000418 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000419
Chris Lattner3082c5a2003-02-18 19:28:33 +0000420 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
421 return new ShiftInst(Instruction::Shl, Op0,
422 ConstantUInt::get(Type::UByteTy, C));
423 } else {
424 ConstantFP *Op1F = cast<ConstantFP>(Op1);
425 if (Op1F->isNullValue())
426 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000427
Chris Lattner3082c5a2003-02-18 19:28:33 +0000428 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
429 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
430 if (Op1F->getValue() == 1.0)
431 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
432 }
Chris Lattner260ab202002-04-18 17:39:14 +0000433 }
434
Chris Lattner934a64cf2003-03-10 23:23:04 +0000435 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
436 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
437 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
438
Chris Lattner113f4f42002-06-25 16:13:24 +0000439 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000440}
441
Chris Lattner113f4f42002-06-25 16:13:24 +0000442Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000443 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000444 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000445 if (RHS->equalsInt(1))
446 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000447
448 // Check to see if this is an unsigned division with an exact power of 2,
449 // if so, convert to a right shift.
450 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
451 if (uint64_t Val = C->getValue()) // Don't break X / 0
452 if (uint64_t C = Log2(Val))
453 return new ShiftInst(Instruction::Shr, I.getOperand(0),
454 ConstantUInt::get(Type::UByteTy, C));
455 }
456
457 // 0 / X == 0, we don't need to preserve faults!
458 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
459 if (LHS->equalsInt(0))
460 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
461
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000462 return 0;
463}
464
465
Chris Lattner113f4f42002-06-25 16:13:24 +0000466Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000467 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
468 if (RHS->equalsInt(1)) // X % 1 == 0
469 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
470
471 // Check to see if this is an unsigned remainder with an exact power of 2,
472 // if so, convert to a bitwise and.
473 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
474 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
475 if (Log2(Val))
476 return BinaryOperator::create(Instruction::And, I.getOperand(0),
477 ConstantUInt::get(I.getType(), Val-1));
478 }
479
480 // 0 % X == 0, we don't need to preserve faults!
481 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
482 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000483 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
484
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000485 return 0;
486}
487
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000488// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000489static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000490 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
491 // Calculate -1 casted to the right type...
492 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
493 uint64_t Val = ~0ULL; // All ones
494 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
495 return CU->getValue() == Val-1;
496 }
497
498 const ConstantSInt *CS = cast<ConstantSInt>(C);
499
500 // Calculate 0111111111..11111
501 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
502 int64_t Val = INT64_MAX; // All ones
503 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
504 return CS->getValue() == Val-1;
505}
506
507// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000508static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000509 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
510 return CU->getValue() == 1;
511
512 const ConstantSInt *CS = cast<ConstantSInt>(C);
513
514 // Calculate 1111111111000000000000
515 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
516 int64_t Val = -1; // All ones
517 Val <<= TypeBits-1; // Shift over to the right spot
518 return CS->getValue() == Val+1;
519}
520
521
Chris Lattner113f4f42002-06-25 16:13:24 +0000522Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000523 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000524 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000525
526 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000527 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
528 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000529
530 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +0000531 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000532 if (RHS->isAllOnesValue())
533 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000534
Chris Lattner33217db2003-07-23 19:36:21 +0000535 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
536 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +0000537 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
538 if (Op0I->getOpcode() == Instruction::Xor) {
Chris Lattner33217db2003-07-23 19:36:21 +0000539 if ((*RHS & *Op0CI)->isNullValue()) {
540 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
541 return BinaryOperator::create(Instruction::And, X, RHS);
542 } else if (isOnlyUse(Op0)) {
Chris Lattner16464b32003-07-23 19:25:52 +0000543 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
544 std::string Op0Name = Op0I->getName(); Op0I->setName("");
545 Instruction *And = BinaryOperator::create(Instruction::And,
Chris Lattner33217db2003-07-23 19:36:21 +0000546 X, RHS, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000547 InsertNewInstBefore(And, I);
548 return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
549 }
550 } else if (Op0I->getOpcode() == Instruction::Or) {
551 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
552 if ((*RHS & *Op0CI)->isNullValue())
Chris Lattner33217db2003-07-23 19:36:21 +0000553 return BinaryOperator::create(Instruction::And, X, RHS);
Chris Lattner16464b32003-07-23 19:25:52 +0000554
555 Constant *Together = *RHS & *Op0CI;
556 if (Together == RHS) // (X | C) & C --> C
557 return ReplaceInstUsesWith(I, RHS);
558
559 if (isOnlyUse(Op0)) {
560 if (Together != Op0CI) {
561 // (X | C1) & C2 --> (X | (C1&C2)) & C2
562 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattner33217db2003-07-23 19:36:21 +0000563 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
564 Together, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000565 InsertNewInstBefore(Or, I);
566 return BinaryOperator::create(Instruction::And, Or, RHS);
567 }
568 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000569 }
Chris Lattner33217db2003-07-23 19:36:21 +0000570 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000571 }
572
Chris Lattnerbb74e222003-03-10 23:06:50 +0000573 Value *Op0NotVal = dyn_castNotVal(Op0);
574 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000575
576 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000577 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000578 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
Chris Lattner49b47ae2003-07-23 17:57:01 +0000579 Op1NotVal,I.getName()+".demorgan");
580 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000581 return BinaryOperator::createNot(Or);
582 }
583
584 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
585 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000586
Chris Lattner113f4f42002-06-25 16:13:24 +0000587 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000588}
589
590
591
Chris Lattner113f4f42002-06-25 16:13:24 +0000592Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000593 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000594 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000595
596 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000597 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
598 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000599
600 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +0000601 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000602 if (RHS->isAllOnesValue())
603 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000604
Chris Lattner8f0d1562003-07-23 18:29:44 +0000605 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
606 // (X & C1) | C2 --> (X | C2) & (C1|C2)
607 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
608 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
609 std::string Op0Name = Op0I->getName(); Op0I->setName("");
610 Instruction *Or = BinaryOperator::create(Instruction::Or,
611 Op0I->getOperand(0), RHS,
612 Op0Name);
613 InsertNewInstBefore(Or, I);
614 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
615 }
616
617 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
618 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
619 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
620 std::string Op0Name = Op0I->getName(); Op0I->setName("");
621 Instruction *Or = BinaryOperator::create(Instruction::Or,
622 Op0I->getOperand(0), RHS,
623 Op0Name);
624 InsertNewInstBefore(Or, I);
625 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
626 }
627 }
628 }
629
Chris Lattner812aab72003-08-12 19:11:07 +0000630 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattner01d56392003-08-12 19:17:27 +0000631 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
632 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
633 if (LHS->getOperand(0) == RHS->getOperand(0))
634 if (Constant *C0 = dyn_castMaskingAnd(LHS))
635 if (Constant *C1 = dyn_castMaskingAnd(RHS))
636 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
Chris Lattner812aab72003-08-12 19:11:07 +0000637 *C0 | *C1);
638
Chris Lattner3e327a42003-03-10 23:13:59 +0000639 Value *Op0NotVal = dyn_castNotVal(Op0);
640 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000641
Chris Lattner3e327a42003-03-10 23:13:59 +0000642 if (Op1 == Op0NotVal) // ~A | A == -1
643 return ReplaceInstUsesWith(I,
644 ConstantIntegral::getAllOnesValue(I.getType()));
645
646 if (Op0 == Op1NotVal) // A | ~A == -1
647 return ReplaceInstUsesWith(I,
648 ConstantIntegral::getAllOnesValue(I.getType()));
649
650 // (~A | ~B) == (~(A & B)) - Demorgan's Law
651 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
652 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
653 Op1NotVal,I.getName()+".demorgan",
654 &I);
655 WorkList.push_back(And);
656 return BinaryOperator::createNot(And);
657 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000658
Chris Lattner113f4f42002-06-25 16:13:24 +0000659 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000660}
661
662
663
Chris Lattner113f4f42002-06-25 16:13:24 +0000664Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000665 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000666 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000667
668 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000669 if (Op0 == Op1)
670 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000671
Chris Lattner97638592003-07-23 21:37:07 +0000672 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000673 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +0000674 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +0000675 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000676
Chris Lattner97638592003-07-23 21:37:07 +0000677 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000678 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +0000679 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
680 if (RHS == ConstantBool::True && SCI->use_size() == 1)
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000681 return new SetCondInst(SCI->getInverseCondition(),
682 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattner97638592003-07-23 21:37:07 +0000683
684 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
685 if (Op0I->getOpcode() == Instruction::And) {
686 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
687 if ((*RHS & *Op0CI)->isNullValue())
688 return BinaryOperator::create(Instruction::Or, Op0, RHS);
689 } else if (Op0I->getOpcode() == Instruction::Or) {
690 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
691 if ((*RHS & *Op0CI) == RHS)
692 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
693 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000694 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000695 }
696
Chris Lattnerbb74e222003-03-10 23:06:50 +0000697 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000698 if (X == Op1)
699 return ReplaceInstUsesWith(I,
700 ConstantIntegral::getAllOnesValue(I.getType()));
701
Chris Lattnerbb74e222003-03-10 23:06:50 +0000702 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000703 if (X == Op0)
704 return ReplaceInstUsesWith(I,
705 ConstantIntegral::getAllOnesValue(I.getType()));
706
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000707 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
708 if (Op1I->getOpcode() == Instruction::Or)
709 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
710 cast<BinaryOperator>(Op1I)->swapOperands();
711 I.swapOperands();
712 std::swap(Op0, Op1);
713 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
714 I.swapOperands();
715 std::swap(Op0, Op1);
716 }
717
718 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
719 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
720 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
721 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000722 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000723 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
724 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000725 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
726 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000727 }
728 }
729
Chris Lattner7fb29e12003-03-11 00:12:48 +0000730 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
731 if (Constant *C1 = dyn_castMaskingAnd(Op0))
732 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +0000733 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000734 return BinaryOperator::create(Instruction::Or, Op0, Op1);
735
Chris Lattner113f4f42002-06-25 16:13:24 +0000736 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000737}
738
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000739// AddOne, SubOne - Add or subtract a constant one from an integer constant...
740static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000741 Constant *Result = ConstantExpr::get(Instruction::Add, C,
742 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000743 assert(Result && "Constant folding integer addition failed!");
744 return Result;
745}
746static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000747 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
748 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000749 assert(Result && "Constant folding integer addition failed!");
750 return Result;
751}
752
Chris Lattner1fc23f32002-05-09 20:11:54 +0000753// isTrueWhenEqual - Return true if the specified setcondinst instruction is
754// true when both operands are equal...
755//
Chris Lattner113f4f42002-06-25 16:13:24 +0000756static bool isTrueWhenEqual(Instruction &I) {
757 return I.getOpcode() == Instruction::SetEQ ||
758 I.getOpcode() == Instruction::SetGE ||
759 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000760}
761
Chris Lattner113f4f42002-06-25 16:13:24 +0000762Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000763 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000764 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
765 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000766
767 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000768 if (Op0 == Op1)
769 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000770
Chris Lattnerd07283a2003-08-13 05:38:46 +0000771 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
772 if (isa<ConstantPointerNull>(Op1) &&
773 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000774 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
775
Chris Lattnerd07283a2003-08-13 05:38:46 +0000776
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000777 // setcc's with boolean values can always be turned into bitwise operations
778 if (Ty == Type::BoolTy) {
779 // If this is <, >, or !=, we can change this into a simple xor instruction
780 if (!isTrueWhenEqual(I))
781 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
782
783 // Otherwise we need to make a temporary intermediate instruction and insert
784 // it into the instruction stream. This is what we are after:
785 //
786 // seteq bool %A, %B -> ~(A^B)
787 // setle bool %A, %B -> ~A | B
788 // setge bool %A, %B -> A | ~B
789 //
790 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
791 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
792 I.getName()+"tmp");
793 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000794 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000795 }
796
797 // Handle the setXe cases...
798 assert(I.getOpcode() == Instruction::SetGE ||
799 I.getOpcode() == Instruction::SetLE);
800
801 if (I.getOpcode() == Instruction::SetGE)
802 std::swap(Op0, Op1); // Change setge -> setle
803
804 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000805 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000806 InsertNewInstBefore(Not, I);
807 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
808 }
809
810 // Check to see if we are doing one of many comparisons against constant
811 // integers at the end of their ranges...
812 //
813 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000814 // Simplify seteq and setne instructions...
815 if (I.getOpcode() == Instruction::SetEQ ||
816 I.getOpcode() == Instruction::SetNE) {
817 bool isSetNE = I.getOpcode() == Instruction::SetNE;
818
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000819 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000820 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +0000821 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
822 switch (BO->getOpcode()) {
823 case Instruction::Add:
824 if (CI->isNullValue()) {
825 // Replace ((add A, B) != 0) with (A != -B) if A or B is
826 // efficiently invertible, or if the add has just this one use.
827 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
828 if (Value *NegVal = dyn_castNegVal(BOp1))
829 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
830 else if (Value *NegVal = dyn_castNegVal(BOp0))
831 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
832 else if (BO->use_size() == 1) {
833 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
834 BO->setName("");
835 InsertNewInstBefore(Neg, I);
836 return new SetCondInst(I.getOpcode(), BOp0, Neg);
837 }
838 }
839 break;
840 case Instruction::Xor:
841 // For the xor case, we can xor two constants together, eliminating
842 // the explicit xor.
843 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
844 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
845 *CI ^ *BOC);
846
847 // FALLTHROUGH
848 case Instruction::Sub:
849 // Replace (([sub|xor] A, B) != 0) with (A != B)
850 if (CI->isNullValue())
851 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
852 BO->getOperand(1));
853 break;
854
855 case Instruction::Or:
856 // If bits are being or'd in that are not present in the constant we
857 // are comparing against, then the comparison could never succeed!
858 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000859 if (!(*BOC & *~*CI)->isNullValue())
860 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +0000861 break;
862
863 case Instruction::And:
864 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000865 // If bits are being compared against that are and'd out, then the
866 // comparison can never succeed!
867 if (!(*CI & *~*BOC)->isNullValue())
868 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +0000869
870 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
871 // to be a signed value as appropriate.
872 if (isSignBit(BOC)) {
873 Value *X = BO->getOperand(0);
874 // If 'X' is not signed, insert a cast now...
875 if (!BOC->getType()->isSigned()) {
876 const Type *DestTy;
877 switch (BOC->getType()->getPrimitiveID()) {
878 case Type::UByteTyID: DestTy = Type::SByteTy; break;
879 case Type::UShortTyID: DestTy = Type::ShortTy; break;
880 case Type::UIntTyID: DestTy = Type::IntTy; break;
881 case Type::ULongTyID: DestTy = Type::LongTy; break;
882 default: assert(0 && "Invalid unsigned integer type!"); abort();
883 }
884 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
885 InsertNewInstBefore(NewCI, I);
886 X = NewCI;
887 }
888 return new SetCondInst(isSetNE ? Instruction::SetLT :
889 Instruction::SetGE, X,
890 Constant::getNullValue(X->getType()));
891 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000892 }
Chris Lattnerc992add2003-08-13 05:33:12 +0000893 default: break;
894 }
895 }
Chris Lattnere967b342003-06-04 05:10:11 +0000896 }
Chris Lattner791ac1a2003-06-01 03:35:25 +0000897
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000898 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +0000899 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000900 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
901 return ReplaceInstUsesWith(I, ConstantBool::False);
902 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
903 return ReplaceInstUsesWith(I, ConstantBool::True);
904 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
905 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
906 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
907 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
908
Chris Lattnere6794492002-08-12 21:17:25 +0000909 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000910 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
911 return ReplaceInstUsesWith(I, ConstantBool::False);
912 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
913 return ReplaceInstUsesWith(I, ConstantBool::True);
914 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
915 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
916 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
917 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
918
919 // Comparing against a value really close to min or max?
920 } else if (isMinValuePlusOne(CI)) {
921 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
922 return BinaryOperator::create(Instruction::SetEQ, Op0,
923 SubOne(CI), I.getName());
924 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
925 return BinaryOperator::create(Instruction::SetNE, Op0,
926 SubOne(CI), I.getName());
927
928 } else if (isMaxValueMinusOne(CI)) {
929 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
930 return BinaryOperator::create(Instruction::SetEQ, Op0,
931 AddOne(CI), I.getName());
932 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
933 return BinaryOperator::create(Instruction::SetNE, Op0,
934 AddOne(CI), I.getName());
935 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000936 }
937
Chris Lattner113f4f42002-06-25 16:13:24 +0000938 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000939}
940
941
942
Chris Lattnere8d6c602003-03-10 19:16:08 +0000943Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000944 assert(I.getOperand(1)->getType() == Type::UByteTy);
945 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000946 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000947
948 // shl X, 0 == X and shr X, 0 == X
949 // shl 0, X == 0 and shr 0, X == 0
950 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +0000951 Op0 == Constant::getNullValue(Op0->getType()))
952 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000953
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000954 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
955 if (!isLeftShift)
956 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
957 if (CSI->isAllOnesValue())
958 return ReplaceInstUsesWith(I, CSI);
959
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000960 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +0000961 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
962 // of a signed value.
963 //
Chris Lattnere8d6c602003-03-10 19:16:08 +0000964 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
965 if (CUI->getValue() >= TypeBits &&
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000966 (!Op0->getType()->isSigned() || isLeftShift))
Chris Lattnere8d6c602003-03-10 19:16:08 +0000967 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +0000968
Chris Lattnerede3fe02003-08-13 04:18:28 +0000969 // ((X*C1) << C2) == (X * (C1 << C2))
970 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
971 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
972 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
973 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
974 *BOOp << *CUI);
975
976
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +0000977 // If the operand is an bitwise operator with a constant RHS, and the
978 // shift is the only use, we can pull it out of the shift.
979 if (Op0->use_size() == 1)
980 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
981 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
982 bool isValid = true; // Valid only for And, Or, Xor
983 bool highBitSet = false; // Transform if high bit of constant set?
984
985 switch (Op0BO->getOpcode()) {
986 default: isValid = false; break; // Do not perform transform!
987 case Instruction::Or:
988 case Instruction::Xor:
989 highBitSet = false;
990 break;
991 case Instruction::And:
992 highBitSet = true;
993 break;
994 }
995
996 // If this is a signed shift right, and the high bit is modified
997 // by the logical operation, do not perform the transformation.
998 // The highBitSet boolean indicates the value of the high bit of
999 // the constant which would cause it to be modified for this
1000 // operation.
1001 //
1002 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1003 uint64_t Val = Op0C->getRawValue();
1004 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1005 }
1006
1007 if (isValid) {
1008 Constant *NewRHS =
1009 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1010
1011 Instruction *NewShift =
1012 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1013 Op0BO->getName());
1014 Op0BO->setName("");
1015 InsertNewInstBefore(NewShift, I);
1016
1017 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1018 NewRHS);
1019 }
1020 }
1021
Chris Lattner3204d4e2003-07-24 17:52:58 +00001022 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001023 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00001024 if (ConstantUInt *ShiftAmt1C =
1025 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001026 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1027 unsigned ShiftAmt2 = CUI->getValue();
1028
1029 // Check for (A << c1) << c2 and (A >> c1) >> c2
1030 if (I.getOpcode() == Op0SI->getOpcode()) {
1031 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1032 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1033 ConstantUInt::get(Type::UByteTy, Amt));
1034 }
1035
Chris Lattnerab780df2003-07-24 18:38:56 +00001036 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1037 // signed types, we can only support the (A >> c1) << c2 configuration,
1038 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001039 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001040 // Calculate bitmask for what gets shifted off the edge...
1041 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001042 if (isLeftShift)
Chris Lattner3204d4e2003-07-24 17:52:58 +00001043 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001044 else
1045 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00001046
1047 Instruction *Mask =
1048 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1049 C, Op0SI->getOperand(0)->getName()+".mask");
1050 InsertNewInstBefore(Mask, I);
1051
1052 // Figure out what flavor of shift we should use...
1053 if (ShiftAmt1 == ShiftAmt2)
1054 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1055 else if (ShiftAmt1 < ShiftAmt2) {
1056 return new ShiftInst(I.getOpcode(), Mask,
1057 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1058 } else {
1059 return new ShiftInst(Op0SI->getOpcode(), Mask,
1060 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1061 }
1062 }
1063 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001064 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00001065
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001066 return 0;
1067}
1068
1069
Chris Lattner48a44f72002-05-02 17:06:02 +00001070// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1071// instruction.
1072//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001073static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1074 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001075
Chris Lattner650b6da2002-08-02 20:00:25 +00001076 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1077 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +00001078 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +00001079 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00001080 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00001081
1082 // Allow free casting and conversion of sizes as long as the sign doesn't
1083 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001084 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00001085 unsigned SrcSize = SrcTy->getPrimitiveSize();
1086 unsigned MidSize = MidTy->getPrimitiveSize();
1087 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +00001088
Chris Lattner3732aca2002-08-15 16:15:25 +00001089 // Cases where we are monotonically decreasing the size of the type are
1090 // always ok, regardless of what sign changes are going on.
1091 //
Chris Lattner0bb75912002-08-14 23:21:10 +00001092 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +00001093 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +00001094
Chris Lattner555518c2002-09-23 23:39:43 +00001095 // Cases where the source and destination type are the same, but the middle
1096 // type is bigger are noops.
1097 //
1098 if (SrcSize == DstSize && MidSize > SrcSize)
1099 return true;
1100
Chris Lattner3732aca2002-08-15 16:15:25 +00001101 // If we are monotonically growing, things are more complex.
1102 //
1103 if (SrcSize <= MidSize && MidSize <= DstSize) {
1104 // We have eight combinations of signedness to worry about. Here's the
1105 // table:
1106 static const int SignTable[8] = {
1107 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1108 1, // U U U Always ok
1109 1, // U U S Always ok
1110 3, // U S U Ok iff SrcSize != MidSize
1111 3, // U S S Ok iff SrcSize != MidSize
1112 0, // S U U Never ok
1113 2, // S U S Ok iff MidSize == DstSize
1114 1, // S S U Always ok
1115 1, // S S S Always ok
1116 };
1117
1118 // Choose an action based on the current entry of the signtable that this
1119 // cast of cast refers to...
1120 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1121 switch (SignTable[Row]) {
1122 case 0: return false; // Never ok
1123 case 1: return true; // Always ok
1124 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1125 case 3: // Ok iff SrcSize != MidSize
1126 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1127 default: assert(0 && "Bad entry in sign table!");
1128 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001129 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001130 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001131
1132 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1133 // like: short -> ushort -> uint, because this can create wrong results if
1134 // the input short is negative!
1135 //
1136 return false;
1137}
1138
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001139static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1140 if (V->getType() == Ty || isa<Constant>(V)) return false;
1141 if (const CastInst *CI = dyn_cast<CastInst>(V))
1142 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1143 return false;
1144 return true;
1145}
1146
1147/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1148/// InsertBefore instruction. This is specialized a bit to avoid inserting
1149/// casts that are known to not do anything...
1150///
1151Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1152 Instruction *InsertBefore) {
1153 if (V->getType() == DestTy) return V;
1154 if (Constant *C = dyn_cast<Constant>(V))
1155 return ConstantExpr::getCast(C, DestTy);
1156
1157 CastInst *CI = new CastInst(V, DestTy, V->getName());
1158 InsertNewInstBefore(CI, *InsertBefore);
1159 return CI;
1160}
Chris Lattner48a44f72002-05-02 17:06:02 +00001161
1162// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00001163//
Chris Lattner113f4f42002-06-25 16:13:24 +00001164Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00001165 Value *Src = CI.getOperand(0);
1166
Chris Lattner48a44f72002-05-02 17:06:02 +00001167 // If the user is casting a value to the same type, eliminate this cast
1168 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00001169 if (CI.getType() == Src->getType())
1170 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00001171
Chris Lattner48a44f72002-05-02 17:06:02 +00001172 // If casting the result of another cast instruction, try to eliminate this
1173 // one!
1174 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001175 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001176 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1177 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001178 // This instruction now refers directly to the cast's src operand. This
1179 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00001180 CI.setOperand(0, CSrc->getOperand(0));
1181 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00001182 }
1183
Chris Lattner650b6da2002-08-02 20:00:25 +00001184 // If this is an A->B->A cast, and we are dealing with integral types, try
1185 // to convert this into a logical 'and' instruction.
1186 //
1187 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001188 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00001189 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1190 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1191 assert(CSrc->getType() != Type::ULongTy &&
1192 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00001193 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00001194 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1195 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1196 AndOp);
1197 }
1198 }
1199
Chris Lattnerd0d51602003-06-21 23:12:02 +00001200 // If casting the result of a getelementptr instruction with no offset, turn
1201 // this into a cast of the original pointer!
1202 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001203 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00001204 bool AllZeroOperands = true;
1205 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1206 if (!isa<Constant>(GEP->getOperand(i)) ||
1207 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1208 AllZeroOperands = false;
1209 break;
1210 }
1211 if (AllZeroOperands) {
1212 CI.setOperand(0, GEP->getOperand(0));
1213 return &CI;
1214 }
1215 }
1216
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001217 // If the source value is an instruction with only this use, we can attempt to
1218 // propagate the cast into the instruction. Also, only handle integral types
1219 // for now.
1220 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1221 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1222 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1223 const Type *DestTy = CI.getType();
1224 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1225 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1226
1227 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1228 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1229
1230 switch (SrcI->getOpcode()) {
1231 case Instruction::Add:
1232 case Instruction::Mul:
1233 case Instruction::And:
1234 case Instruction::Or:
1235 case Instruction::Xor:
1236 // If we are discarding information, or just changing the sign, rewrite.
1237 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1238 // Don't insert two casts if they cannot be eliminated. We allow two
1239 // casts to be inserted if the sizes are the same. This could only be
1240 // converting signedness, which is a noop.
1241 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1242 !ValueRequiresCast(Op0, DestTy)) {
1243 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1244 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1245 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1246 ->getOpcode(), Op0c, Op1c);
1247 }
1248 }
1249 break;
1250 case Instruction::Shl:
1251 // Allow changing the sign of the source operand. Do not allow changing
1252 // the size of the shift, UNLESS the shift amount is a constant. We
1253 // mush not change variable sized shifts to a smaller size, because it
1254 // is undefined to shift more bits out than exist in the value.
1255 if (DestBitSize == SrcBitSize ||
1256 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1257 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1258 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1259 }
1260 break;
1261 }
1262 }
1263
Chris Lattner260ab202002-04-18 17:39:14 +00001264 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00001265}
1266
Chris Lattner970c33a2003-06-19 17:00:31 +00001267// CallInst simplification
1268//
1269Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1270 if (transformConstExprCastCall(&CI)) return 0;
1271 return 0;
1272}
1273
1274// InvokeInst simplification
1275//
1276Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1277 if (transformConstExprCastCall(&II)) return 0;
1278 return 0;
1279}
1280
1281// getPromotedType - Return the specified type promoted as it would be to pass
1282// though a va_arg area...
1283static const Type *getPromotedType(const Type *Ty) {
1284 switch (Ty->getPrimitiveID()) {
1285 case Type::SByteTyID:
1286 case Type::ShortTyID: return Type::IntTy;
1287 case Type::UByteTyID:
1288 case Type::UShortTyID: return Type::UIntTy;
1289 case Type::FloatTyID: return Type::DoubleTy;
1290 default: return Ty;
1291 }
1292}
1293
1294// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1295// attempt to move the cast to the arguments of the call/invoke.
1296//
1297bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1298 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1299 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1300 if (CE->getOpcode() != Instruction::Cast ||
1301 !isa<ConstantPointerRef>(CE->getOperand(0)))
1302 return false;
1303 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1304 if (!isa<Function>(CPR->getValue())) return false;
1305 Function *Callee = cast<Function>(CPR->getValue());
1306 Instruction *Caller = CS.getInstruction();
1307
1308 // Okay, this is a cast from a function to a different type. Unless doing so
1309 // would cause a type conversion of one of our arguments, change this call to
1310 // be a direct call with arguments casted to the appropriate types.
1311 //
1312 const FunctionType *FT = Callee->getFunctionType();
1313 const Type *OldRetTy = Caller->getType();
1314
1315 if (Callee->isExternal() &&
1316 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1317 return false; // Cannot transform this return value...
1318
1319 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1320 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1321
1322 CallSite::arg_iterator AI = CS.arg_begin();
1323 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1324 const Type *ParamTy = FT->getParamType(i);
1325 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1326 if (Callee->isExternal() && !isConvertible) return false;
1327 }
1328
1329 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1330 Callee->isExternal())
1331 return false; // Do not delete arguments unless we have a function body...
1332
1333 // Okay, we decided that this is a safe thing to do: go ahead and start
1334 // inserting cast instructions as necessary...
1335 std::vector<Value*> Args;
1336 Args.reserve(NumActualArgs);
1337
1338 AI = CS.arg_begin();
1339 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1340 const Type *ParamTy = FT->getParamType(i);
1341 if ((*AI)->getType() == ParamTy) {
1342 Args.push_back(*AI);
1343 } else {
1344 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1345 InsertNewInstBefore(Cast, *Caller);
1346 Args.push_back(Cast);
1347 }
1348 }
1349
1350 // If the function takes more arguments than the call was taking, add them
1351 // now...
1352 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1353 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1354
1355 // If we are removing arguments to the function, emit an obnoxious warning...
1356 if (FT->getNumParams() < NumActualArgs)
1357 if (!FT->isVarArg()) {
1358 std::cerr << "WARNING: While resolving call to function '"
1359 << Callee->getName() << "' arguments were dropped!\n";
1360 } else {
1361 // Add all of the arguments in their promoted form to the arg list...
1362 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1363 const Type *PTy = getPromotedType((*AI)->getType());
1364 if (PTy != (*AI)->getType()) {
1365 // Must promote to pass through va_arg area!
1366 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1367 InsertNewInstBefore(Cast, *Caller);
1368 Args.push_back(Cast);
1369 } else {
1370 Args.push_back(*AI);
1371 }
1372 }
1373 }
1374
1375 if (FT->getReturnType() == Type::VoidTy)
1376 Caller->setName(""); // Void type should not have a name...
1377
1378 Instruction *NC;
1379 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1380 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1381 Args, Caller->getName(), Caller);
1382 } else {
1383 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1384 }
1385
1386 // Insert a cast of the return type as necessary...
1387 Value *NV = NC;
1388 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1389 if (NV->getType() != Type::VoidTy) {
1390 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1391 InsertNewInstBefore(NC, *Caller);
1392 AddUsesToWorkList(*Caller);
1393 } else {
1394 NV = Constant::getNullValue(Caller->getType());
1395 }
1396 }
1397
1398 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1399 Caller->replaceAllUsesWith(NV);
1400 Caller->getParent()->getInstList().erase(Caller);
1401 removeFromWorkList(Caller);
1402 return true;
1403}
1404
1405
Chris Lattner48a44f72002-05-02 17:06:02 +00001406
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001407// PHINode simplification
1408//
Chris Lattner113f4f42002-06-25 16:13:24 +00001409Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001410 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +00001411 if (PN.getNumIncomingValues() == 1)
1412 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +00001413
1414 // Otherwise if all of the incoming values are the same for the PHI, replace
1415 // the PHI node with the incoming value.
1416 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +00001417 Value *InVal = 0;
1418 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1419 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1420 if (InVal && PN.getIncomingValue(i) != InVal)
1421 return 0; // Not the same, bail out.
1422 else
1423 InVal = PN.getIncomingValue(i);
1424
1425 // The only case that could cause InVal to be null is if we have a PHI node
1426 // that only has entries for itself. In this case, there is no entry into the
1427 // loop, so kill the PHI.
1428 //
1429 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001430
Chris Lattner9cd1e662002-08-20 15:35:35 +00001431 // All of the incoming values are the same, replace the PHI node now.
1432 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001433}
1434
Chris Lattner48a44f72002-05-02 17:06:02 +00001435
Chris Lattner113f4f42002-06-25 16:13:24 +00001436Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +00001437 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00001438 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001439 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +00001440 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001441 GEP.getNumOperands() == 1)
1442 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +00001443
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001444 // Combine Indices - If the source pointer to this getelementptr instruction
1445 // is a getelementptr instruction, combine the indices of the two
1446 // getelementptr instructions into a single instruction.
1447 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001448 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001449 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +00001450
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001451 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +00001452 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1453 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +00001454 // Replace: gep (gep %P, long C1), long C2, ...
1455 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +00001456 Value *Sum = ConstantExpr::get(Instruction::Add,
1457 cast<Constant>(Src->getOperand(1)),
1458 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +00001459 assert(Sum && "Constant folding of longs failed!?");
1460 GEP.setOperand(0, Src->getOperand(0));
1461 GEP.setOperand(1, Sum);
1462 AddUsesToWorkList(*Src); // Reduce use count of Src
1463 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +00001464 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +00001465 // Replace: gep (gep %P, long B), long A, ...
1466 // With: T = long A+B; gep %P, T, ...
1467 //
1468 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1469 GEP.getOperand(1),
1470 Src->getName()+".sum", &GEP);
1471 GEP.setOperand(0, Src->getOperand(0));
1472 GEP.setOperand(1, Sum);
1473 WorkList.push_back(cast<Instruction>(Sum));
1474 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00001475 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00001476 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001477 // Otherwise we can do the fold if the first index of the GEP is a zero
1478 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1479 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00001480 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1481 Constant::getNullValue(Type::LongTy)) {
1482 // If the src gep ends with a constant array index, merge this get into
1483 // it, even if we have a non-zero array index.
1484 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1485 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001486 }
1487
1488 if (!Indices.empty())
1489 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001490
1491 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1492 // GEP of global variable. If all of the indices for this GEP are
1493 // constants, we can promote this to a constexpr instead of an instruction.
1494
1495 // Scan for nonconstants...
1496 std::vector<Constant*> Indices;
1497 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1498 for (; I != E && isa<Constant>(*I); ++I)
1499 Indices.push_back(cast<Constant>(*I));
1500
1501 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001502 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001503 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1504
1505 // Replace all uses of the GEP with the new constexpr...
1506 return ReplaceInstUsesWith(GEP, CE);
1507 }
Chris Lattnerca081252001-12-14 16:52:21 +00001508 }
1509
Chris Lattnerca081252001-12-14 16:52:21 +00001510 return 0;
1511}
1512
Chris Lattner1085bdf2002-11-04 16:18:53 +00001513Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1514 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1515 if (AI.isArrayAllocation()) // Check C != 1
1516 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1517 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001518 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001519
1520 // Create and insert the replacement instruction...
1521 if (isa<MallocInst>(AI))
1522 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001523 else {
1524 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001525 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001526 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001527
1528 // Scan to the end of the allocation instructions, to skip over a block of
1529 // allocas if possible...
1530 //
1531 BasicBlock::iterator It = New;
1532 while (isa<AllocationInst>(*It)) ++It;
1533
1534 // Now that I is pointing to the first non-allocation-inst in the block,
1535 // insert our getelementptr instruction...
1536 //
1537 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1538 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1539
1540 // Now make everything use the getelementptr instead of the original
1541 // allocation.
1542 ReplaceInstUsesWith(AI, V);
1543 return &AI;
1544 }
1545 return 0;
1546}
1547
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001548/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1549/// constantexpr, return the constant value being addressed by the constant
1550/// expression, or null if something is funny.
1551///
1552static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1553 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1554 return 0; // Do not allow stepping over the value!
1555
1556 // Loop over all of the operands, tracking down which value we are
1557 // addressing...
1558 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1559 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1560 ConstantStruct *CS = cast<ConstantStruct>(C);
1561 if (CU->getValue() >= CS->getValues().size()) return 0;
1562 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1563 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1564 ConstantArray *CA = cast<ConstantArray>(C);
1565 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1566 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1567 } else
1568 return 0;
1569 return C;
1570}
1571
1572Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1573 Value *Op = LI.getOperand(0);
1574 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1575 Op = CPR->getValue();
1576
1577 // Instcombine load (constant global) into the value loaded...
1578 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001579 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001580 return ReplaceInstUsesWith(LI, GV->getInitializer());
1581
1582 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1583 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1584 if (CE->getOpcode() == Instruction::GetElementPtr)
1585 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1586 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001587 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001588 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1589 return ReplaceInstUsesWith(LI, V);
1590 return 0;
1591}
1592
1593
Chris Lattner9eef8a72003-06-04 04:46:00 +00001594Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1595 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner45789ac2003-06-05 20:12:51 +00001596 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
Chris Lattnere967b342003-06-04 05:10:11 +00001597 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1598 BasicBlock *TrueDest = BI.getSuccessor(0);
1599 BasicBlock *FalseDest = BI.getSuccessor(1);
1600 // Swap Destinations and condition...
1601 BI.setCondition(V);
1602 BI.setSuccessor(0, FalseDest);
1603 BI.setSuccessor(1, TrueDest);
1604 return &BI;
1605 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00001606 return 0;
1607}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001608
Chris Lattnerca081252001-12-14 16:52:21 +00001609
Chris Lattner99f48c62002-09-02 04:59:56 +00001610void InstCombiner::removeFromWorkList(Instruction *I) {
1611 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1612 WorkList.end());
1613}
1614
Chris Lattner113f4f42002-06-25 16:13:24 +00001615bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001616 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001617
Chris Lattner260ab202002-04-18 17:39:14 +00001618 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001619
1620 while (!WorkList.empty()) {
1621 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1622 WorkList.pop_back();
1623
Misha Brukman632df282002-10-29 23:06:16 +00001624 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001625 // Check to see if we can DIE the instruction...
1626 if (isInstructionTriviallyDead(I)) {
1627 // Add operands to the worklist...
1628 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1629 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1630 WorkList.push_back(Op);
1631
1632 ++NumDeadInst;
1633 BasicBlock::iterator BBI = I;
1634 if (dceInstruction(BBI)) {
1635 removeFromWorkList(I);
1636 continue;
1637 }
1638 }
1639
Misha Brukman632df282002-10-29 23:06:16 +00001640 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001641 if (Constant *C = ConstantFoldInstruction(I)) {
1642 // Add operands to the worklist...
1643 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1644 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1645 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001646 ReplaceInstUsesWith(*I, C);
1647
Chris Lattner99f48c62002-09-02 04:59:56 +00001648 ++NumConstProp;
1649 BasicBlock::iterator BBI = I;
1650 if (dceInstruction(BBI)) {
1651 removeFromWorkList(I);
1652 continue;
1653 }
1654 }
1655
Chris Lattnerca081252001-12-14 16:52:21 +00001656 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001657 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001658 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001659 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001660 if (Result != I) {
1661 // Instructions can end up on the worklist more than once. Make sure
1662 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001663 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001664 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001665 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001666 BasicBlock::iterator II = I;
1667
1668 // If the instruction was modified, it's possible that it is now dead.
1669 // if so, remove it.
1670 if (dceInstruction(II)) {
1671 // Instructions may end up in the worklist more than once. Erase them
1672 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001673 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001674 Result = 0;
1675 }
Chris Lattner053c0932002-05-14 15:24:07 +00001676 }
Chris Lattner260ab202002-04-18 17:39:14 +00001677
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001678 if (Result) {
1679 WorkList.push_back(Result);
1680 AddUsesToWorkList(*Result);
1681 }
Chris Lattner260ab202002-04-18 17:39:14 +00001682 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001683 }
1684 }
1685
Chris Lattner260ab202002-04-18 17:39:14 +00001686 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001687}
1688
1689Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001690 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001691}