blob: a095f0886c8b039036813b57c14269368caeefd0 [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 Lattnerb8b97502003-08-13 19:01:45 +0000270
271/// AssociativeOpt - Perform an optimization on an associative operator. This
272/// function is designed to check a chain of associative operators for a
273/// potential to apply a certain optimization. Since the optimization may be
274/// applicable if the expression was reassociated, this checks the chain, then
275/// reassociates the expression as necessary to expose the optimization
276/// opportunity. This makes use of a special Functor, which must define
277/// 'shouldApply' and 'apply' methods.
278///
279template<typename Functor>
280Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
281 unsigned Opcode = Root.getOpcode();
282 Value *LHS = Root.getOperand(0);
283
284 // Quick check, see if the immediate LHS matches...
285 if (F.shouldApply(LHS))
286 return F.apply(Root);
287
288 // Otherwise, if the LHS is not of the same opcode as the root, return.
289 Instruction *LHSI = dyn_cast<Instruction>(LHS);
290 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->use_size() == 1) {
291 // Should we apply this transform to the RHS?
292 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
293
294 // If not to the RHS, check to see if we should apply to the LHS...
295 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
296 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
297 ShouldApply = true;
298 }
299
300 // If the functor wants to apply the optimization to the RHS of LHSI,
301 // reassociate the expression from ((? op A) op B) to (? op (A op B))
302 if (ShouldApply) {
303 BasicBlock *BB = Root.getParent();
304 // All of the instructions have a single use and have no side-effects,
305 // because of this, we can pull them all into the current basic block.
306 if (LHSI->getParent() != BB) {
307 // Move all of the instructions from root to LHSI into the current
308 // block.
309 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
310 Instruction *LastUse = &Root;
311 while (TmpLHSI->getParent() == BB) {
312 LastUse = TmpLHSI;
313 TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
314 }
315
316 // Loop over all of the instructions in other blocks, moving them into
317 // the current one.
318 Value *TmpLHS = TmpLHSI;
319 do {
320 TmpLHSI = cast<Instruction>(TmpLHS);
321 // Remove from current block...
322 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
323 // Insert before the last instruction...
324 BB->getInstList().insert(LastUse, TmpLHSI);
325 TmpLHS = TmpLHSI->getOperand(0);
326 } while (TmpLHSI != LHSI);
327 }
328
329 // Now all of the instructions are in the current basic block, go ahead
330 // and perform the reassociation.
331 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
332
333 // First move the selected RHS to the LHS of the root...
334 Root.setOperand(0, LHSI->getOperand(1));
335
336 // Make what used to be the LHS of the root be the user of the root...
337 Value *ExtraOperand = TmpLHSI->getOperand(1);
338 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
339 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
340 BB->getInstList().remove(&Root); // Remove root from the BB
341 BB->getInstList().insert(TmpLHSI, &Root); // Insert root before TmpLHSI
342
343 // Now propagate the ExtraOperand down the chain of instructions until we
344 // get to LHSI.
345 while (TmpLHSI != LHSI) {
346 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
347 Value *NextOp = NextLHSI->getOperand(1);
348 NextLHSI->setOperand(1, ExtraOperand);
349 TmpLHSI = NextLHSI;
350 ExtraOperand = NextOp;
351 }
352
353 // Now that the instructions are reassociated, have the functor perform
354 // the transformation...
355 return F.apply(Root);
356 }
357
358 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
359 }
360 return 0;
361}
362
363
364// AddRHS - Implements: X + X --> X << 1
365struct AddRHS {
366 Value *RHS;
367 AddRHS(Value *rhs) : RHS(rhs) {}
368 bool shouldApply(Value *LHS) const { return LHS == RHS; }
369 Instruction *apply(BinaryOperator &Add) const {
370 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
371 ConstantInt::get(Type::UByteTy, 1));
372 }
373};
374
375// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
376// iff C1&C2 == 0
377struct AddMaskingAnd {
378 Constant *C2;
379 AddMaskingAnd(Constant *c) : C2(c) {}
380 bool shouldApply(Value *LHS) const {
381 if (Constant *C1 = dyn_castMaskingAnd(LHS))
382 return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
383 return false;
384 }
385 Instruction *apply(BinaryOperator &Add) const {
386 return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
387 Add.getOperand(1));
388 }
389};
390
391
392
Chris Lattner113f4f42002-06-25 16:13:24 +0000393Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000394 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000395 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000396
Chris Lattnerb8b97502003-08-13 19:01:45 +0000397 // X + 0 --> X
Chris Lattnere6794492002-08-12 21:17:25 +0000398 if (RHS == Constant::getNullValue(I.getType()))
399 return ReplaceInstUsesWith(I, LHS);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000400
Chris Lattnerb8b97502003-08-13 19:01:45 +0000401 // X + X --> X << 1
402 if (I.getType()->isInteger())
403 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattnerede3fe02003-08-13 04:18:28 +0000404
Chris Lattner147e9752002-05-08 22:46:53 +0000405 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000406 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner147e9752002-05-08 22:46:53 +0000407 return BinaryOperator::create(Instruction::Sub, RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000408
409 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000410 if (!isa<Constant>(RHS))
411 if (Value *V = dyn_castNegVal(RHS))
412 return BinaryOperator::create(Instruction::Sub, LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000413
Chris Lattner57c8d992003-02-18 19:57:07 +0000414 // X*C + X --> X * (C+1)
415 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000416 Constant *CP1 =
417 ConstantExpr::get(Instruction::Add,
418 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
419 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000420 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
421 }
422
423 // X + X*C --> X * (C+1)
424 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000425 Constant *CP1 =
426 ConstantExpr::get(Instruction::Add,
427 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
428 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000429 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
430 }
431
Chris Lattnerb8b97502003-08-13 19:01:45 +0000432 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
433 if (Constant *C2 = dyn_castMaskingAnd(RHS))
434 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000435
Chris Lattner113f4f42002-06-25 16:13:24 +0000436 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000437}
438
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000439// isSignBit - Return true if the value represented by the constant only has the
440// highest order bit set.
441static bool isSignBit(ConstantInt *CI) {
442 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
443 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
444}
445
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000446static unsigned getTypeSizeInBits(const Type *Ty) {
447 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
448}
449
Chris Lattner113f4f42002-06-25 16:13:24 +0000450Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000451 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000452
Chris Lattnere6794492002-08-12 21:17:25 +0000453 if (Op0 == Op1) // sub X, X -> 0
454 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000455
Chris Lattnere6794492002-08-12 21:17:25 +0000456 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000457 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner147e9752002-05-08 22:46:53 +0000458 return BinaryOperator::create(Instruction::Add, Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000459
Chris Lattner3082c5a2003-02-18 19:28:33 +0000460 // Replace (-1 - A) with (~A)...
461 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
462 if (C->isAllOnesValue())
463 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000464
Chris Lattner3082c5a2003-02-18 19:28:33 +0000465 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
466 if (Op1I->use_size() == 1) {
467 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
468 // is not used by anyone else...
469 //
470 if (Op1I->getOpcode() == Instruction::Sub) {
471 // Swap the two operands of the subexpr...
472 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
473 Op1I->setOperand(0, IIOp1);
474 Op1I->setOperand(1, IIOp0);
475
476 // Create the new top level add instruction...
477 return BinaryOperator::create(Instruction::Add, Op0, Op1);
478 }
479
480 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
481 //
482 if (Op1I->getOpcode() == Instruction::And &&
483 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
484 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
485
486 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
487 return BinaryOperator::create(Instruction::And, Op0, NewNot);
488 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000489
490 // X - X*C --> X * (1-C)
491 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000492 Constant *CP1 =
493 ConstantExpr::get(Instruction::Sub,
494 ConstantInt::get(I.getType(), 1),
495 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000496 assert(CP1 && "Couldn't constant fold 1-C?");
497 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
498 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000499 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000500
Chris Lattner57c8d992003-02-18 19:57:07 +0000501 // X*C - X --> X * (C-1)
502 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000503 Constant *CP1 =
504 ConstantExpr::get(Instruction::Sub,
505 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
506 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000507 assert(CP1 && "Couldn't constant fold C - 1?");
508 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
509 }
510
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000511 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000512}
513
Chris Lattner113f4f42002-06-25 16:13:24 +0000514Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000515 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000516 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000517
Chris Lattnere6794492002-08-12 21:17:25 +0000518 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000519 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
520 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000521
522 // ((X << C1)*C2) == (X * (C2 << C1))
523 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
524 if (SI->getOpcode() == Instruction::Shl)
525 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
526 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
527 *CI << *ShOp);
528
Chris Lattner3082c5a2003-02-18 19:28:33 +0000529 const Type *Ty = CI->getType();
Chris Lattner6077c312003-07-23 15:22:26 +0000530 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000531 switch (Val) {
Chris Lattner35236d82003-06-25 17:09:20 +0000532 case -1: // X * -1 -> -X
533 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner3082c5a2003-02-18 19:28:33 +0000534 case 0:
535 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
536 case 1:
537 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
Chris Lattner3082c5a2003-02-18 19:28:33 +0000538 }
Chris Lattner31ba1292002-04-29 22:24:47 +0000539
Chris Lattner3082c5a2003-02-18 19:28:33 +0000540 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
541 return new ShiftInst(Instruction::Shl, Op0,
542 ConstantUInt::get(Type::UByteTy, C));
543 } else {
544 ConstantFP *Op1F = cast<ConstantFP>(Op1);
545 if (Op1F->isNullValue())
546 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000547
Chris Lattner3082c5a2003-02-18 19:28:33 +0000548 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
549 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
550 if (Op1F->getValue() == 1.0)
551 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
552 }
Chris Lattner260ab202002-04-18 17:39:14 +0000553 }
554
Chris Lattner934a64cf2003-03-10 23:23:04 +0000555 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
556 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
557 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
558
Chris Lattner113f4f42002-06-25 16:13:24 +0000559 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000560}
561
Chris Lattner113f4f42002-06-25 16:13:24 +0000562Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000563 // div X, 1 == X
Chris Lattner3082c5a2003-02-18 19:28:33 +0000564 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere6794492002-08-12 21:17:25 +0000565 if (RHS->equalsInt(1))
566 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000567
568 // Check to see if this is an unsigned division with an exact power of 2,
569 // if so, convert to a right shift.
570 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
571 if (uint64_t Val = C->getValue()) // Don't break X / 0
572 if (uint64_t C = Log2(Val))
573 return new ShiftInst(Instruction::Shr, I.getOperand(0),
574 ConstantUInt::get(Type::UByteTy, C));
575 }
576
577 // 0 / X == 0, we don't need to preserve faults!
578 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
579 if (LHS->equalsInt(0))
580 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
581
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000582 return 0;
583}
584
585
Chris Lattner113f4f42002-06-25 16:13:24 +0000586Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000587 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
588 if (RHS->equalsInt(1)) // X % 1 == 0
589 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
590
591 // Check to see if this is an unsigned remainder with an exact power of 2,
592 // if so, convert to a bitwise and.
593 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
594 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
595 if (Log2(Val))
596 return BinaryOperator::create(Instruction::And, I.getOperand(0),
597 ConstantUInt::get(I.getType(), Val-1));
598 }
599
600 // 0 % X == 0, we don't need to preserve faults!
601 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
602 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000603 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
604
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000605 return 0;
606}
607
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000608// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000609static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000610 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
611 // Calculate -1 casted to the right type...
612 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
613 uint64_t Val = ~0ULL; // All ones
614 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
615 return CU->getValue() == Val-1;
616 }
617
618 const ConstantSInt *CS = cast<ConstantSInt>(C);
619
620 // Calculate 0111111111..11111
621 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
622 int64_t Val = INT64_MAX; // All ones
623 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
624 return CS->getValue() == Val-1;
625}
626
627// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000628static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000629 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
630 return CU->getValue() == 1;
631
632 const ConstantSInt *CS = cast<ConstantSInt>(C);
633
634 // Calculate 1111111111000000000000
635 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
636 int64_t Val = -1; // All ones
637 Val <<= TypeBits-1; // Shift over to the right spot
638 return CS->getValue() == Val+1;
639}
640
641
Chris Lattner113f4f42002-06-25 16:13:24 +0000642Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000643 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000645
646 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +0000647 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
648 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000649
650 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +0000651 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000652 if (RHS->isAllOnesValue())
653 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000654
Chris Lattner33217db2003-07-23 19:36:21 +0000655 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
656 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +0000657 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
658 if (Op0I->getOpcode() == Instruction::Xor) {
Chris Lattner33217db2003-07-23 19:36:21 +0000659 if ((*RHS & *Op0CI)->isNullValue()) {
660 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
661 return BinaryOperator::create(Instruction::And, X, RHS);
662 } else if (isOnlyUse(Op0)) {
Chris Lattner16464b32003-07-23 19:25:52 +0000663 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
664 std::string Op0Name = Op0I->getName(); Op0I->setName("");
665 Instruction *And = BinaryOperator::create(Instruction::And,
Chris Lattner33217db2003-07-23 19:36:21 +0000666 X, RHS, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000667 InsertNewInstBefore(And, I);
668 return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
669 }
670 } else if (Op0I->getOpcode() == Instruction::Or) {
671 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
672 if ((*RHS & *Op0CI)->isNullValue())
Chris Lattner33217db2003-07-23 19:36:21 +0000673 return BinaryOperator::create(Instruction::And, X, RHS);
Chris Lattner16464b32003-07-23 19:25:52 +0000674
675 Constant *Together = *RHS & *Op0CI;
676 if (Together == RHS) // (X | C) & C --> C
677 return ReplaceInstUsesWith(I, RHS);
678
679 if (isOnlyUse(Op0)) {
680 if (Together != Op0CI) {
681 // (X | C1) & C2 --> (X | (C1&C2)) & C2
682 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattner33217db2003-07-23 19:36:21 +0000683 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
684 Together, Op0Name);
Chris Lattner16464b32003-07-23 19:25:52 +0000685 InsertNewInstBefore(Or, I);
686 return BinaryOperator::create(Instruction::And, Or, RHS);
687 }
688 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000689 }
Chris Lattner33217db2003-07-23 19:36:21 +0000690 }
Chris Lattner49b47ae2003-07-23 17:57:01 +0000691 }
692
Chris Lattnerbb74e222003-03-10 23:06:50 +0000693 Value *Op0NotVal = dyn_castNotVal(Op0);
694 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000695
696 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +0000697 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000698 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
Chris Lattner49b47ae2003-07-23 17:57:01 +0000699 Op1NotVal,I.getName()+".demorgan");
700 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000701 return BinaryOperator::createNot(Or);
702 }
703
704 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
705 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner65217ff2002-08-23 18:32:43 +0000706
Chris Lattner113f4f42002-06-25 16:13:24 +0000707 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000708}
709
710
711
Chris Lattner113f4f42002-06-25 16:13:24 +0000712Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000713 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000715
716 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000717 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
718 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000719
720 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +0000721 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +0000722 if (RHS->isAllOnesValue())
723 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000724
Chris Lattner8f0d1562003-07-23 18:29:44 +0000725 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
726 // (X & C1) | C2 --> (X | C2) & (C1|C2)
727 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
728 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
729 std::string Op0Name = Op0I->getName(); Op0I->setName("");
730 Instruction *Or = BinaryOperator::create(Instruction::Or,
731 Op0I->getOperand(0), RHS,
732 Op0Name);
733 InsertNewInstBefore(Or, I);
734 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
735 }
736
737 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
738 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
739 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
740 std::string Op0Name = Op0I->getName(); Op0I->setName("");
741 Instruction *Or = BinaryOperator::create(Instruction::Or,
742 Op0I->getOperand(0), RHS,
743 Op0Name);
744 InsertNewInstBefore(Or, I);
745 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
746 }
747 }
748 }
749
Chris Lattner812aab72003-08-12 19:11:07 +0000750 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattner01d56392003-08-12 19:17:27 +0000751 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
752 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
753 if (LHS->getOperand(0) == RHS->getOperand(0))
754 if (Constant *C0 = dyn_castMaskingAnd(LHS))
755 if (Constant *C1 = dyn_castMaskingAnd(RHS))
756 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
Chris Lattner812aab72003-08-12 19:11:07 +0000757 *C0 | *C1);
758
Chris Lattner3e327a42003-03-10 23:13:59 +0000759 Value *Op0NotVal = dyn_castNotVal(Op0);
760 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000761
Chris Lattner3e327a42003-03-10 23:13:59 +0000762 if (Op1 == Op0NotVal) // ~A | A == -1
763 return ReplaceInstUsesWith(I,
764 ConstantIntegral::getAllOnesValue(I.getType()));
765
766 if (Op0 == Op1NotVal) // A | ~A == -1
767 return ReplaceInstUsesWith(I,
768 ConstantIntegral::getAllOnesValue(I.getType()));
769
770 // (~A | ~B) == (~(A & B)) - Demorgan's Law
771 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
772 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
773 Op1NotVal,I.getName()+".demorgan",
774 &I);
775 WorkList.push_back(And);
776 return BinaryOperator::createNot(And);
777 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000778
Chris Lattner113f4f42002-06-25 16:13:24 +0000779 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000780}
781
782
783
Chris Lattner113f4f42002-06-25 16:13:24 +0000784Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000785 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000786 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000787
788 // xor X, X = 0
Chris Lattnere6794492002-08-12 21:17:25 +0000789 if (Op0 == Op1)
790 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000791
Chris Lattner97638592003-07-23 21:37:07 +0000792 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000793 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +0000794 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +0000795 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000796
Chris Lattner97638592003-07-23 21:37:07 +0000797 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000798 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +0000799 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
800 if (RHS == ConstantBool::True && SCI->use_size() == 1)
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000801 return new SetCondInst(SCI->getInverseCondition(),
802 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattner97638592003-07-23 21:37:07 +0000803
804 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
805 if (Op0I->getOpcode() == Instruction::And) {
806 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
807 if ((*RHS & *Op0CI)->isNullValue())
808 return BinaryOperator::create(Instruction::Or, Op0, RHS);
809 } else if (Op0I->getOpcode() == Instruction::Or) {
810 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
811 if ((*RHS & *Op0CI) == RHS)
812 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
813 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +0000814 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000815 }
816
Chris Lattnerbb74e222003-03-10 23:06:50 +0000817 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000818 if (X == Op1)
819 return ReplaceInstUsesWith(I,
820 ConstantIntegral::getAllOnesValue(I.getType()));
821
Chris Lattnerbb74e222003-03-10 23:06:50 +0000822 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +0000823 if (X == Op0)
824 return ReplaceInstUsesWith(I,
825 ConstantIntegral::getAllOnesValue(I.getType()));
826
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000827 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
828 if (Op1I->getOpcode() == Instruction::Or)
829 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
830 cast<BinaryOperator>(Op1I)->swapOperands();
831 I.swapOperands();
832 std::swap(Op0, Op1);
833 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
834 I.swapOperands();
835 std::swap(Op0, Op1);
836 }
837
838 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
839 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
840 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
841 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000842 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000843 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
844 WorkList.push_back(cast<Instruction>(NotB));
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000845 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
846 NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +0000847 }
848 }
849
Chris Lattner7fb29e12003-03-11 00:12:48 +0000850 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
851 if (Constant *C1 = dyn_castMaskingAnd(Op0))
852 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner34428442003-05-27 16:40:51 +0000853 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000854 return BinaryOperator::create(Instruction::Or, Op0, Op1);
855
Chris Lattner113f4f42002-06-25 16:13:24 +0000856 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000857}
858
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000859// AddOne, SubOne - Add or subtract a constant one from an integer constant...
860static Constant *AddOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000861 Constant *Result = ConstantExpr::get(Instruction::Add, C,
862 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000863 assert(Result && "Constant folding integer addition failed!");
864 return Result;
865}
866static Constant *SubOne(ConstantInt *C) {
Chris Lattner34428442003-05-27 16:40:51 +0000867 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
868 ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000869 assert(Result && "Constant folding integer addition failed!");
870 return Result;
871}
872
Chris Lattner1fc23f32002-05-09 20:11:54 +0000873// isTrueWhenEqual - Return true if the specified setcondinst instruction is
874// true when both operands are equal...
875//
Chris Lattner113f4f42002-06-25 16:13:24 +0000876static bool isTrueWhenEqual(Instruction &I) {
877 return I.getOpcode() == Instruction::SetEQ ||
878 I.getOpcode() == Instruction::SetGE ||
879 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +0000880}
881
Chris Lattner113f4f42002-06-25 16:13:24 +0000882Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000883 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000884 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
885 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000886
887 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000888 if (Op0 == Op1)
889 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +0000890
Chris Lattnerd07283a2003-08-13 05:38:46 +0000891 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
892 if (isa<ConstantPointerNull>(Op1) &&
893 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000894 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
895
Chris Lattnerd07283a2003-08-13 05:38:46 +0000896
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000897 // setcc's with boolean values can always be turned into bitwise operations
898 if (Ty == Type::BoolTy) {
899 // If this is <, >, or !=, we can change this into a simple xor instruction
900 if (!isTrueWhenEqual(I))
901 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
902
903 // Otherwise we need to make a temporary intermediate instruction and insert
904 // it into the instruction stream. This is what we are after:
905 //
906 // seteq bool %A, %B -> ~(A^B)
907 // setle bool %A, %B -> ~A | B
908 // setge bool %A, %B -> A | ~B
909 //
910 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
911 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
912 I.getName()+"tmp");
913 InsertNewInstBefore(Xor, I);
Chris Lattner31ae8632002-08-14 17:51:49 +0000914 return BinaryOperator::createNot(Xor, I.getName());
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000915 }
916
917 // Handle the setXe cases...
918 assert(I.getOpcode() == Instruction::SetGE ||
919 I.getOpcode() == Instruction::SetLE);
920
921 if (I.getOpcode() == Instruction::SetGE)
922 std::swap(Op0, Op1); // Change setge -> setle
923
924 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +0000925 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000926 InsertNewInstBefore(Not, I);
927 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
928 }
929
930 // Check to see if we are doing one of many comparisons against constant
931 // integers at the end of their ranges...
932 //
933 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000934 // Simplify seteq and setne instructions...
935 if (I.getOpcode() == Instruction::SetEQ ||
936 I.getOpcode() == Instruction::SetNE) {
937 bool isSetNE = I.getOpcode() == Instruction::SetNE;
938
Chris Lattnercfbce7c2003-07-23 17:26:36 +0000939 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000940 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +0000941 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
942 switch (BO->getOpcode()) {
943 case Instruction::Add:
944 if (CI->isNullValue()) {
945 // Replace ((add A, B) != 0) with (A != -B) if A or B is
946 // efficiently invertible, or if the add has just this one use.
947 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
948 if (Value *NegVal = dyn_castNegVal(BOp1))
949 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
950 else if (Value *NegVal = dyn_castNegVal(BOp0))
951 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
952 else if (BO->use_size() == 1) {
953 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
954 BO->setName("");
955 InsertNewInstBefore(Neg, I);
956 return new SetCondInst(I.getOpcode(), BOp0, Neg);
957 }
958 }
959 break;
960 case Instruction::Xor:
961 // For the xor case, we can xor two constants together, eliminating
962 // the explicit xor.
963 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
964 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
965 *CI ^ *BOC);
966
967 // FALLTHROUGH
968 case Instruction::Sub:
969 // Replace (([sub|xor] A, B) != 0) with (A != B)
970 if (CI->isNullValue())
971 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
972 BO->getOperand(1));
973 break;
974
975 case Instruction::Or:
976 // If bits are being or'd in that are not present in the constant we
977 // are comparing against, then the comparison could never succeed!
978 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000979 if (!(*BOC & *~*CI)->isNullValue())
980 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +0000981 break;
982
983 case Instruction::And:
984 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +0000985 // If bits are being compared against that are and'd out, then the
986 // comparison can never succeed!
987 if (!(*CI & *~*BOC)->isNullValue())
988 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +0000989
990 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
991 // to be a signed value as appropriate.
992 if (isSignBit(BOC)) {
993 Value *X = BO->getOperand(0);
994 // If 'X' is not signed, insert a cast now...
995 if (!BOC->getType()->isSigned()) {
996 const Type *DestTy;
997 switch (BOC->getType()->getPrimitiveID()) {
998 case Type::UByteTyID: DestTy = Type::SByteTy; break;
999 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1000 case Type::UIntTyID: DestTy = Type::IntTy; break;
1001 case Type::ULongTyID: DestTy = Type::LongTy; break;
1002 default: assert(0 && "Invalid unsigned integer type!"); abort();
1003 }
1004 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1005 InsertNewInstBefore(NewCI, I);
1006 X = NewCI;
1007 }
1008 return new SetCondInst(isSetNE ? Instruction::SetLT :
1009 Instruction::SetGE, X,
1010 Constant::getNullValue(X->getType()));
1011 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001012 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001013 default: break;
1014 }
1015 }
Chris Lattnere967b342003-06-04 05:10:11 +00001016 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00001017
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001018 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00001019 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001020 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1021 return ReplaceInstUsesWith(I, ConstantBool::False);
1022 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1023 return ReplaceInstUsesWith(I, ConstantBool::True);
1024 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1025 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1026 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1027 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1028
Chris Lattnere6794492002-08-12 21:17:25 +00001029 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001030 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1031 return ReplaceInstUsesWith(I, ConstantBool::False);
1032 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1033 return ReplaceInstUsesWith(I, ConstantBool::True);
1034 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1035 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1036 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1037 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1038
1039 // Comparing against a value really close to min or max?
1040 } else if (isMinValuePlusOne(CI)) {
1041 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1042 return BinaryOperator::create(Instruction::SetEQ, Op0,
1043 SubOne(CI), I.getName());
1044 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1045 return BinaryOperator::create(Instruction::SetNE, Op0,
1046 SubOne(CI), I.getName());
1047
1048 } else if (isMaxValueMinusOne(CI)) {
1049 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1050 return BinaryOperator::create(Instruction::SetEQ, Op0,
1051 AddOne(CI), I.getName());
1052 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1053 return BinaryOperator::create(Instruction::SetNE, Op0,
1054 AddOne(CI), I.getName());
1055 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001056 }
1057
Chris Lattner113f4f42002-06-25 16:13:24 +00001058 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001059}
1060
1061
1062
Chris Lattnere8d6c602003-03-10 19:16:08 +00001063Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001064 assert(I.getOperand(1)->getType() == Type::UByteTy);
1065 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001066 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001067
1068 // shl X, 0 == X and shr X, 0 == X
1069 // shl 0, X == 0 and shr 0, X == 0
1070 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001071 Op0 == Constant::getNullValue(Op0->getType()))
1072 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001073
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001074 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1075 if (!isLeftShift)
1076 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1077 if (CSI->isAllOnesValue())
1078 return ReplaceInstUsesWith(I, CSI);
1079
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001080 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001081 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1082 // of a signed value.
1083 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00001084 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1085 if (CUI->getValue() >= TypeBits &&
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001086 (!Op0->getType()->isSigned() || isLeftShift))
Chris Lattnere8d6c602003-03-10 19:16:08 +00001087 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner55f3d942002-09-10 23:04:09 +00001088
Chris Lattnerede3fe02003-08-13 04:18:28 +00001089 // ((X*C1) << C2) == (X * (C1 << C2))
1090 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1091 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1092 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1093 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1094 *BOOp << *CUI);
1095
1096
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001097 // If the operand is an bitwise operator with a constant RHS, and the
1098 // shift is the only use, we can pull it out of the shift.
1099 if (Op0->use_size() == 1)
1100 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1101 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1102 bool isValid = true; // Valid only for And, Or, Xor
1103 bool highBitSet = false; // Transform if high bit of constant set?
1104
1105 switch (Op0BO->getOpcode()) {
1106 default: isValid = false; break; // Do not perform transform!
1107 case Instruction::Or:
1108 case Instruction::Xor:
1109 highBitSet = false;
1110 break;
1111 case Instruction::And:
1112 highBitSet = true;
1113 break;
1114 }
1115
1116 // If this is a signed shift right, and the high bit is modified
1117 // by the logical operation, do not perform the transformation.
1118 // The highBitSet boolean indicates the value of the high bit of
1119 // the constant which would cause it to be modified for this
1120 // operation.
1121 //
1122 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1123 uint64_t Val = Op0C->getRawValue();
1124 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1125 }
1126
1127 if (isValid) {
1128 Constant *NewRHS =
1129 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1130
1131 Instruction *NewShift =
1132 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1133 Op0BO->getName());
1134 Op0BO->setName("");
1135 InsertNewInstBefore(NewShift, I);
1136
1137 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1138 NewRHS);
1139 }
1140 }
1141
Chris Lattner3204d4e2003-07-24 17:52:58 +00001142 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001143 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00001144 if (ConstantUInt *ShiftAmt1C =
1145 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001146 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1147 unsigned ShiftAmt2 = CUI->getValue();
1148
1149 // Check for (A << c1) << c2 and (A >> c1) >> c2
1150 if (I.getOpcode() == Op0SI->getOpcode()) {
1151 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1152 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1153 ConstantUInt::get(Type::UByteTy, Amt));
1154 }
1155
Chris Lattnerab780df2003-07-24 18:38:56 +00001156 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1157 // signed types, we can only support the (A >> c1) << c2 configuration,
1158 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001159 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001160 // Calculate bitmask for what gets shifted off the edge...
1161 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001162 if (isLeftShift)
Chris Lattner3204d4e2003-07-24 17:52:58 +00001163 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001164 else
1165 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00001166
1167 Instruction *Mask =
1168 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1169 C, Op0SI->getOperand(0)->getName()+".mask");
1170 InsertNewInstBefore(Mask, I);
1171
1172 // Figure out what flavor of shift we should use...
1173 if (ShiftAmt1 == ShiftAmt2)
1174 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1175 else if (ShiftAmt1 < ShiftAmt2) {
1176 return new ShiftInst(I.getOpcode(), Mask,
1177 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1178 } else {
1179 return new ShiftInst(Op0SI->getOpcode(), Mask,
1180 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1181 }
1182 }
1183 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001184 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00001185
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001186 return 0;
1187}
1188
1189
Chris Lattner48a44f72002-05-02 17:06:02 +00001190// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1191// instruction.
1192//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001193static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1194 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001195
Chris Lattner650b6da2002-08-02 20:00:25 +00001196 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1197 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +00001198 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +00001199 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00001200 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00001201
1202 // Allow free casting and conversion of sizes as long as the sign doesn't
1203 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001204 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00001205 unsigned SrcSize = SrcTy->getPrimitiveSize();
1206 unsigned MidSize = MidTy->getPrimitiveSize();
1207 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +00001208
Chris Lattner3732aca2002-08-15 16:15:25 +00001209 // Cases where we are monotonically decreasing the size of the type are
1210 // always ok, regardless of what sign changes are going on.
1211 //
Chris Lattner0bb75912002-08-14 23:21:10 +00001212 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +00001213 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +00001214
Chris Lattner555518c2002-09-23 23:39:43 +00001215 // Cases where the source and destination type are the same, but the middle
1216 // type is bigger are noops.
1217 //
1218 if (SrcSize == DstSize && MidSize > SrcSize)
1219 return true;
1220
Chris Lattner3732aca2002-08-15 16:15:25 +00001221 // If we are monotonically growing, things are more complex.
1222 //
1223 if (SrcSize <= MidSize && MidSize <= DstSize) {
1224 // We have eight combinations of signedness to worry about. Here's the
1225 // table:
1226 static const int SignTable[8] = {
1227 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1228 1, // U U U Always ok
1229 1, // U U S Always ok
1230 3, // U S U Ok iff SrcSize != MidSize
1231 3, // U S S Ok iff SrcSize != MidSize
1232 0, // S U U Never ok
1233 2, // S U S Ok iff MidSize == DstSize
1234 1, // S S U Always ok
1235 1, // S S S Always ok
1236 };
1237
1238 // Choose an action based on the current entry of the signtable that this
1239 // cast of cast refers to...
1240 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1241 switch (SignTable[Row]) {
1242 case 0: return false; // Never ok
1243 case 1: return true; // Always ok
1244 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1245 case 3: // Ok iff SrcSize != MidSize
1246 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1247 default: assert(0 && "Bad entry in sign table!");
1248 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001249 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001250 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001251
1252 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1253 // like: short -> ushort -> uint, because this can create wrong results if
1254 // the input short is negative!
1255 //
1256 return false;
1257}
1258
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001259static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1260 if (V->getType() == Ty || isa<Constant>(V)) return false;
1261 if (const CastInst *CI = dyn_cast<CastInst>(V))
1262 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1263 return false;
1264 return true;
1265}
1266
1267/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1268/// InsertBefore instruction. This is specialized a bit to avoid inserting
1269/// casts that are known to not do anything...
1270///
1271Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1272 Instruction *InsertBefore) {
1273 if (V->getType() == DestTy) return V;
1274 if (Constant *C = dyn_cast<Constant>(V))
1275 return ConstantExpr::getCast(C, DestTy);
1276
1277 CastInst *CI = new CastInst(V, DestTy, V->getName());
1278 InsertNewInstBefore(CI, *InsertBefore);
1279 return CI;
1280}
Chris Lattner48a44f72002-05-02 17:06:02 +00001281
1282// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00001283//
Chris Lattner113f4f42002-06-25 16:13:24 +00001284Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00001285 Value *Src = CI.getOperand(0);
1286
Chris Lattner48a44f72002-05-02 17:06:02 +00001287 // If the user is casting a value to the same type, eliminate this cast
1288 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00001289 if (CI.getType() == Src->getType())
1290 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00001291
Chris Lattner48a44f72002-05-02 17:06:02 +00001292 // If casting the result of another cast instruction, try to eliminate this
1293 // one!
1294 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001295 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001296 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1297 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001298 // This instruction now refers directly to the cast's src operand. This
1299 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00001300 CI.setOperand(0, CSrc->getOperand(0));
1301 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00001302 }
1303
Chris Lattner650b6da2002-08-02 20:00:25 +00001304 // If this is an A->B->A cast, and we are dealing with integral types, try
1305 // to convert this into a logical 'and' instruction.
1306 //
1307 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001308 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00001309 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1310 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1311 assert(CSrc->getType() != Type::ULongTy &&
1312 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00001313 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00001314 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1315 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1316 AndOp);
1317 }
1318 }
1319
Chris Lattnerd0d51602003-06-21 23:12:02 +00001320 // If casting the result of a getelementptr instruction with no offset, turn
1321 // this into a cast of the original pointer!
1322 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00001323 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00001324 bool AllZeroOperands = true;
1325 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1326 if (!isa<Constant>(GEP->getOperand(i)) ||
1327 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1328 AllZeroOperands = false;
1329 break;
1330 }
1331 if (AllZeroOperands) {
1332 CI.setOperand(0, GEP->getOperand(0));
1333 return &CI;
1334 }
1335 }
1336
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001337 // If the source value is an instruction with only this use, we can attempt to
1338 // propagate the cast into the instruction. Also, only handle integral types
1339 // for now.
1340 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1341 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1342 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1343 const Type *DestTy = CI.getType();
1344 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1345 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1346
1347 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1348 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1349
1350 switch (SrcI->getOpcode()) {
1351 case Instruction::Add:
1352 case Instruction::Mul:
1353 case Instruction::And:
1354 case Instruction::Or:
1355 case Instruction::Xor:
1356 // If we are discarding information, or just changing the sign, rewrite.
1357 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1358 // Don't insert two casts if they cannot be eliminated. We allow two
1359 // casts to be inserted if the sizes are the same. This could only be
1360 // converting signedness, which is a noop.
1361 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1362 !ValueRequiresCast(Op0, DestTy)) {
1363 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1364 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1365 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1366 ->getOpcode(), Op0c, Op1c);
1367 }
1368 }
1369 break;
1370 case Instruction::Shl:
1371 // Allow changing the sign of the source operand. Do not allow changing
1372 // the size of the shift, UNLESS the shift amount is a constant. We
1373 // mush not change variable sized shifts to a smaller size, because it
1374 // is undefined to shift more bits out than exist in the value.
1375 if (DestBitSize == SrcBitSize ||
1376 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1377 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1378 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1379 }
1380 break;
1381 }
1382 }
1383
Chris Lattner260ab202002-04-18 17:39:14 +00001384 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00001385}
1386
Chris Lattner970c33a2003-06-19 17:00:31 +00001387// CallInst simplification
1388//
1389Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1390 if (transformConstExprCastCall(&CI)) return 0;
1391 return 0;
1392}
1393
1394// InvokeInst simplification
1395//
1396Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1397 if (transformConstExprCastCall(&II)) return 0;
1398 return 0;
1399}
1400
1401// getPromotedType - Return the specified type promoted as it would be to pass
1402// though a va_arg area...
1403static const Type *getPromotedType(const Type *Ty) {
1404 switch (Ty->getPrimitiveID()) {
1405 case Type::SByteTyID:
1406 case Type::ShortTyID: return Type::IntTy;
1407 case Type::UByteTyID:
1408 case Type::UShortTyID: return Type::UIntTy;
1409 case Type::FloatTyID: return Type::DoubleTy;
1410 default: return Ty;
1411 }
1412}
1413
1414// transformConstExprCastCall - If the callee is a constexpr cast of a function,
1415// attempt to move the cast to the arguments of the call/invoke.
1416//
1417bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1418 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1419 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1420 if (CE->getOpcode() != Instruction::Cast ||
1421 !isa<ConstantPointerRef>(CE->getOperand(0)))
1422 return false;
1423 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1424 if (!isa<Function>(CPR->getValue())) return false;
1425 Function *Callee = cast<Function>(CPR->getValue());
1426 Instruction *Caller = CS.getInstruction();
1427
1428 // Okay, this is a cast from a function to a different type. Unless doing so
1429 // would cause a type conversion of one of our arguments, change this call to
1430 // be a direct call with arguments casted to the appropriate types.
1431 //
1432 const FunctionType *FT = Callee->getFunctionType();
1433 const Type *OldRetTy = Caller->getType();
1434
1435 if (Callee->isExternal() &&
1436 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1437 return false; // Cannot transform this return value...
1438
1439 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1440 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1441
1442 CallSite::arg_iterator AI = CS.arg_begin();
1443 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1444 const Type *ParamTy = FT->getParamType(i);
1445 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1446 if (Callee->isExternal() && !isConvertible) return false;
1447 }
1448
1449 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1450 Callee->isExternal())
1451 return false; // Do not delete arguments unless we have a function body...
1452
1453 // Okay, we decided that this is a safe thing to do: go ahead and start
1454 // inserting cast instructions as necessary...
1455 std::vector<Value*> Args;
1456 Args.reserve(NumActualArgs);
1457
1458 AI = CS.arg_begin();
1459 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1460 const Type *ParamTy = FT->getParamType(i);
1461 if ((*AI)->getType() == ParamTy) {
1462 Args.push_back(*AI);
1463 } else {
1464 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1465 InsertNewInstBefore(Cast, *Caller);
1466 Args.push_back(Cast);
1467 }
1468 }
1469
1470 // If the function takes more arguments than the call was taking, add them
1471 // now...
1472 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1473 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1474
1475 // If we are removing arguments to the function, emit an obnoxious warning...
1476 if (FT->getNumParams() < NumActualArgs)
1477 if (!FT->isVarArg()) {
1478 std::cerr << "WARNING: While resolving call to function '"
1479 << Callee->getName() << "' arguments were dropped!\n";
1480 } else {
1481 // Add all of the arguments in their promoted form to the arg list...
1482 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1483 const Type *PTy = getPromotedType((*AI)->getType());
1484 if (PTy != (*AI)->getType()) {
1485 // Must promote to pass through va_arg area!
1486 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1487 InsertNewInstBefore(Cast, *Caller);
1488 Args.push_back(Cast);
1489 } else {
1490 Args.push_back(*AI);
1491 }
1492 }
1493 }
1494
1495 if (FT->getReturnType() == Type::VoidTy)
1496 Caller->setName(""); // Void type should not have a name...
1497
1498 Instruction *NC;
1499 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1500 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1501 Args, Caller->getName(), Caller);
1502 } else {
1503 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1504 }
1505
1506 // Insert a cast of the return type as necessary...
1507 Value *NV = NC;
1508 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1509 if (NV->getType() != Type::VoidTy) {
1510 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1511 InsertNewInstBefore(NC, *Caller);
1512 AddUsesToWorkList(*Caller);
1513 } else {
1514 NV = Constant::getNullValue(Caller->getType());
1515 }
1516 }
1517
1518 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1519 Caller->replaceAllUsesWith(NV);
1520 Caller->getParent()->getInstList().erase(Caller);
1521 removeFromWorkList(Caller);
1522 return true;
1523}
1524
1525
Chris Lattner48a44f72002-05-02 17:06:02 +00001526
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001527// PHINode simplification
1528//
Chris Lattner113f4f42002-06-25 16:13:24 +00001529Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001530 // If the PHI node only has one incoming value, eliminate the PHI node...
Chris Lattnere6794492002-08-12 21:17:25 +00001531 if (PN.getNumIncomingValues() == 1)
1532 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
Chris Lattner9cd1e662002-08-20 15:35:35 +00001533
1534 // Otherwise if all of the incoming values are the same for the PHI, replace
1535 // the PHI node with the incoming value.
1536 //
Chris Lattnerf6c0efa2002-08-22 20:22:01 +00001537 Value *InVal = 0;
1538 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1539 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1540 if (InVal && PN.getIncomingValue(i) != InVal)
1541 return 0; // Not the same, bail out.
1542 else
1543 InVal = PN.getIncomingValue(i);
1544
1545 // The only case that could cause InVal to be null is if we have a PHI node
1546 // that only has entries for itself. In this case, there is no entry into the
1547 // loop, so kill the PHI.
1548 //
1549 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001550
Chris Lattner9cd1e662002-08-20 15:35:35 +00001551 // All of the incoming values are the same, replace the PHI node now.
1552 return ReplaceInstUsesWith(PN, InVal);
Chris Lattnerbbbdd852002-05-06 18:06:38 +00001553}
1554
Chris Lattner48a44f72002-05-02 17:06:02 +00001555
Chris Lattner113f4f42002-06-25 16:13:24 +00001556Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner471bd762003-05-22 19:07:21 +00001557 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00001558 // If so, eliminate the noop.
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001559 if ((GEP.getNumOperands() == 2 &&
Chris Lattner136dab72002-09-11 01:21:33 +00001560 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001561 GEP.getNumOperands() == 1)
1562 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
Chris Lattner48a44f72002-05-02 17:06:02 +00001563
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001564 // Combine Indices - If the source pointer to this getelementptr instruction
1565 // is a getelementptr instruction, combine the indices of the two
1566 // getelementptr instructions into a single instruction.
1567 //
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001568 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001569 std::vector<Value *> Indices;
Chris Lattnerca081252001-12-14 16:52:21 +00001570
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001571 // Can we combine the two pointer arithmetics offsets?
Chris Lattner471bd762003-05-22 19:07:21 +00001572 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1573 isa<Constant>(GEP.getOperand(1))) {
Chris Lattner235af562003-03-05 22:33:14 +00001574 // Replace: gep (gep %P, long C1), long C2, ...
1575 // With: gep %P, long (C1+C2), ...
Chris Lattner34428442003-05-27 16:40:51 +00001576 Value *Sum = ConstantExpr::get(Instruction::Add,
1577 cast<Constant>(Src->getOperand(1)),
1578 cast<Constant>(GEP.getOperand(1)));
Chris Lattner235af562003-03-05 22:33:14 +00001579 assert(Sum && "Constant folding of longs failed!?");
1580 GEP.setOperand(0, Src->getOperand(0));
1581 GEP.setOperand(1, Sum);
1582 AddUsesToWorkList(*Src); // Reduce use count of Src
1583 return &GEP;
Chris Lattner471bd762003-05-22 19:07:21 +00001584 } else if (Src->getNumOperands() == 2) {
Chris Lattner235af562003-03-05 22:33:14 +00001585 // Replace: gep (gep %P, long B), long A, ...
1586 // With: T = long A+B; gep %P, T, ...
1587 //
1588 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1589 GEP.getOperand(1),
1590 Src->getName()+".sum", &GEP);
1591 GEP.setOperand(0, Src->getOperand(0));
1592 GEP.setOperand(1, Sum);
1593 WorkList.push_back(cast<Instruction>(Sum));
1594 return &GEP;
Chris Lattner5d606a02002-11-04 16:43:32 +00001595 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
Chris Lattnera8339e32002-09-17 21:05:42 +00001596 Src->getNumOperands() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001597 // Otherwise we can do the fold if the first index of the GEP is a zero
1598 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1599 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner5d606a02002-11-04 16:43:32 +00001600 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1601 Constant::getNullValue(Type::LongTy)) {
1602 // If the src gep ends with a constant array index, merge this get into
1603 // it, even if we have a non-zero array index.
1604 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1605 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001606 }
1607
1608 if (!Indices.empty())
1609 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001610
1611 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1612 // GEP of global variable. If all of the indices for this GEP are
1613 // constants, we can promote this to a constexpr instead of an instruction.
1614
1615 // Scan for nonconstants...
1616 std::vector<Constant*> Indices;
1617 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1618 for (; I != E && isa<Constant>(*I); ++I)
1619 Indices.push_back(cast<Constant>(*I));
1620
1621 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00001622 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00001623 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1624
1625 // Replace all uses of the GEP with the new constexpr...
1626 return ReplaceInstUsesWith(GEP, CE);
1627 }
Chris Lattnerca081252001-12-14 16:52:21 +00001628 }
1629
Chris Lattnerca081252001-12-14 16:52:21 +00001630 return 0;
1631}
1632
Chris Lattner1085bdf2002-11-04 16:18:53 +00001633Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1634 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1635 if (AI.isArrayAllocation()) // Check C != 1
1636 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1637 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00001638 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00001639
1640 // Create and insert the replacement instruction...
1641 if (isa<MallocInst>(AI))
1642 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001643 else {
1644 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner1085bdf2002-11-04 16:18:53 +00001645 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
Chris Lattnera2620ac2002-11-09 00:49:43 +00001646 }
Chris Lattner1085bdf2002-11-04 16:18:53 +00001647
1648 // Scan to the end of the allocation instructions, to skip over a block of
1649 // allocas if possible...
1650 //
1651 BasicBlock::iterator It = New;
1652 while (isa<AllocationInst>(*It)) ++It;
1653
1654 // Now that I is pointing to the first non-allocation-inst in the block,
1655 // insert our getelementptr instruction...
1656 //
1657 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1658 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1659
1660 // Now make everything use the getelementptr instead of the original
1661 // allocation.
1662 ReplaceInstUsesWith(AI, V);
1663 return &AI;
1664 }
1665 return 0;
1666}
1667
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001668/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1669/// constantexpr, return the constant value being addressed by the constant
1670/// expression, or null if something is funny.
1671///
1672static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1673 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1674 return 0; // Do not allow stepping over the value!
1675
1676 // Loop over all of the operands, tracking down which value we are
1677 // addressing...
1678 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1679 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1680 ConstantStruct *CS = cast<ConstantStruct>(C);
1681 if (CU->getValue() >= CS->getValues().size()) return 0;
1682 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1683 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1684 ConstantArray *CA = cast<ConstantArray>(C);
1685 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1686 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1687 } else
1688 return 0;
1689 return C;
1690}
1691
1692Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1693 Value *Op = LI.getOperand(0);
1694 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1695 Op = CPR->getValue();
1696
1697 // Instcombine load (constant global) into the value loaded...
1698 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001699 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001700 return ReplaceInstUsesWith(LI, GV->getInitializer());
1701
1702 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1703 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1704 if (CE->getOpcode() == Instruction::GetElementPtr)
1705 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1706 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00001707 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00001708 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1709 return ReplaceInstUsesWith(LI, V);
1710 return 0;
1711}
1712
1713
Chris Lattner9eef8a72003-06-04 04:46:00 +00001714Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1715 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner45789ac2003-06-05 20:12:51 +00001716 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
Chris Lattnere967b342003-06-04 05:10:11 +00001717 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1718 BasicBlock *TrueDest = BI.getSuccessor(0);
1719 BasicBlock *FalseDest = BI.getSuccessor(1);
1720 // Swap Destinations and condition...
1721 BI.setCondition(V);
1722 BI.setSuccessor(0, FalseDest);
1723 BI.setSuccessor(1, TrueDest);
1724 return &BI;
1725 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00001726 return 0;
1727}
Chris Lattner1085bdf2002-11-04 16:18:53 +00001728
Chris Lattnerca081252001-12-14 16:52:21 +00001729
Chris Lattner99f48c62002-09-02 04:59:56 +00001730void InstCombiner::removeFromWorkList(Instruction *I) {
1731 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1732 WorkList.end());
1733}
1734
Chris Lattner113f4f42002-06-25 16:13:24 +00001735bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00001736 bool Changed = false;
Chris Lattnerca081252001-12-14 16:52:21 +00001737
Chris Lattner260ab202002-04-18 17:39:14 +00001738 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
Chris Lattnerca081252001-12-14 16:52:21 +00001739
1740 while (!WorkList.empty()) {
1741 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1742 WorkList.pop_back();
1743
Misha Brukman632df282002-10-29 23:06:16 +00001744 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00001745 // Check to see if we can DIE the instruction...
1746 if (isInstructionTriviallyDead(I)) {
1747 // Add operands to the worklist...
1748 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1749 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1750 WorkList.push_back(Op);
1751
1752 ++NumDeadInst;
1753 BasicBlock::iterator BBI = I;
1754 if (dceInstruction(BBI)) {
1755 removeFromWorkList(I);
1756 continue;
1757 }
1758 }
1759
Misha Brukman632df282002-10-29 23:06:16 +00001760 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00001761 if (Constant *C = ConstantFoldInstruction(I)) {
1762 // Add operands to the worklist...
1763 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1764 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1765 WorkList.push_back(Op);
Chris Lattnerc6509f42002-12-05 22:41:53 +00001766 ReplaceInstUsesWith(*I, C);
1767
Chris Lattner99f48c62002-09-02 04:59:56 +00001768 ++NumConstProp;
1769 BasicBlock::iterator BBI = I;
1770 if (dceInstruction(BBI)) {
1771 removeFromWorkList(I);
1772 continue;
1773 }
1774 }
1775
Chris Lattnerca081252001-12-14 16:52:21 +00001776 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001777 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00001778 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00001779 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00001780 if (Result != I) {
1781 // Instructions can end up on the worklist more than once. Make sure
1782 // we do not process an instruction that has been deleted.
Chris Lattner99f48c62002-09-02 04:59:56 +00001783 removeFromWorkList(I);
Chris Lattner260ab202002-04-18 17:39:14 +00001784 ReplaceInstWithInst(I, Result);
Chris Lattner113f4f42002-06-25 16:13:24 +00001785 } else {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001786 BasicBlock::iterator II = I;
1787
1788 // If the instruction was modified, it's possible that it is now dead.
1789 // if so, remove it.
1790 if (dceInstruction(II)) {
1791 // Instructions may end up in the worklist more than once. Erase them
1792 // all.
Chris Lattner99f48c62002-09-02 04:59:56 +00001793 removeFromWorkList(I);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001794 Result = 0;
1795 }
Chris Lattner053c0932002-05-14 15:24:07 +00001796 }
Chris Lattner260ab202002-04-18 17:39:14 +00001797
Chris Lattnerae7a0d32002-08-02 19:29:35 +00001798 if (Result) {
1799 WorkList.push_back(Result);
1800 AddUsesToWorkList(*Result);
1801 }
Chris Lattner260ab202002-04-18 17:39:14 +00001802 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00001803 }
1804 }
1805
Chris Lattner260ab202002-04-18 17:39:14 +00001806 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00001807}
1808
1809Pass *createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00001810 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00001811}