blob: 3119e5704401a9fd75c464210f322b9be4b312ce [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
46#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000047#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000049#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000050#include "llvm/Support/Debug.h"
51#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000052#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000053using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000054using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000055
Chris Lattner260ab202002-04-18 17:39:14 +000056namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000057 Statistic<> NumCombined ("instcombine", "Number of insts combined");
58 Statistic<> NumConstProp("instcombine", "Number of constant folds");
59 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
60
Chris Lattnerc8e66542002-04-27 06:56:12 +000061 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000062 public InstVisitor<InstCombiner, Instruction*> {
63 // Worklist of all of the instructions that need to be simplified.
64 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000065 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000066
Chris Lattner51ea1272004-02-28 05:22:00 +000067 /// AddUsersToWorkList - When an instruction is simplified, add all users of
68 /// the instruction to the work lists because they might get more simplified
69 /// now.
70 ///
71 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000072 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000073 UI != UE; ++UI)
74 WorkList.push_back(cast<Instruction>(*UI));
75 }
76
Chris Lattner51ea1272004-02-28 05:22:00 +000077 /// AddUsesToWorkList - When an instruction is simplified, add operands to
78 /// the work lists because they might get more simplified now.
79 ///
80 void AddUsesToWorkList(Instruction &I) {
81 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83 WorkList.push_back(Op);
84 }
85
Chris Lattner99f48c62002-09-02 04:59:56 +000086 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000088 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000089 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000090
Chris Lattnerf12cc842002-04-28 21:27:06 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000092 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000093 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000094 }
95
Chris Lattner69193f92004-04-05 01:30:19 +000096 TargetData &getTargetData() const { return *TD; }
97
Chris Lattner260ab202002-04-18 17:39:14 +000098 // Visitation implementation - Implement instruction combining for different
99 // instruction types. The semantics are as follows:
100 // Return Value:
101 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000102 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // otherwise - Change was made, replace I with returned instruction
104 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000105 Instruction *visitAdd(BinaryOperator &I);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitMul(BinaryOperator &I);
108 Instruction *visitDiv(BinaryOperator &I);
109 Instruction *visitRem(BinaryOperator &I);
110 Instruction *visitAnd(BinaryOperator &I);
111 Instruction *visitOr (BinaryOperator &I);
112 Instruction *visitXor(BinaryOperator &I);
113 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000114 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000115 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000116 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000121 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000122 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000123 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000124 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000125 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000126
127 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000129
Chris Lattner970c33a2003-06-19 17:00:31 +0000130 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000131 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 bool transformConstExprCastCall(CallSite CS);
133
Chris Lattner69193f92004-04-05 01:30:19 +0000134 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000135 // InsertNewInstBefore - insert an instruction New before instruction Old
136 // in the program. Add the new instruction to the worklist.
137 //
Chris Lattner623826c2004-09-28 21:48:02 +0000138 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000139 assert(New && New->getParent() == 0 &&
140 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000141 BasicBlock *BB = Old.getParent();
142 BB->getInstList().insert(&Old, New); // Insert inst
143 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000144 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145 }
146
Chris Lattner7e794272004-09-24 15:21:34 +0000147 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
148 /// This also adds the cast to the worklist. Finally, this returns the
149 /// cast.
150 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
151 if (V->getType() == Ty) return V;
152
153 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
154 WorkList.push_back(C);
155 return C;
156 }
157
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000158 // ReplaceInstUsesWith - This method is to be used when an instruction is
159 // found to be dead, replacable with another preexisting expression. Here
160 // we add all uses of I to the worklist, replace all uses of I with the new
161 // value, then return I, so that the inst combiner will know that I was
162 // modified.
163 //
164 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000165 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000166 if (&I != V) {
167 I.replaceAllUsesWith(V);
168 return &I;
169 } else {
170 // If we are replacing the instruction with itself, this must be in a
171 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000172 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000173 return &I;
174 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000175 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000176
177 // EraseInstFromFunction - When dealing with an instruction that has side
178 // effects or produces a void value, we can't rely on DCE to delete the
179 // instruction. Instead, visit methods should return the value returned by
180 // this function.
181 Instruction *EraseInstFromFunction(Instruction &I) {
182 assert(I.use_empty() && "Cannot erase instruction that is used!");
183 AddUsesToWorkList(I);
184 removeFromWorkList(&I);
185 I.getParent()->getInstList().erase(&I);
186 return 0; // Don't do anything with FI
187 }
188
189
Chris Lattner3ac7c262003-08-13 20:16:26 +0000190 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000191 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
192 /// InsertBefore instruction. This is specialized a bit to avoid inserting
193 /// casts that are known to not do anything...
194 ///
195 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
196 Instruction *InsertBefore);
197
Chris Lattner7fb29e12003-03-11 00:12:48 +0000198 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000199 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000200 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000201
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000202
203 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
204 // PHI node as operand #0, see if we can fold the instruction into the PHI
205 // (which is only possible if all operands to the PHI are constants).
206 Instruction *FoldOpIntoPhi(Instruction &I);
207
Chris Lattnerba1cb382003-09-19 17:17:26 +0000208 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
209 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000210
211 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
212 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000213 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000214
Chris Lattnerc8b70922002-07-26 21:12:46 +0000215 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000216}
217
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000218// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000219// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000220static unsigned getComplexity(Value *V) {
221 if (isa<Instruction>(V)) {
222 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000223 return 3;
224 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000225 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000226 if (isa<Argument>(V)) return 3;
227 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000228}
Chris Lattner260ab202002-04-18 17:39:14 +0000229
Chris Lattner7fb29e12003-03-11 00:12:48 +0000230// isOnlyUse - Return true if this instruction will be deleted if we stop using
231// it.
232static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000233 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000234}
235
Chris Lattnere79e8542004-02-23 06:38:22 +0000236// getPromotedType - Return the specified type promoted as it would be to pass
237// though a va_arg area...
238static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000239 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000240 case Type::SByteTyID:
241 case Type::ShortTyID: return Type::IntTy;
242 case Type::UByteTyID:
243 case Type::UShortTyID: return Type::UIntTy;
244 case Type::FloatTyID: return Type::DoubleTy;
245 default: return Ty;
246 }
247}
248
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000249// SimplifyCommutative - This performs a few simplifications for commutative
250// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000251//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000252// 1. Order operands such that they are listed from right (least complex) to
253// left (most complex). This puts constants before unary operators before
254// binary operators.
255//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000256// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
257// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000258//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000259bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000260 bool Changed = false;
261 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
262 Changed = !I.swapOperands();
263
264 if (!I.isAssociative()) return Changed;
265 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000266 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
267 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
268 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000269 Constant *Folded = ConstantExpr::get(I.getOpcode(),
270 cast<Constant>(I.getOperand(1)),
271 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000272 I.setOperand(0, Op->getOperand(0));
273 I.setOperand(1, Folded);
274 return true;
275 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
276 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
277 isOnlyUse(Op) && isOnlyUse(Op1)) {
278 Constant *C1 = cast<Constant>(Op->getOperand(1));
279 Constant *C2 = cast<Constant>(Op1->getOperand(1));
280
281 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000282 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000283 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
284 Op1->getOperand(0),
285 Op1->getName(), &I);
286 WorkList.push_back(New);
287 I.setOperand(0, New);
288 I.setOperand(1, Folded);
289 return true;
290 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000291 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000292 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000293}
Chris Lattnerca081252001-12-14 16:52:21 +0000294
Chris Lattnerbb74e222003-03-10 23:06:50 +0000295// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
296// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000297//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000298static inline Value *dyn_castNegVal(Value *V) {
299 if (BinaryOperator::isNeg(V))
300 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
301
Chris Lattner9244df62003-04-30 22:19:10 +0000302 // Constants can be considered to be negated values if they can be folded...
303 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000304 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000305 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000306}
307
Chris Lattnerbb74e222003-03-10 23:06:50 +0000308static inline Value *dyn_castNotVal(Value *V) {
309 if (BinaryOperator::isNot(V))
310 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
311
312 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000313 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000314 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000315 return 0;
316}
317
Chris Lattner7fb29e12003-03-11 00:12:48 +0000318// dyn_castFoldableMul - If this value is a multiply that can be folded into
319// other computations (because it has a constant operand), return the
320// non-constant operand of the multiply.
321//
322static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000323 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000324 if (Instruction *I = dyn_cast<Instruction>(V))
325 if (I->getOpcode() == Instruction::Mul)
326 if (isa<Constant>(I->getOperand(1)))
327 return I->getOperand(0);
328 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000329}
Chris Lattner31ae8632002-08-14 17:51:49 +0000330
Chris Lattner3082c5a2003-02-18 19:28:33 +0000331// Log2 - Calculate the log base 2 for the specified value if it is exactly a
332// power of 2.
333static unsigned Log2(uint64_t Val) {
334 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
335 unsigned Count = 0;
336 while (Val != 1) {
337 if (Val & 1) return 0; // Multiple bits set?
338 Val >>= 1;
339 ++Count;
340 }
341 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000342}
343
Chris Lattner623826c2004-09-28 21:48:02 +0000344// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000345static ConstantInt *AddOne(ConstantInt *C) {
346 return cast<ConstantInt>(ConstantExpr::getAdd(C,
347 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000348}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000349static ConstantInt *SubOne(ConstantInt *C) {
350 return cast<ConstantInt>(ConstantExpr::getSub(C,
351 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000352}
353
354// isTrueWhenEqual - Return true if the specified setcondinst instruction is
355// true when both operands are equal...
356//
357static bool isTrueWhenEqual(Instruction &I) {
358 return I.getOpcode() == Instruction::SetEQ ||
359 I.getOpcode() == Instruction::SetGE ||
360 I.getOpcode() == Instruction::SetLE;
361}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000362
363/// AssociativeOpt - Perform an optimization on an associative operator. This
364/// function is designed to check a chain of associative operators for a
365/// potential to apply a certain optimization. Since the optimization may be
366/// applicable if the expression was reassociated, this checks the chain, then
367/// reassociates the expression as necessary to expose the optimization
368/// opportunity. This makes use of a special Functor, which must define
369/// 'shouldApply' and 'apply' methods.
370///
371template<typename Functor>
372Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
373 unsigned Opcode = Root.getOpcode();
374 Value *LHS = Root.getOperand(0);
375
376 // Quick check, see if the immediate LHS matches...
377 if (F.shouldApply(LHS))
378 return F.apply(Root);
379
380 // Otherwise, if the LHS is not of the same opcode as the root, return.
381 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000382 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000383 // Should we apply this transform to the RHS?
384 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
385
386 // If not to the RHS, check to see if we should apply to the LHS...
387 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
388 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
389 ShouldApply = true;
390 }
391
392 // If the functor wants to apply the optimization to the RHS of LHSI,
393 // reassociate the expression from ((? op A) op B) to (? op (A op B))
394 if (ShouldApply) {
395 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000396
397 // Now all of the instructions are in the current basic block, go ahead
398 // and perform the reassociation.
399 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
400
401 // First move the selected RHS to the LHS of the root...
402 Root.setOperand(0, LHSI->getOperand(1));
403
404 // Make what used to be the LHS of the root be the user of the root...
405 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000406 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000407 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
408 return 0;
409 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000410 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000411 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000412 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
413 BasicBlock::iterator ARI = &Root; ++ARI;
414 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
415 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000416
417 // Now propagate the ExtraOperand down the chain of instructions until we
418 // get to LHSI.
419 while (TmpLHSI != LHSI) {
420 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000421 // Move the instruction to immediately before the chain we are
422 // constructing to avoid breaking dominance properties.
423 NextLHSI->getParent()->getInstList().remove(NextLHSI);
424 BB->getInstList().insert(ARI, NextLHSI);
425 ARI = NextLHSI;
426
Chris Lattnerb8b97502003-08-13 19:01:45 +0000427 Value *NextOp = NextLHSI->getOperand(1);
428 NextLHSI->setOperand(1, ExtraOperand);
429 TmpLHSI = NextLHSI;
430 ExtraOperand = NextOp;
431 }
432
433 // Now that the instructions are reassociated, have the functor perform
434 // the transformation...
435 return F.apply(Root);
436 }
437
438 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
439 }
440 return 0;
441}
442
443
444// AddRHS - Implements: X + X --> X << 1
445struct AddRHS {
446 Value *RHS;
447 AddRHS(Value *rhs) : RHS(rhs) {}
448 bool shouldApply(Value *LHS) const { return LHS == RHS; }
449 Instruction *apply(BinaryOperator &Add) const {
450 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
451 ConstantInt::get(Type::UByteTy, 1));
452 }
453};
454
455// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
456// iff C1&C2 == 0
457struct AddMaskingAnd {
458 Constant *C2;
459 AddMaskingAnd(Constant *c) : C2(c) {}
460 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000461 ConstantInt *C1;
462 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
463 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000464 }
465 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000466 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000467 }
468};
469
Chris Lattner183b3362004-04-09 19:05:30 +0000470static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
471 InstCombiner *IC) {
472 // Figure out if the constant is the left or the right argument.
473 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
474 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000475
Chris Lattner183b3362004-04-09 19:05:30 +0000476 if (Constant *SOC = dyn_cast<Constant>(SO)) {
477 if (ConstIsRHS)
478 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
479 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
480 }
481
482 Value *Op0 = SO, *Op1 = ConstOperand;
483 if (!ConstIsRHS)
484 std::swap(Op0, Op1);
485 Instruction *New;
486 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
487 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
488 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
489 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000490 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000491 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000492 abort();
493 }
Chris Lattner183b3362004-04-09 19:05:30 +0000494 return IC->InsertNewInstBefore(New, BI);
495}
496
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000497
498/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
499/// node as operand #0, see if we can fold the instruction into the PHI (which
500/// is only possible if all operands to the PHI are constants).
501Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
502 PHINode *PN = cast<PHINode>(I.getOperand(0));
503 if (!PN->hasOneUse()) return 0;
504
505 // Check to see if all of the operands of the PHI are constants. If not, we
506 // cannot do the transformation.
507 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
508 if (!isa<Constant>(PN->getIncomingValue(i)))
509 return 0;
510
511 // Okay, we can do the transformation: create the new PHI node.
512 PHINode *NewPN = new PHINode(I.getType(), I.getName());
513 I.setName("");
514 NewPN->op_reserve(PN->getNumOperands());
515 InsertNewInstBefore(NewPN, *PN);
516
517 // Next, add all of the operands to the PHI.
518 if (I.getNumOperands() == 2) {
519 Constant *C = cast<Constant>(I.getOperand(1));
520 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
521 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
522 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
523 PN->getIncomingBlock(i));
524 }
525 } else {
526 assert(isa<CastInst>(I) && "Unary op should be a cast!");
527 const Type *RetTy = I.getType();
528 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
529 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
530 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
531 PN->getIncomingBlock(i));
532 }
533 }
534 return ReplaceInstUsesWith(I, NewPN);
535}
536
Chris Lattner183b3362004-04-09 19:05:30 +0000537// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
538// constant as the other operand, try to fold the binary operator into the
539// select arguments.
540static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
541 InstCombiner *IC) {
542 // Don't modify shared select instructions
543 if (!SI->hasOneUse()) return 0;
544 Value *TV = SI->getOperand(1);
545 Value *FV = SI->getOperand(2);
546
547 if (isa<Constant>(TV) || isa<Constant>(FV)) {
548 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
549 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
550
551 return new SelectInst(SI->getCondition(), SelectTrueVal,
552 SelectFalseVal);
553 }
554 return 0;
555}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000556
Chris Lattner113f4f42002-06-25 16:13:24 +0000557Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000558 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000559 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000560
Chris Lattnercf4a9962004-04-10 22:01:55 +0000561 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000562 // X + undef -> undef
563 if (isa<UndefValue>(RHS))
564 return ReplaceInstUsesWith(I, RHS);
565
Chris Lattnercf4a9962004-04-10 22:01:55 +0000566 // X + 0 --> X
567 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
568 RHSC->isNullValue())
569 return ReplaceInstUsesWith(I, LHS);
570
571 // X + (signbit) --> X ^ signbit
572 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
573 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
574 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
575 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000576 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000577 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000578
579 if (isa<PHINode>(LHS))
580 if (Instruction *NV = FoldOpIntoPhi(I))
581 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000582 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000583
Chris Lattnerb8b97502003-08-13 19:01:45 +0000584 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000585 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000586 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000587 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000588
Chris Lattner147e9752002-05-08 22:46:53 +0000589 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000590 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000591 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000592
593 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000594 if (!isa<Constant>(RHS))
595 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000596 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000597
Chris Lattner57c8d992003-02-18 19:57:07 +0000598 // X*C + X --> X * (C+1)
599 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000600 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000601 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000602 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
603 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000604 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000605 }
606
607 // X + X*C --> X * (C+1)
608 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000609 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000610 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000611 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
612 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000613 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000614 }
615
Chris Lattnerb8b97502003-08-13 19:01:45 +0000616 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000617 ConstantInt *C2;
618 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000619 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000620
Chris Lattnerb9cde762003-10-02 15:11:26 +0000621 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000622 Value *X;
623 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
624 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
625 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000626 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000627
Chris Lattnerbff91d92004-10-08 05:07:56 +0000628 // (X & FF00) + xx00 -> (X+xx00) & FF00
629 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
630 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
631 if (Anded == CRHS) {
632 // See if all bits from the first bit set in the Add RHS up are included
633 // in the mask. First, get the rightmost bit.
634 uint64_t AddRHSV = CRHS->getRawValue();
635
636 // Form a mask of all bits from the lowest bit added through the top.
637 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
638 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
639
640 // See if the and mask includes all of these bits.
641 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
642
643 if (AddRHSHighBits == AddRHSHighBitsAnd) {
644 // Okay, the xform is safe. Insert the new add pronto.
645 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
646 LHS->getName()), I);
647 return BinaryOperator::createAnd(NewAdd, C2);
648 }
649 }
650 }
651
652
Chris Lattnerd4252a72004-07-30 07:50:03 +0000653 // Try to fold constant add into select arguments.
654 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
655 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
656 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000657 }
658
Chris Lattner113f4f42002-06-25 16:13:24 +0000659 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000660}
661
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000662// isSignBit - Return true if the value represented by the constant only has the
663// highest order bit set.
664static bool isSignBit(ConstantInt *CI) {
665 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
666 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
667}
668
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000669static unsigned getTypeSizeInBits(const Type *Ty) {
670 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
671}
672
Chris Lattner022167f2004-03-13 00:11:49 +0000673/// RemoveNoopCast - Strip off nonconverting casts from the value.
674///
675static Value *RemoveNoopCast(Value *V) {
676 if (CastInst *CI = dyn_cast<CastInst>(V)) {
677 const Type *CTy = CI->getType();
678 const Type *OpTy = CI->getOperand(0)->getType();
679 if (CTy->isInteger() && OpTy->isInteger()) {
680 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
681 return RemoveNoopCast(CI->getOperand(0));
682 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
683 return RemoveNoopCast(CI->getOperand(0));
684 }
685 return V;
686}
687
Chris Lattner113f4f42002-06-25 16:13:24 +0000688Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000690
Chris Lattnere6794492002-08-12 21:17:25 +0000691 if (Op0 == Op1) // sub X, X -> 0
692 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000693
Chris Lattnere6794492002-08-12 21:17:25 +0000694 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000695 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000696 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000697
Chris Lattner81a7a232004-10-16 18:11:37 +0000698 if (isa<UndefValue>(Op0))
699 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
700 if (isa<UndefValue>(Op1))
701 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
702
Chris Lattner8f2f5982003-11-05 01:06:05 +0000703 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
704 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000705 if (C->isAllOnesValue())
706 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000707
Chris Lattner8f2f5982003-11-05 01:06:05 +0000708 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000709 Value *X;
710 if (match(Op1, m_Not(m_Value(X))))
711 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000712 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000713 // -((uint)X >> 31) -> ((int)X >> 31)
714 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000715 if (C->isNullValue()) {
716 Value *NoopCastedRHS = RemoveNoopCast(Op1);
717 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000718 if (SI->getOpcode() == Instruction::Shr)
719 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
720 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000721 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000722 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000723 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000724 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000725 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000726 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000727 // Ok, the transformation is safe. Insert a cast of the incoming
728 // value, then the new shift, then the new cast.
729 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
730 SI->getOperand(0)->getName());
731 Value *InV = InsertNewInstBefore(FirstCast, I);
732 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
733 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000734 if (NewShift->getType() == I.getType())
735 return NewShift;
736 else {
737 InV = InsertNewInstBefore(NewShift, I);
738 return new CastInst(NewShift, I.getType());
739 }
Chris Lattner92295c52004-03-12 23:53:13 +0000740 }
741 }
Chris Lattner022167f2004-03-13 00:11:49 +0000742 }
Chris Lattner183b3362004-04-09 19:05:30 +0000743
744 // Try to fold constant sub into select arguments.
745 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
746 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
747 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000748
749 if (isa<PHINode>(Op0))
750 if (Instruction *NV = FoldOpIntoPhi(I))
751 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000752 }
753
Chris Lattner3082c5a2003-02-18 19:28:33 +0000754 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000755 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000756 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
757 // is not used by anyone else...
758 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000759 if (Op1I->getOpcode() == Instruction::Sub &&
760 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000761 // Swap the two operands of the subexpr...
762 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
763 Op1I->setOperand(0, IIOp1);
764 Op1I->setOperand(1, IIOp0);
765
766 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000767 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000768 }
769
770 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
771 //
772 if (Op1I->getOpcode() == Instruction::And &&
773 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
774 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
775
Chris Lattner396dbfe2004-06-09 05:08:07 +0000776 Value *NewNot =
777 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000778 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000779 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000780
Chris Lattner0aee4b72004-10-06 15:08:25 +0000781 // -(X sdiv C) -> (X sdiv -C)
782 if (Op1I->getOpcode() == Instruction::Div)
783 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
784 if (CSI->getValue() == 0)
785 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
786 return BinaryOperator::createDiv(Op1I->getOperand(0),
787 ConstantExpr::getNeg(DivRHS));
788
Chris Lattner57c8d992003-02-18 19:57:07 +0000789 // X - X*C --> X * (1-C)
790 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000791 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000792 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000793 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000794 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000795 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000796 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000797 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000798
Chris Lattner57c8d992003-02-18 19:57:07 +0000799 // X*C - X --> X * (C-1)
800 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000801 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000802 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000803 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000804 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000805 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000806 }
807
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000808 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000809}
810
Chris Lattnere79e8542004-02-23 06:38:22 +0000811/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
812/// really just returns true if the most significant (sign) bit is set.
813static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
814 if (RHS->getType()->isSigned()) {
815 // True if source is LHS < 0 or LHS <= -1
816 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
817 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
818 } else {
819 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
820 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
821 // the size of the integer type.
822 if (Opcode == Instruction::SetGE)
823 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
824 if (Opcode == Instruction::SetGT)
825 return RHSC->getValue() ==
826 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
827 }
828 return false;
829}
830
Chris Lattner113f4f42002-06-25 16:13:24 +0000831Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000832 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000833 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000834
Chris Lattner81a7a232004-10-16 18:11:37 +0000835 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
836 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
837
Chris Lattnere6794492002-08-12 21:17:25 +0000838 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000839 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
840 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000841
842 // ((X << C1)*C2) == (X * (C2 << C1))
843 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
844 if (SI->getOpcode() == Instruction::Shl)
845 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000846 return BinaryOperator::createMul(SI->getOperand(0),
847 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000848
Chris Lattnercce81be2003-09-11 22:24:54 +0000849 if (CI->isNullValue())
850 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
851 if (CI->equalsInt(1)) // X * 1 == X
852 return ReplaceInstUsesWith(I, Op0);
853 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000854 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000855
Chris Lattnercce81be2003-09-11 22:24:54 +0000856 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000857 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
858 return new ShiftInst(Instruction::Shl, Op0,
859 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000860 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000861 if (Op1F->isNullValue())
862 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000863
Chris Lattner3082c5a2003-02-18 19:28:33 +0000864 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
865 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
866 if (Op1F->getValue() == 1.0)
867 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
868 }
Chris Lattner183b3362004-04-09 19:05:30 +0000869
870 // Try to fold constant mul into select arguments.
871 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
872 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
873 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000874
875 if (isa<PHINode>(Op0))
876 if (Instruction *NV = FoldOpIntoPhi(I))
877 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000878 }
879
Chris Lattner934a64cf2003-03-10 23:23:04 +0000880 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
881 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000882 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000883
Chris Lattner2635b522004-02-23 05:39:21 +0000884 // If one of the operands of the multiply is a cast from a boolean value, then
885 // we know the bool is either zero or one, so this is a 'masking' multiply.
886 // See if we can simplify things based on how the boolean was originally
887 // formed.
888 CastInst *BoolCast = 0;
889 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
890 if (CI->getOperand(0)->getType() == Type::BoolTy)
891 BoolCast = CI;
892 if (!BoolCast)
893 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
894 if (CI->getOperand(0)->getType() == Type::BoolTy)
895 BoolCast = CI;
896 if (BoolCast) {
897 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
898 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
899 const Type *SCOpTy = SCIOp0->getType();
900
Chris Lattnere79e8542004-02-23 06:38:22 +0000901 // If the setcc is true iff the sign bit of X is set, then convert this
902 // multiply into a shift/and combination.
903 if (isa<ConstantInt>(SCIOp1) &&
904 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000905 // Shift the X value right to turn it into "all signbits".
906 Constant *Amt = ConstantUInt::get(Type::UByteTy,
907 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000908 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000909 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000910 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
911 SCIOp0->getName()), I);
912 }
913
914 Value *V =
915 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
916 BoolCast->getOperand(0)->getName()+
917 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000918
919 // If the multiply type is not the same as the source type, sign extend
920 // or truncate to the multiply type.
921 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000922 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000923
924 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000925 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000926 }
927 }
928 }
929
Chris Lattner113f4f42002-06-25 16:13:24 +0000930 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000931}
932
Chris Lattner113f4f42002-06-25 16:13:24 +0000933Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000934 if (isa<UndefValue>(I.getOperand(0))) // undef / X -> 0
935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
936 if (isa<UndefValue>(I.getOperand(1)))
937 return ReplaceInstUsesWith(I, I.getOperand(1)); // X / undef -> undef
938
Chris Lattner3082c5a2003-02-18 19:28:33 +0000939 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000940 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000941 if (RHS->equalsInt(1))
942 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000943
Chris Lattnere20c3342004-04-26 14:01:59 +0000944 // div X, -1 == -X
945 if (RHS->isAllOnesValue())
946 return BinaryOperator::createNeg(I.getOperand(0));
947
Chris Lattner272d5ca2004-09-28 18:22:15 +0000948 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
949 if (LHS->getOpcode() == Instruction::Div)
950 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000951 // (X / C1) / C2 -> X / (C1*C2)
952 return BinaryOperator::createDiv(LHS->getOperand(0),
953 ConstantExpr::getMul(RHS, LHSRHS));
954 }
955
Chris Lattner3082c5a2003-02-18 19:28:33 +0000956 // Check to see if this is an unsigned division with an exact power of 2,
957 // if so, convert to a right shift.
958 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
959 if (uint64_t Val = C->getValue()) // Don't break X / 0
960 if (uint64_t C = Log2(Val))
961 return new ShiftInst(Instruction::Shr, I.getOperand(0),
962 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000963
Chris Lattner4ad08352004-10-09 02:50:40 +0000964 // -X/C -> X/-C
965 if (RHS->getType()->isSigned())
966 if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
967 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
968
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000969 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
970 if (Instruction *NV = FoldOpIntoPhi(I))
971 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000972 }
973
974 // 0 / X == 0, we don't need to preserve faults!
975 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
976 if (LHS->equalsInt(0))
977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
978
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000979 return 0;
980}
981
982
Chris Lattner113f4f42002-06-25 16:13:24 +0000983Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000984 if (I.getType()->isSigned())
985 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000986 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000987 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000988 // X % -Y -> X % Y
989 AddUsesToWorkList(I);
990 I.setOperand(1, RHSNeg);
991 return &I;
992 }
993
Chris Lattner81a7a232004-10-16 18:11:37 +0000994 if (isa<UndefValue>(I.getOperand(0))) // undef % X -> 0
995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
996 if (isa<UndefValue>(I.getOperand(1)))
997 return ReplaceInstUsesWith(I, I.getOperand(1)); // X % undef -> undef
998
Chris Lattner3082c5a2003-02-18 19:28:33 +0000999 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
1000 if (RHS->equalsInt(1)) // X % 1 == 0
1001 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1002
1003 // Check to see if this is an unsigned remainder with an exact power of 2,
1004 // if so, convert to a bitwise and.
1005 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1006 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001007 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001008 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +00001009 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001010 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1011 if (Instruction *NV = FoldOpIntoPhi(I))
1012 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +00001013 }
1014
1015 // 0 % X == 0, we don't need to preserve faults!
1016 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
1017 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1019
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001020 return 0;
1021}
1022
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001023// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001024static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001025 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1026 // Calculate -1 casted to the right type...
1027 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1028 uint64_t Val = ~0ULL; // All ones
1029 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1030 return CU->getValue() == Val-1;
1031 }
1032
1033 const ConstantSInt *CS = cast<ConstantSInt>(C);
1034
1035 // Calculate 0111111111..11111
1036 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1037 int64_t Val = INT64_MAX; // All ones
1038 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1039 return CS->getValue() == Val-1;
1040}
1041
1042// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001043static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001044 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1045 return CU->getValue() == 1;
1046
1047 const ConstantSInt *CS = cast<ConstantSInt>(C);
1048
1049 // Calculate 1111111111000000000000
1050 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1051 int64_t Val = -1; // All ones
1052 Val <<= TypeBits-1; // Shift over to the right spot
1053 return CS->getValue() == Val+1;
1054}
1055
Chris Lattner35167c32004-06-09 07:59:58 +00001056// isOneBitSet - Return true if there is exactly one bit set in the specified
1057// constant.
1058static bool isOneBitSet(const ConstantInt *CI) {
1059 uint64_t V = CI->getRawValue();
1060 return V && (V & (V-1)) == 0;
1061}
1062
Chris Lattner8fc5af42004-09-23 21:46:38 +00001063#if 0 // Currently unused
1064// isLowOnes - Return true if the constant is of the form 0+1+.
1065static bool isLowOnes(const ConstantInt *CI) {
1066 uint64_t V = CI->getRawValue();
1067
1068 // There won't be bits set in parts that the type doesn't contain.
1069 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1070
1071 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1072 return U && V && (U & V) == 0;
1073}
1074#endif
1075
1076// isHighOnes - Return true if the constant is of the form 1+0+.
1077// This is the same as lowones(~X).
1078static bool isHighOnes(const ConstantInt *CI) {
1079 uint64_t V = ~CI->getRawValue();
1080
1081 // There won't be bits set in parts that the type doesn't contain.
1082 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1083
1084 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1085 return U && V && (U & V) == 0;
1086}
1087
1088
Chris Lattner3ac7c262003-08-13 20:16:26 +00001089/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1090/// are carefully arranged to allow folding of expressions such as:
1091///
1092/// (A < B) | (A > B) --> (A != B)
1093///
1094/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1095/// represents that the comparison is true if A == B, and bit value '1' is true
1096/// if A < B.
1097///
1098static unsigned getSetCondCode(const SetCondInst *SCI) {
1099 switch (SCI->getOpcode()) {
1100 // False -> 0
1101 case Instruction::SetGT: return 1;
1102 case Instruction::SetEQ: return 2;
1103 case Instruction::SetGE: return 3;
1104 case Instruction::SetLT: return 4;
1105 case Instruction::SetNE: return 5;
1106 case Instruction::SetLE: return 6;
1107 // True -> 7
1108 default:
1109 assert(0 && "Invalid SetCC opcode!");
1110 return 0;
1111 }
1112}
1113
1114/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1115/// opcode and two operands into either a constant true or false, or a brand new
1116/// SetCC instruction.
1117static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1118 switch (Opcode) {
1119 case 0: return ConstantBool::False;
1120 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1121 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1122 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1123 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1124 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1125 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1126 case 7: return ConstantBool::True;
1127 default: assert(0 && "Illegal SetCCCode!"); return 0;
1128 }
1129}
1130
1131// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1132struct FoldSetCCLogical {
1133 InstCombiner &IC;
1134 Value *LHS, *RHS;
1135 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1136 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1137 bool shouldApply(Value *V) const {
1138 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1139 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1140 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1141 return false;
1142 }
1143 Instruction *apply(BinaryOperator &Log) const {
1144 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1145 if (SCI->getOperand(0) != LHS) {
1146 assert(SCI->getOperand(1) == LHS);
1147 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1148 }
1149
1150 unsigned LHSCode = getSetCondCode(SCI);
1151 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1152 unsigned Code;
1153 switch (Log.getOpcode()) {
1154 case Instruction::And: Code = LHSCode & RHSCode; break;
1155 case Instruction::Or: Code = LHSCode | RHSCode; break;
1156 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001157 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001158 }
1159
1160 Value *RV = getSetCCValue(Code, LHS, RHS);
1161 if (Instruction *I = dyn_cast<Instruction>(RV))
1162 return I;
1163 // Otherwise, it's a constant boolean value...
1164 return IC.ReplaceInstUsesWith(Log, RV);
1165 }
1166};
1167
1168
Chris Lattnerba1cb382003-09-19 17:17:26 +00001169// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1170// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1171// guaranteed to be either a shift instruction or a binary operator.
1172Instruction *InstCombiner::OptAndOp(Instruction *Op,
1173 ConstantIntegral *OpRHS,
1174 ConstantIntegral *AndRHS,
1175 BinaryOperator &TheAnd) {
1176 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001177 Constant *Together = 0;
1178 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001179 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001180
Chris Lattnerba1cb382003-09-19 17:17:26 +00001181 switch (Op->getOpcode()) {
1182 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001183 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001184 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001185 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001186 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001187 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1188 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001189 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001190 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001191 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001192 }
1193 break;
1194 case Instruction::Or:
1195 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001196 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001197 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001198 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001199 if (Together == AndRHS) // (X | C) & C --> C
1200 return ReplaceInstUsesWith(TheAnd, AndRHS);
1201
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001202 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001203 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1204 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001205 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001206 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001207 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001208 }
1209 }
1210 break;
1211 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001212 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001213 // Adding a one to a single bit bit-field should be turned into an XOR
1214 // of the bit. First thing to check is to see if this AND is with a
1215 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001216 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001217
1218 // Clear bits that are not part of the constant.
1219 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1220
1221 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001222 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001223 // Ok, at this point, we know that we are masking the result of the
1224 // ADD down to exactly one bit. If the constant we are adding has
1225 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001226 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001227
1228 // Check to see if any bits below the one bit set in AndRHSV are set.
1229 if ((AddRHS & (AndRHSV-1)) == 0) {
1230 // If not, the only thing that can effect the output of the AND is
1231 // the bit specified by AndRHSV. If that bit is set, the effect of
1232 // the XOR is to toggle the bit. If it is clear, then the ADD has
1233 // no effect.
1234 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1235 TheAnd.setOperand(0, X);
1236 return &TheAnd;
1237 } else {
1238 std::string Name = Op->getName(); Op->setName("");
1239 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001240 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001241 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001242 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001243 }
1244 }
1245 }
1246 }
1247 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001248
1249 case Instruction::Shl: {
1250 // We know that the AND will not produce any of the bits shifted in, so if
1251 // the anded constant includes them, clear them now!
1252 //
1253 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001254 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1255 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1256
1257 if (CI == ShlMask) { // Masking out bits that the shift already masks
1258 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1259 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001260 TheAnd.setOperand(1, CI);
1261 return &TheAnd;
1262 }
1263 break;
1264 }
1265 case Instruction::Shr:
1266 // We know that the AND will not produce any of the bits shifted in, so if
1267 // the anded constant includes them, clear them now! This only applies to
1268 // unsigned shifts, because a signed shr may bring in set bits!
1269 //
1270 if (AndRHS->getType()->isUnsigned()) {
1271 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001272 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1273 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1274
1275 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1276 return ReplaceInstUsesWith(TheAnd, Op);
1277 } else if (CI != AndRHS) {
1278 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001279 return &TheAnd;
1280 }
Chris Lattner7e794272004-09-24 15:21:34 +00001281 } else { // Signed shr.
1282 // See if this is shifting in some sign extension, then masking it out
1283 // with an and.
1284 if (Op->hasOneUse()) {
1285 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1286 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1287 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1288 if (CI == ShrMask) { // Masking out bits shifted in.
1289 // Make the argument unsigned.
1290 Value *ShVal = Op->getOperand(0);
1291 ShVal = InsertCastBefore(ShVal,
1292 ShVal->getType()->getUnsignedVersion(),
1293 TheAnd);
1294 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1295 OpRHS, Op->getName()),
1296 TheAnd);
1297 return new CastInst(ShVal, Op->getType());
1298 }
1299 }
Chris Lattner2da29172003-09-19 19:05:02 +00001300 }
1301 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001302 }
1303 return 0;
1304}
1305
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001306
Chris Lattner6862fbd2004-09-29 17:40:11 +00001307/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1308/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1309/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1310/// insert new instructions.
1311Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1312 bool Inside, Instruction &IB) {
1313 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1314 "Lo is not <= Hi in range emission code!");
1315 if (Inside) {
1316 if (Lo == Hi) // Trivially false.
1317 return new SetCondInst(Instruction::SetNE, V, V);
1318 if (cast<ConstantIntegral>(Lo)->isMinValue())
1319 return new SetCondInst(Instruction::SetLT, V, Hi);
1320
1321 Constant *AddCST = ConstantExpr::getNeg(Lo);
1322 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1323 InsertNewInstBefore(Add, IB);
1324 // Convert to unsigned for the comparison.
1325 const Type *UnsType = Add->getType()->getUnsignedVersion();
1326 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1327 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1328 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1329 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1330 }
1331
1332 if (Lo == Hi) // Trivially true.
1333 return new SetCondInst(Instruction::SetEQ, V, V);
1334
1335 Hi = SubOne(cast<ConstantInt>(Hi));
1336 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1337 return new SetCondInst(Instruction::SetGT, V, Hi);
1338
1339 // Emit X-Lo > Hi-Lo-1
1340 Constant *AddCST = ConstantExpr::getNeg(Lo);
1341 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1342 InsertNewInstBefore(Add, IB);
1343 // Convert to unsigned for the comparison.
1344 const Type *UnsType = Add->getType()->getUnsignedVersion();
1345 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1346 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1347 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1348 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1349}
1350
1351
Chris Lattner113f4f42002-06-25 16:13:24 +00001352Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001353 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001354 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001355
Chris Lattner81a7a232004-10-16 18:11:37 +00001356 if (isa<UndefValue>(Op1)) // X & undef -> 0
1357 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1358
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001359 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001360 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1361 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001362
1363 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001364 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001365 if (RHS->isAllOnesValue())
1366 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001367
Chris Lattnerba1cb382003-09-19 17:17:26 +00001368 // Optimize a variety of ((val OP C1) & C2) combinations...
1369 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1370 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001371 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001372 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001373 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1374 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001375 }
Chris Lattner183b3362004-04-09 19:05:30 +00001376
1377 // Try to fold constant and into select arguments.
1378 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1379 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1380 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001381 if (isa<PHINode>(Op0))
1382 if (Instruction *NV = FoldOpIntoPhi(I))
1383 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001384 }
1385
Chris Lattnerbb74e222003-03-10 23:06:50 +00001386 Value *Op0NotVal = dyn_castNotVal(Op0);
1387 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001388
Chris Lattner023a4832004-06-18 06:07:51 +00001389 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1390 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1391
Misha Brukman9c003d82004-07-30 12:50:08 +00001392 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001393 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001394 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1395 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001396 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001397 return BinaryOperator::createNot(Or);
1398 }
1399
Chris Lattner623826c2004-09-28 21:48:02 +00001400 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1401 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001402 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1403 return R;
1404
Chris Lattner623826c2004-09-28 21:48:02 +00001405 Value *LHSVal, *RHSVal;
1406 ConstantInt *LHSCst, *RHSCst;
1407 Instruction::BinaryOps LHSCC, RHSCC;
1408 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1409 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1410 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1411 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1412 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1413 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1414 // Ensure that the larger constant is on the RHS.
1415 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1416 SetCondInst *LHS = cast<SetCondInst>(Op0);
1417 if (cast<ConstantBool>(Cmp)->getValue()) {
1418 std::swap(LHS, RHS);
1419 std::swap(LHSCst, RHSCst);
1420 std::swap(LHSCC, RHSCC);
1421 }
1422
1423 // At this point, we know we have have two setcc instructions
1424 // comparing a value against two constants and and'ing the result
1425 // together. Because of the above check, we know that we only have
1426 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1427 // FoldSetCCLogical check above), that the two constants are not
1428 // equal.
1429 assert(LHSCst != RHSCst && "Compares not folded above?");
1430
1431 switch (LHSCC) {
1432 default: assert(0 && "Unknown integer condition code!");
1433 case Instruction::SetEQ:
1434 switch (RHSCC) {
1435 default: assert(0 && "Unknown integer condition code!");
1436 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1437 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1438 return ReplaceInstUsesWith(I, ConstantBool::False);
1439 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1440 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1441 return ReplaceInstUsesWith(I, LHS);
1442 }
1443 case Instruction::SetNE:
1444 switch (RHSCC) {
1445 default: assert(0 && "Unknown integer condition code!");
1446 case Instruction::SetLT:
1447 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1448 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1449 break; // (X != 13 & X < 15) -> no change
1450 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1451 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1452 return ReplaceInstUsesWith(I, RHS);
1453 case Instruction::SetNE:
1454 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1455 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1456 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1457 LHSVal->getName()+".off");
1458 InsertNewInstBefore(Add, I);
1459 const Type *UnsType = Add->getType()->getUnsignedVersion();
1460 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1461 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1462 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1463 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1464 }
1465 break; // (X != 13 & X != 15) -> no change
1466 }
1467 break;
1468 case Instruction::SetLT:
1469 switch (RHSCC) {
1470 default: assert(0 && "Unknown integer condition code!");
1471 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1472 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1473 return ReplaceInstUsesWith(I, ConstantBool::False);
1474 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1475 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1476 return ReplaceInstUsesWith(I, LHS);
1477 }
1478 case Instruction::SetGT:
1479 switch (RHSCC) {
1480 default: assert(0 && "Unknown integer condition code!");
1481 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1482 return ReplaceInstUsesWith(I, LHS);
1483 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1484 return ReplaceInstUsesWith(I, RHS);
1485 case Instruction::SetNE:
1486 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1487 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1488 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001489 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1490 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001491 }
1492 }
1493 }
1494 }
1495
Chris Lattner113f4f42002-06-25 16:13:24 +00001496 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001497}
1498
Chris Lattner113f4f42002-06-25 16:13:24 +00001499Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001500 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001501 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001502
Chris Lattner81a7a232004-10-16 18:11:37 +00001503 if (isa<UndefValue>(Op1))
1504 return ReplaceInstUsesWith(I, // X | undef -> -1
1505 ConstantIntegral::getAllOnesValue(I.getType()));
1506
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001507 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001508 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1509 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001510
1511 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001512 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001513 if (RHS->isAllOnesValue())
1514 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001515
Chris Lattnerd4252a72004-07-30 07:50:03 +00001516 ConstantInt *C1; Value *X;
1517 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1518 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1519 std::string Op0Name = Op0->getName(); Op0->setName("");
1520 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1521 InsertNewInstBefore(Or, I);
1522 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1523 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001524
Chris Lattnerd4252a72004-07-30 07:50:03 +00001525 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1526 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1527 std::string Op0Name = Op0->getName(); Op0->setName("");
1528 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1529 InsertNewInstBefore(Or, I);
1530 return BinaryOperator::createXor(Or,
1531 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001532 }
Chris Lattner183b3362004-04-09 19:05:30 +00001533
1534 // Try to fold constant and into select arguments.
1535 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1536 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1537 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001538 if (isa<PHINode>(Op0))
1539 if (Instruction *NV = FoldOpIntoPhi(I))
1540 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001541 }
1542
Chris Lattner812aab72003-08-12 19:11:07 +00001543 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001544 Value *A, *B; ConstantInt *C1, *C2;
1545 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1546 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1547 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001548
Chris Lattnerd4252a72004-07-30 07:50:03 +00001549 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1550 if (A == Op1) // ~A | A == -1
1551 return ReplaceInstUsesWith(I,
1552 ConstantIntegral::getAllOnesValue(I.getType()));
1553 } else {
1554 A = 0;
1555 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001556
Chris Lattnerd4252a72004-07-30 07:50:03 +00001557 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1558 if (Op0 == B)
1559 return ReplaceInstUsesWith(I,
1560 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001561
Misha Brukman9c003d82004-07-30 12:50:08 +00001562 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001563 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1564 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1565 I.getName()+".demorgan"), I);
1566 return BinaryOperator::createNot(And);
1567 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001568 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001569
Chris Lattner3ac7c262003-08-13 20:16:26 +00001570 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001571 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001572 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1573 return R;
1574
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001575 Value *LHSVal, *RHSVal;
1576 ConstantInt *LHSCst, *RHSCst;
1577 Instruction::BinaryOps LHSCC, RHSCC;
1578 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1579 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1580 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1581 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1582 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1583 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1584 // Ensure that the larger constant is on the RHS.
1585 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1586 SetCondInst *LHS = cast<SetCondInst>(Op0);
1587 if (cast<ConstantBool>(Cmp)->getValue()) {
1588 std::swap(LHS, RHS);
1589 std::swap(LHSCst, RHSCst);
1590 std::swap(LHSCC, RHSCC);
1591 }
1592
1593 // At this point, we know we have have two setcc instructions
1594 // comparing a value against two constants and or'ing the result
1595 // together. Because of the above check, we know that we only have
1596 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1597 // FoldSetCCLogical check above), that the two constants are not
1598 // equal.
1599 assert(LHSCst != RHSCst && "Compares not folded above?");
1600
1601 switch (LHSCC) {
1602 default: assert(0 && "Unknown integer condition code!");
1603 case Instruction::SetEQ:
1604 switch (RHSCC) {
1605 default: assert(0 && "Unknown integer condition code!");
1606 case Instruction::SetEQ:
1607 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1608 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1609 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1610 LHSVal->getName()+".off");
1611 InsertNewInstBefore(Add, I);
1612 const Type *UnsType = Add->getType()->getUnsignedVersion();
1613 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1614 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1615 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1616 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1617 }
1618 break; // (X == 13 | X == 15) -> no change
1619
1620 case Instruction::SetGT:
1621 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1622 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1623 break; // (X == 13 | X > 15) -> no change
1624 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1625 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1626 return ReplaceInstUsesWith(I, RHS);
1627 }
1628 break;
1629 case Instruction::SetNE:
1630 switch (RHSCC) {
1631 default: assert(0 && "Unknown integer condition code!");
1632 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1633 return ReplaceInstUsesWith(I, RHS);
1634 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1635 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1636 return ReplaceInstUsesWith(I, LHS);
1637 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1638 return ReplaceInstUsesWith(I, ConstantBool::True);
1639 }
1640 break;
1641 case Instruction::SetLT:
1642 switch (RHSCC) {
1643 default: assert(0 && "Unknown integer condition code!");
1644 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1645 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001646 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1647 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001648 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1649 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1650 return ReplaceInstUsesWith(I, RHS);
1651 }
1652 break;
1653 case Instruction::SetGT:
1654 switch (RHSCC) {
1655 default: assert(0 && "Unknown integer condition code!");
1656 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1657 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1658 return ReplaceInstUsesWith(I, LHS);
1659 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1660 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1661 return ReplaceInstUsesWith(I, ConstantBool::True);
1662 }
1663 }
1664 }
1665 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001666 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001667}
1668
Chris Lattnerc2076352004-02-16 01:20:27 +00001669// XorSelf - Implements: X ^ X --> 0
1670struct XorSelf {
1671 Value *RHS;
1672 XorSelf(Value *rhs) : RHS(rhs) {}
1673 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1674 Instruction *apply(BinaryOperator &Xor) const {
1675 return &Xor;
1676 }
1677};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001678
1679
Chris Lattner113f4f42002-06-25 16:13:24 +00001680Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001681 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001682 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001683
Chris Lattner81a7a232004-10-16 18:11:37 +00001684 if (isa<UndefValue>(Op1))
1685 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1686
Chris Lattnerc2076352004-02-16 01:20:27 +00001687 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1688 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1689 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001690 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001691 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001692
Chris Lattner97638592003-07-23 21:37:07 +00001693 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001694 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001695 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001696 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001697
Chris Lattner97638592003-07-23 21:37:07 +00001698 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001699 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001700 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001701 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001702 return new SetCondInst(SCI->getInverseCondition(),
1703 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001704
Chris Lattner8f2f5982003-11-05 01:06:05 +00001705 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001706 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1707 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001708 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1709 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001710 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001711 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001712 }
Chris Lattner023a4832004-06-18 06:07:51 +00001713
1714 // ~(~X & Y) --> (X | ~Y)
1715 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1716 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1717 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1718 Instruction *NotY =
1719 BinaryOperator::createNot(Op0I->getOperand(1),
1720 Op0I->getOperand(1)->getName()+".not");
1721 InsertNewInstBefore(NotY, I);
1722 return BinaryOperator::createOr(Op0NotVal, NotY);
1723 }
1724 }
Chris Lattner97638592003-07-23 21:37:07 +00001725
1726 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001727 switch (Op0I->getOpcode()) {
1728 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001729 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001730 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001731 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1732 return BinaryOperator::createSub(
1733 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001734 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001735 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001736 }
Chris Lattnere5806662003-11-04 23:50:51 +00001737 break;
1738 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001739 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001740 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1741 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001742 break;
1743 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001744 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001745 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001746 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001747 break;
1748 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001749 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001750 }
Chris Lattner183b3362004-04-09 19:05:30 +00001751
1752 // Try to fold constant and into select arguments.
1753 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1754 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1755 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001756 if (isa<PHINode>(Op0))
1757 if (Instruction *NV = FoldOpIntoPhi(I))
1758 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001759 }
1760
Chris Lattnerbb74e222003-03-10 23:06:50 +00001761 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001762 if (X == Op1)
1763 return ReplaceInstUsesWith(I,
1764 ConstantIntegral::getAllOnesValue(I.getType()));
1765
Chris Lattnerbb74e222003-03-10 23:06:50 +00001766 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001767 if (X == Op0)
1768 return ReplaceInstUsesWith(I,
1769 ConstantIntegral::getAllOnesValue(I.getType()));
1770
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001771 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001772 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001773 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1774 cast<BinaryOperator>(Op1I)->swapOperands();
1775 I.swapOperands();
1776 std::swap(Op0, Op1);
1777 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1778 I.swapOperands();
1779 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001780 }
1781 } else if (Op1I->getOpcode() == Instruction::Xor) {
1782 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1783 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1784 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1785 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1786 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001787
1788 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001789 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001790 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1791 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001792 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001793 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1794 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001795 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001796 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001797 } else if (Op0I->getOpcode() == Instruction::Xor) {
1798 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1799 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1800 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1801 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001802 }
1803
Chris Lattner7aa2d472004-08-01 19:42:59 +00001804 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001805 Value *A, *B; ConstantInt *C1, *C2;
1806 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1807 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001808 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001809 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001810
Chris Lattner3ac7c262003-08-13 20:16:26 +00001811 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1812 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1813 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1814 return R;
1815
Chris Lattner113f4f42002-06-25 16:13:24 +00001816 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001817}
1818
Chris Lattner6862fbd2004-09-29 17:40:11 +00001819/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1820/// overflowed for this type.
1821static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1822 ConstantInt *In2) {
1823 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1824 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1825}
1826
1827static bool isPositive(ConstantInt *C) {
1828 return cast<ConstantSInt>(C)->getValue() >= 0;
1829}
1830
1831/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1832/// overflowed for this type.
1833static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1834 ConstantInt *In2) {
1835 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1836
1837 if (In1->getType()->isUnsigned())
1838 return cast<ConstantUInt>(Result)->getValue() <
1839 cast<ConstantUInt>(In1)->getValue();
1840 if (isPositive(In1) != isPositive(In2))
1841 return false;
1842 if (isPositive(In1))
1843 return cast<ConstantSInt>(Result)->getValue() <
1844 cast<ConstantSInt>(In1)->getValue();
1845 return cast<ConstantSInt>(Result)->getValue() >
1846 cast<ConstantSInt>(In1)->getValue();
1847}
1848
Chris Lattner113f4f42002-06-25 16:13:24 +00001849Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001850 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001851 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1852 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001853
1854 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001855 if (Op0 == Op1)
1856 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001857
Chris Lattner81a7a232004-10-16 18:11:37 +00001858 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1859 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1860
Chris Lattnerd07283a2003-08-13 05:38:46 +00001861 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1862 if (isa<ConstantPointerNull>(Op1) &&
1863 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001864 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1865
Chris Lattnerd07283a2003-08-13 05:38:46 +00001866
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001867 // setcc's with boolean values can always be turned into bitwise operations
1868 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001869 switch (I.getOpcode()) {
1870 default: assert(0 && "Invalid setcc instruction!");
1871 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001872 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001873 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001874 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001875 }
Chris Lattner4456da62004-08-11 00:50:51 +00001876 case Instruction::SetNE:
1877 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001878
Chris Lattner4456da62004-08-11 00:50:51 +00001879 case Instruction::SetGT:
1880 std::swap(Op0, Op1); // Change setgt -> setlt
1881 // FALL THROUGH
1882 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1883 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1884 InsertNewInstBefore(Not, I);
1885 return BinaryOperator::createAnd(Not, Op1);
1886 }
1887 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001888 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001889 // FALL THROUGH
1890 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1891 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1892 InsertNewInstBefore(Not, I);
1893 return BinaryOperator::createOr(Not, Op1);
1894 }
1895 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001896 }
1897
Chris Lattner2dd01742004-06-09 04:24:29 +00001898 // See if we are doing a comparison between a constant and an instruction that
1899 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001900 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001901 // Check to see if we are comparing against the minimum or maximum value...
1902 if (CI->isMinValue()) {
1903 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1904 return ReplaceInstUsesWith(I, ConstantBool::False);
1905 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1906 return ReplaceInstUsesWith(I, ConstantBool::True);
1907 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1908 return BinaryOperator::createSetEQ(Op0, Op1);
1909 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1910 return BinaryOperator::createSetNE(Op0, Op1);
1911
1912 } else if (CI->isMaxValue()) {
1913 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1914 return ReplaceInstUsesWith(I, ConstantBool::False);
1915 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1916 return ReplaceInstUsesWith(I, ConstantBool::True);
1917 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1918 return BinaryOperator::createSetEQ(Op0, Op1);
1919 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1920 return BinaryOperator::createSetNE(Op0, Op1);
1921
1922 // Comparing against a value really close to min or max?
1923 } else if (isMinValuePlusOne(CI)) {
1924 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1925 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1926 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1927 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1928
1929 } else if (isMaxValueMinusOne(CI)) {
1930 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1931 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1932 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1933 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1934 }
1935
1936 // If we still have a setle or setge instruction, turn it into the
1937 // appropriate setlt or setgt instruction. Since the border cases have
1938 // already been handled above, this requires little checking.
1939 //
1940 if (I.getOpcode() == Instruction::SetLE)
1941 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1942 if (I.getOpcode() == Instruction::SetGE)
1943 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1944
Chris Lattnere1e10e12004-05-25 06:32:08 +00001945 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001946 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001947 case Instruction::PHI:
1948 if (Instruction *NV = FoldOpIntoPhi(I))
1949 return NV;
1950 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001951 case Instruction::And:
1952 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1953 LHSI->getOperand(0)->hasOneUse()) {
1954 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1955 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1956 // happens a LOT in code produced by the C front-end, for bitfield
1957 // access.
1958 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1959 ConstantUInt *ShAmt;
1960 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1961 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1962 const Type *Ty = LHSI->getType();
1963
1964 // We can fold this as long as we can't shift unknown bits
1965 // into the mask. This can only happen with signed shift
1966 // rights, as they sign-extend.
1967 if (ShAmt) {
1968 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001969 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001970 if (!CanFold) {
1971 // To test for the bad case of the signed shr, see if any
1972 // of the bits shifted in could be tested after the mask.
1973 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001974 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001975 Constant *ShVal =
1976 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1977 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1978 CanFold = true;
1979 }
1980
1981 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001982 Constant *NewCst;
1983 if (Shift->getOpcode() == Instruction::Shl)
1984 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1985 else
1986 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001987
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001988 // Check to see if we are shifting out any of the bits being
1989 // compared.
1990 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1991 // If we shifted bits out, the fold is not going to work out.
1992 // As a special case, check to see if this means that the
1993 // result is always true or false now.
1994 if (I.getOpcode() == Instruction::SetEQ)
1995 return ReplaceInstUsesWith(I, ConstantBool::False);
1996 if (I.getOpcode() == Instruction::SetNE)
1997 return ReplaceInstUsesWith(I, ConstantBool::True);
1998 } else {
1999 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002000 Constant *NewAndCST;
2001 if (Shift->getOpcode() == Instruction::Shl)
2002 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2003 else
2004 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2005 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002006 LHSI->setOperand(0, Shift->getOperand(0));
2007 WorkList.push_back(Shift); // Shift is dead.
2008 AddUsesToWorkList(I);
2009 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002010 }
2011 }
Chris Lattner35167c32004-06-09 07:59:58 +00002012 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002013 }
2014 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002015
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002016 case Instruction::Cast: { // (setcc (cast X to larger), CI)
2017 const Type *SrcTy = LHSI->getOperand(0)->getType();
2018 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00002019 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002020 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00002021 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002022 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
2023 if (SrcBits < DestBits) {
2024 // Check to see if the comparison is always true or false.
2025 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2026 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
2027 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
2028 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
2029 Min = ConstantExpr::getCast(Min, LHSI->getType());
2030 Max = ConstantExpr::getCast(Max, LHSI->getType());
2031 switch (I.getOpcode()) {
2032 default: assert(0 && "unknown integer comparison");
2033 case Instruction::SetEQ:
2034 return ReplaceInstUsesWith(I, ConstantBool::False);
2035 case Instruction::SetNE:
2036 return ReplaceInstUsesWith(I, ConstantBool::True);
2037 case Instruction::SetLT:
2038 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002039 case Instruction::SetGT:
2040 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002041 }
2042 }
2043
2044 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2045 ConstantExpr::getCast(CI, SrcTy));
2046 }
2047 }
2048 break;
2049 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00002050 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2051 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2052 switch (I.getOpcode()) {
2053 default: break;
2054 case Instruction::SetEQ:
2055 case Instruction::SetNE: {
2056 // If we are comparing against bits always shifted out, the
2057 // comparison cannot succeed.
2058 Constant *Comp =
2059 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2060 if (Comp != CI) {// Comparing against a bit that we know is zero.
2061 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2062 Constant *Cst = ConstantBool::get(IsSetNE);
2063 return ReplaceInstUsesWith(I, Cst);
2064 }
2065
2066 if (LHSI->hasOneUse()) {
2067 // Otherwise strength reduce the shift into an and.
2068 unsigned ShAmtVal = ShAmt->getValue();
2069 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2070 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2071
2072 Constant *Mask;
2073 if (CI->getType()->isUnsigned()) {
2074 Mask = ConstantUInt::get(CI->getType(), Val);
2075 } else if (ShAmtVal != 0) {
2076 Mask = ConstantSInt::get(CI->getType(), Val);
2077 } else {
2078 Mask = ConstantInt::getAllOnesValue(CI->getType());
2079 }
2080
2081 Instruction *AndI =
2082 BinaryOperator::createAnd(LHSI->getOperand(0),
2083 Mask, LHSI->getName()+".mask");
2084 Value *And = InsertNewInstBefore(AndI, I);
2085 return new SetCondInst(I.getOpcode(), And,
2086 ConstantExpr::getUShr(CI, ShAmt));
2087 }
2088 }
2089 }
2090 }
2091 break;
2092
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002093 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002094 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002095 switch (I.getOpcode()) {
2096 default: break;
2097 case Instruction::SetEQ:
2098 case Instruction::SetNE: {
2099 // If we are comparing against bits always shifted out, the
2100 // comparison cannot succeed.
2101 Constant *Comp =
2102 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2103
2104 if (Comp != CI) {// Comparing against a bit that we know is zero.
2105 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2106 Constant *Cst = ConstantBool::get(IsSetNE);
2107 return ReplaceInstUsesWith(I, Cst);
2108 }
2109
2110 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002111 unsigned ShAmtVal = ShAmt->getValue();
2112
Chris Lattner1023b872004-09-27 16:18:50 +00002113 // Otherwise strength reduce the shift into an and.
2114 uint64_t Val = ~0ULL; // All ones.
2115 Val <<= ShAmtVal; // Shift over to the right spot.
2116
2117 Constant *Mask;
2118 if (CI->getType()->isUnsigned()) {
2119 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2120 Val &= (1ULL << TypeBits)-1;
2121 Mask = ConstantUInt::get(CI->getType(), Val);
2122 } else {
2123 Mask = ConstantSInt::get(CI->getType(), Val);
2124 }
2125
2126 Instruction *AndI =
2127 BinaryOperator::createAnd(LHSI->getOperand(0),
2128 Mask, LHSI->getName()+".mask");
2129 Value *And = InsertNewInstBefore(AndI, I);
2130 return new SetCondInst(I.getOpcode(), And,
2131 ConstantExpr::getShl(CI, ShAmt));
2132 }
2133 break;
2134 }
2135 }
2136 }
2137 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002138
Chris Lattner6862fbd2004-09-29 17:40:11 +00002139 case Instruction::Div:
2140 // Fold: (div X, C1) op C2 -> range check
2141 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2142 // Fold this div into the comparison, producing a range check.
2143 // Determine, based on the divide type, what the range is being
2144 // checked. If there is an overflow on the low or high side, remember
2145 // it, otherwise compute the range [low, hi) bounding the new value.
2146 bool LoOverflow = false, HiOverflow = 0;
2147 ConstantInt *LoBound = 0, *HiBound = 0;
2148
2149 ConstantInt *Prod;
2150 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2151
Chris Lattnera92af962004-10-11 19:40:04 +00002152 Instruction::BinaryOps Opcode = I.getOpcode();
2153
Chris Lattner6862fbd2004-09-29 17:40:11 +00002154 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2155 } else if (LHSI->getType()->isUnsigned()) { // udiv
2156 LoBound = Prod;
2157 LoOverflow = ProdOV;
2158 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2159 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2160 if (CI->isNullValue()) { // (X / pos) op 0
2161 // Can't overflow.
2162 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2163 HiBound = DivRHS;
2164 } else if (isPositive(CI)) { // (X / pos) op pos
2165 LoBound = Prod;
2166 LoOverflow = ProdOV;
2167 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2168 } else { // (X / pos) op neg
2169 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2170 LoOverflow = AddWithOverflow(LoBound, Prod,
2171 cast<ConstantInt>(DivRHSH));
2172 HiBound = Prod;
2173 HiOverflow = ProdOV;
2174 }
2175 } else { // Divisor is < 0.
2176 if (CI->isNullValue()) { // (X / neg) op 0
2177 LoBound = AddOne(DivRHS);
2178 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2179 } else if (isPositive(CI)) { // (X / neg) op pos
2180 HiOverflow = LoOverflow = ProdOV;
2181 if (!LoOverflow)
2182 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2183 HiBound = AddOne(Prod);
2184 } else { // (X / neg) op neg
2185 LoBound = Prod;
2186 LoOverflow = HiOverflow = ProdOV;
2187 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2188 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002189
Chris Lattnera92af962004-10-11 19:40:04 +00002190 // Dividing by a negate swaps the condition.
2191 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002192 }
2193
2194 if (LoBound) {
2195 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002196 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002197 default: assert(0 && "Unhandled setcc opcode!");
2198 case Instruction::SetEQ:
2199 if (LoOverflow && HiOverflow)
2200 return ReplaceInstUsesWith(I, ConstantBool::False);
2201 else if (HiOverflow)
2202 return new SetCondInst(Instruction::SetGE, X, LoBound);
2203 else if (LoOverflow)
2204 return new SetCondInst(Instruction::SetLT, X, HiBound);
2205 else
2206 return InsertRangeTest(X, LoBound, HiBound, true, I);
2207 case Instruction::SetNE:
2208 if (LoOverflow && HiOverflow)
2209 return ReplaceInstUsesWith(I, ConstantBool::True);
2210 else if (HiOverflow)
2211 return new SetCondInst(Instruction::SetLT, X, LoBound);
2212 else if (LoOverflow)
2213 return new SetCondInst(Instruction::SetGE, X, HiBound);
2214 else
2215 return InsertRangeTest(X, LoBound, HiBound, false, I);
2216 case Instruction::SetLT:
2217 if (LoOverflow)
2218 return ReplaceInstUsesWith(I, ConstantBool::False);
2219 return new SetCondInst(Instruction::SetLT, X, LoBound);
2220 case Instruction::SetGT:
2221 if (HiOverflow)
2222 return ReplaceInstUsesWith(I, ConstantBool::False);
2223 return new SetCondInst(Instruction::SetGE, X, HiBound);
2224 }
2225 }
2226 }
2227 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002228 case Instruction::Select:
2229 // If either operand of the select is a constant, we can fold the
2230 // comparison into the select arms, which will cause one to be
2231 // constant folded and the select turned into a bitwise or.
2232 Value *Op1 = 0, *Op2 = 0;
2233 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002234 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002235 // Fold the known value into the constant operand.
2236 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2237 // Insert a new SetCC of the other select operand.
2238 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002239 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002240 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002241 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002242 // Fold the known value into the constant operand.
2243 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2244 // Insert a new SetCC of the other select operand.
2245 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002246 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002247 I.getName()), I);
2248 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002249 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002250
2251 if (Op1)
2252 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2253 break;
2254 }
2255
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002256 // Simplify seteq and setne instructions...
2257 if (I.getOpcode() == Instruction::SetEQ ||
2258 I.getOpcode() == Instruction::SetNE) {
2259 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2260
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002261 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002262 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002263 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2264 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002265 case Instruction::Rem:
2266 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2267 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2268 BO->hasOneUse() &&
2269 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2270 if (unsigned L2 =
2271 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2272 const Type *UTy = BO->getType()->getUnsignedVersion();
2273 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2274 UTy, "tmp"), I);
2275 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2276 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2277 RHSCst, BO->getName()), I);
2278 return BinaryOperator::create(I.getOpcode(), NewRem,
2279 Constant::getNullValue(UTy));
2280 }
2281 break;
2282
Chris Lattnerc992add2003-08-13 05:33:12 +00002283 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002284 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2285 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002286 if (BO->hasOneUse())
2287 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2288 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002289 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002290 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2291 // efficiently invertible, or if the add has just this one use.
2292 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002293
Chris Lattnerc992add2003-08-13 05:33:12 +00002294 if (Value *NegVal = dyn_castNegVal(BOp1))
2295 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2296 else if (Value *NegVal = dyn_castNegVal(BOp0))
2297 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002298 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002299 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2300 BO->setName("");
2301 InsertNewInstBefore(Neg, I);
2302 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2303 }
2304 }
2305 break;
2306 case Instruction::Xor:
2307 // For the xor case, we can xor two constants together, eliminating
2308 // the explicit xor.
2309 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2310 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002311 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002312
2313 // FALLTHROUGH
2314 case Instruction::Sub:
2315 // Replace (([sub|xor] A, B) != 0) with (A != B)
2316 if (CI->isNullValue())
2317 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2318 BO->getOperand(1));
2319 break;
2320
2321 case Instruction::Or:
2322 // If bits are being or'd in that are not present in the constant we
2323 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002324 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002325 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002326 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002327 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002328 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002329 break;
2330
2331 case Instruction::And:
2332 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002333 // If bits are being compared against that are and'd out, then the
2334 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002335 if (!ConstantExpr::getAnd(CI,
2336 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002337 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002338
Chris Lattner35167c32004-06-09 07:59:58 +00002339 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002340 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002341 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2342 Instruction::SetNE, Op0,
2343 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002344
Chris Lattnerc992add2003-08-13 05:33:12 +00002345 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2346 // to be a signed value as appropriate.
2347 if (isSignBit(BOC)) {
2348 Value *X = BO->getOperand(0);
2349 // If 'X' is not signed, insert a cast now...
2350 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002351 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002352 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002353 }
2354 return new SetCondInst(isSetNE ? Instruction::SetLT :
2355 Instruction::SetGE, X,
2356 Constant::getNullValue(X->getType()));
2357 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002358
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002359 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002360 if (CI->isNullValue() && isHighOnes(BOC)) {
2361 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002362 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002363
2364 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002365 if (NegX->getType()->isSigned()) {
2366 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2367 X = InsertCastBefore(X, DestTy, I);
2368 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002369 }
2370
2371 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002372 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002373 }
2374
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002375 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002376 default: break;
2377 }
2378 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002379 } else { // Not a SetEQ/SetNE
2380 // If the LHS is a cast from an integral value of the same size,
2381 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2382 Value *CastOp = Cast->getOperand(0);
2383 const Type *SrcTy = CastOp->getType();
2384 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2385 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2386 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2387 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2388 "Source and destination signednesses should differ!");
2389 if (Cast->getType()->isSigned()) {
2390 // If this is a signed comparison, check for comparisons in the
2391 // vicinity of zero.
2392 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2393 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002394 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002395 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2396 else if (I.getOpcode() == Instruction::SetGT &&
2397 cast<ConstantSInt>(CI)->getValue() == -1)
2398 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002399 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002400 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2401 } else {
2402 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2403 if (I.getOpcode() == Instruction::SetLT &&
2404 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2405 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002406 return BinaryOperator::createSetGT(CastOp,
2407 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002408 else if (I.getOpcode() == Instruction::SetGT &&
2409 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2410 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002411 return BinaryOperator::createSetLT(CastOp,
2412 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002413 }
2414 }
2415 }
Chris Lattnere967b342003-06-04 05:10:11 +00002416 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002417 }
2418
Chris Lattner16930792003-11-03 04:25:02 +00002419 // Test to see if the operands of the setcc are casted versions of other
2420 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002421 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2422 Value *CastOp0 = CI->getOperand(0);
2423 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002424 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002425 (I.getOpcode() == Instruction::SetEQ ||
2426 I.getOpcode() == Instruction::SetNE)) {
2427 // We keep moving the cast from the left operand over to the right
2428 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002429 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002430
2431 // If operand #1 is a cast instruction, see if we can eliminate it as
2432 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002433 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2434 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002435 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002436 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002437
2438 // If Op1 is a constant, we can fold the cast into the constant.
2439 if (Op1->getType() != Op0->getType())
2440 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2441 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2442 } else {
2443 // Otherwise, cast the RHS right before the setcc
2444 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2445 InsertNewInstBefore(cast<Instruction>(Op1), I);
2446 }
2447 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2448 }
2449
Chris Lattner6444c372003-11-03 05:17:03 +00002450 // Handle the special case of: setcc (cast bool to X), <cst>
2451 // This comes up when you have code like
2452 // int X = A < B;
2453 // if (X) ...
2454 // For generality, we handle any zero-extension of any operand comparison
2455 // with a constant.
2456 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2457 const Type *SrcTy = CastOp0->getType();
2458 const Type *DestTy = Op0->getType();
2459 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2460 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2461 // Ok, we have an expansion of operand 0 into a new type. Get the
2462 // constant value, masink off bits which are not set in the RHS. These
2463 // could be set if the destination value is signed.
2464 uint64_t ConstVal = ConstantRHS->getRawValue();
2465 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2466
2467 // If the constant we are comparing it with has high bits set, which
2468 // don't exist in the original value, the values could never be equal,
2469 // because the source would be zero extended.
2470 unsigned SrcBits =
2471 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002472 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2473 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002474 switch (I.getOpcode()) {
2475 default: assert(0 && "Unknown comparison type!");
2476 case Instruction::SetEQ:
2477 return ReplaceInstUsesWith(I, ConstantBool::False);
2478 case Instruction::SetNE:
2479 return ReplaceInstUsesWith(I, ConstantBool::True);
2480 case Instruction::SetLT:
2481 case Instruction::SetLE:
2482 if (DestTy->isSigned() && HasSignBit)
2483 return ReplaceInstUsesWith(I, ConstantBool::False);
2484 return ReplaceInstUsesWith(I, ConstantBool::True);
2485 case Instruction::SetGT:
2486 case Instruction::SetGE:
2487 if (DestTy->isSigned() && HasSignBit)
2488 return ReplaceInstUsesWith(I, ConstantBool::True);
2489 return ReplaceInstUsesWith(I, ConstantBool::False);
2490 }
2491 }
2492
2493 // Otherwise, we can replace the setcc with a setcc of the smaller
2494 // operand value.
2495 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2496 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2497 }
2498 }
2499 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002500 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002501}
2502
2503
2504
Chris Lattnere8d6c602003-03-10 19:16:08 +00002505Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002506 assert(I.getOperand(1)->getType() == Type::UByteTy);
2507 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002508 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002509
2510 // shl X, 0 == X and shr X, 0 == X
2511 // shl 0, X == 0 and shr 0, X == 0
2512 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002513 Op0 == Constant::getNullValue(Op0->getType()))
2514 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002515
Chris Lattner81a7a232004-10-16 18:11:37 +00002516 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2517 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00002518 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00002519 else // undef << X -> 0 AND undef >>u X -> 0
2520 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2521 }
2522 if (isa<UndefValue>(Op1)) {
2523 if (isLeftShift || I.getType()->isUnsigned())
2524 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2525 else
2526 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2527 }
2528
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002529 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2530 if (!isLeftShift)
2531 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2532 if (CSI->isAllOnesValue())
2533 return ReplaceInstUsesWith(I, CSI);
2534
Chris Lattner183b3362004-04-09 19:05:30 +00002535 // Try to fold constant and into select arguments.
2536 if (isa<Constant>(Op0))
2537 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2538 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2539 return R;
2540
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002541 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002542 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2543 // of a signed value.
2544 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002545 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002546 if (CUI->getValue() >= TypeBits) {
2547 if (!Op0->getType()->isSigned() || isLeftShift)
2548 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2549 else {
2550 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2551 return &I;
2552 }
2553 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002554
Chris Lattnerede3fe02003-08-13 04:18:28 +00002555 // ((X*C1) << C2) == (X * (C1 << C2))
2556 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2557 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2558 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002559 return BinaryOperator::createMul(BO->getOperand(0),
2560 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002561
Chris Lattner183b3362004-04-09 19:05:30 +00002562 // Try to fold constant and into select arguments.
2563 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2564 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2565 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002566 if (isa<PHINode>(Op0))
2567 if (Instruction *NV = FoldOpIntoPhi(I))
2568 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002569
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002570 // If the operand is an bitwise operator with a constant RHS, and the
2571 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002572 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002573 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2574 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2575 bool isValid = true; // Valid only for And, Or, Xor
2576 bool highBitSet = false; // Transform if high bit of constant set?
2577
2578 switch (Op0BO->getOpcode()) {
2579 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002580 case Instruction::Add:
2581 isValid = isLeftShift;
2582 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002583 case Instruction::Or:
2584 case Instruction::Xor:
2585 highBitSet = false;
2586 break;
2587 case Instruction::And:
2588 highBitSet = true;
2589 break;
2590 }
2591
2592 // If this is a signed shift right, and the high bit is modified
2593 // by the logical operation, do not perform the transformation.
2594 // The highBitSet boolean indicates the value of the high bit of
2595 // the constant which would cause it to be modified for this
2596 // operation.
2597 //
2598 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2599 uint64_t Val = Op0C->getRawValue();
2600 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2601 }
2602
2603 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002604 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002605
2606 Instruction *NewShift =
2607 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2608 Op0BO->getName());
2609 Op0BO->setName("");
2610 InsertNewInstBefore(NewShift, I);
2611
2612 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2613 NewRHS);
2614 }
2615 }
2616
Chris Lattner3204d4e2003-07-24 17:52:58 +00002617 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002618 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002619 if (ConstantUInt *ShiftAmt1C =
2620 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002621 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2622 unsigned ShiftAmt2 = CUI->getValue();
2623
2624 // Check for (A << c1) << c2 and (A >> c1) >> c2
2625 if (I.getOpcode() == Op0SI->getOpcode()) {
2626 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002627 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2628 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002629 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2630 ConstantUInt::get(Type::UByteTy, Amt));
2631 }
2632
Chris Lattnerab780df2003-07-24 18:38:56 +00002633 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2634 // signed types, we can only support the (A >> c1) << c2 configuration,
2635 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002636 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002637 // Calculate bitmask for what gets shifted off the edge...
2638 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002639 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002640 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002641 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002642 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002643
2644 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002645 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2646 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002647 InsertNewInstBefore(Mask, I);
2648
2649 // Figure out what flavor of shift we should use...
2650 if (ShiftAmt1 == ShiftAmt2)
2651 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2652 else if (ShiftAmt1 < ShiftAmt2) {
2653 return new ShiftInst(I.getOpcode(), Mask,
2654 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2655 } else {
2656 return new ShiftInst(Op0SI->getOpcode(), Mask,
2657 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2658 }
2659 }
2660 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002661 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002662
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002663 return 0;
2664}
2665
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002666enum CastType {
2667 Noop = 0,
2668 Truncate = 1,
2669 Signext = 2,
2670 Zeroext = 3
2671};
2672
2673/// getCastType - In the future, we will split the cast instruction into these
2674/// various types. Until then, we have to do the analysis here.
2675static CastType getCastType(const Type *Src, const Type *Dest) {
2676 assert(Src->isIntegral() && Dest->isIntegral() &&
2677 "Only works on integral types!");
2678 unsigned SrcSize = Src->getPrimitiveSize()*8;
2679 if (Src == Type::BoolTy) SrcSize = 1;
2680 unsigned DestSize = Dest->getPrimitiveSize()*8;
2681 if (Dest == Type::BoolTy) DestSize = 1;
2682
2683 if (SrcSize == DestSize) return Noop;
2684 if (SrcSize > DestSize) return Truncate;
2685 if (Src->isSigned()) return Signext;
2686 return Zeroext;
2687}
2688
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002689
Chris Lattner48a44f72002-05-02 17:06:02 +00002690// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2691// instruction.
2692//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002693static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002694 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002695
Chris Lattner650b6da2002-08-02 20:00:25 +00002696 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2697 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002698 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002699 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002700 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002701
Chris Lattner4fbad962004-07-21 04:27:24 +00002702 // If we are casting between pointer and integer types, treat pointers as
2703 // integers of the appropriate size for the code below.
2704 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2705 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2706 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002707
Chris Lattner48a44f72002-05-02 17:06:02 +00002708 // Allow free casting and conversion of sizes as long as the sign doesn't
2709 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002710 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002711 CastType FirstCast = getCastType(SrcTy, MidTy);
2712 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002713
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002714 // Capture the effect of these two casts. If the result is a legal cast,
2715 // the CastType is stored here, otherwise a special code is used.
2716 static const unsigned CastResult[] = {
2717 // First cast is noop
2718 0, 1, 2, 3,
2719 // First cast is a truncate
2720 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2721 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002722 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002723 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002724 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002725 };
2726
2727 unsigned Result = CastResult[FirstCast*4+SecondCast];
2728 switch (Result) {
2729 default: assert(0 && "Illegal table value!");
2730 case 0:
2731 case 1:
2732 case 2:
2733 case 3:
2734 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2735 // truncates, we could eliminate more casts.
2736 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2737 case 4:
2738 return false; // Not possible to eliminate this here.
2739 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002740 // Sign or zero extend followed by truncate is always ok if the result
2741 // is a truncate or noop.
2742 CastType ResultCast = getCastType(SrcTy, DstTy);
2743 if (ResultCast == Noop || ResultCast == Truncate)
2744 return true;
2745 // Otherwise we are still growing the value, we are only safe if the
2746 // result will match the sign/zeroextendness of the result.
2747 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002748 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002749 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002750 return false;
2751}
2752
Chris Lattner11ffd592004-07-20 05:21:00 +00002753static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002754 if (V->getType() == Ty || isa<Constant>(V)) return false;
2755 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002756 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2757 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002758 return false;
2759 return true;
2760}
2761
2762/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2763/// InsertBefore instruction. This is specialized a bit to avoid inserting
2764/// casts that are known to not do anything...
2765///
2766Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2767 Instruction *InsertBefore) {
2768 if (V->getType() == DestTy) return V;
2769 if (Constant *C = dyn_cast<Constant>(V))
2770 return ConstantExpr::getCast(C, DestTy);
2771
2772 CastInst *CI = new CastInst(V, DestTy, V->getName());
2773 InsertNewInstBefore(CI, *InsertBefore);
2774 return CI;
2775}
Chris Lattner48a44f72002-05-02 17:06:02 +00002776
2777// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002778//
Chris Lattner113f4f42002-06-25 16:13:24 +00002779Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002780 Value *Src = CI.getOperand(0);
2781
Chris Lattner48a44f72002-05-02 17:06:02 +00002782 // If the user is casting a value to the same type, eliminate this cast
2783 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002784 if (CI.getType() == Src->getType())
2785 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002786
Chris Lattner81a7a232004-10-16 18:11:37 +00002787 if (isa<UndefValue>(Src)) // cast undef -> undef
2788 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2789
Chris Lattner48a44f72002-05-02 17:06:02 +00002790 // If casting the result of another cast instruction, try to eliminate this
2791 // one!
2792 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002793 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002794 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002795 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002796 // This instruction now refers directly to the cast's src operand. This
2797 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002798 CI.setOperand(0, CSrc->getOperand(0));
2799 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002800 }
2801
Chris Lattner650b6da2002-08-02 20:00:25 +00002802 // If this is an A->B->A cast, and we are dealing with integral types, try
2803 // to convert this into a logical 'and' instruction.
2804 //
2805 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002806 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002807 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2808 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2809 assert(CSrc->getType() != Type::ULongTy &&
2810 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002811 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002812 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002813 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002814 }
2815 }
2816
Chris Lattner03841652004-05-25 04:29:21 +00002817 // If this is a cast to bool, turn it into the appropriate setne instruction.
2818 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002819 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002820 Constant::getNullValue(CI.getOperand(0)->getType()));
2821
Chris Lattnerd0d51602003-06-21 23:12:02 +00002822 // If casting the result of a getelementptr instruction with no offset, turn
2823 // this into a cast of the original pointer!
2824 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002825 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002826 bool AllZeroOperands = true;
2827 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2828 if (!isa<Constant>(GEP->getOperand(i)) ||
2829 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2830 AllZeroOperands = false;
2831 break;
2832 }
2833 if (AllZeroOperands) {
2834 CI.setOperand(0, GEP->getOperand(0));
2835 return &CI;
2836 }
2837 }
2838
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002839 // If we are casting a malloc or alloca to a pointer to a type of the same
2840 // size, rewrite the allocation instruction to allocate the "right" type.
2841 //
2842 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002843 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002844 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2845 // Get the type really allocated and the type casted to...
2846 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002847 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002848 if (AllocElTy->isSized() && CastElTy->isSized()) {
2849 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2850 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002851
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002852 // If the allocation is for an even multiple of the cast type size
2853 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2854 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002855 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002856 std::string Name = AI->getName(); AI->setName("");
2857 AllocationInst *New;
2858 if (isa<MallocInst>(AI))
2859 New = new MallocInst(CastElTy, Amt, Name);
2860 else
2861 New = new AllocaInst(CastElTy, Amt, Name);
2862 InsertNewInstBefore(New, *AI);
2863 return ReplaceInstUsesWith(CI, New);
2864 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002865 }
2866 }
2867
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002868 if (isa<PHINode>(Src))
2869 if (Instruction *NV = FoldOpIntoPhi(CI))
2870 return NV;
2871
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002872 // If the source value is an instruction with only this use, we can attempt to
2873 // propagate the cast into the instruction. Also, only handle integral types
2874 // for now.
2875 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002876 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002877 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2878 const Type *DestTy = CI.getType();
2879 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2880 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2881
2882 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2883 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2884
2885 switch (SrcI->getOpcode()) {
2886 case Instruction::Add:
2887 case Instruction::Mul:
2888 case Instruction::And:
2889 case Instruction::Or:
2890 case Instruction::Xor:
2891 // If we are discarding information, or just changing the sign, rewrite.
2892 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2893 // Don't insert two casts if they cannot be eliminated. We allow two
2894 // casts to be inserted if the sizes are the same. This could only be
2895 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002896 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2897 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002898 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2899 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2900 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2901 ->getOpcode(), Op0c, Op1c);
2902 }
2903 }
2904 break;
2905 case Instruction::Shl:
2906 // Allow changing the sign of the source operand. Do not allow changing
2907 // the size of the shift, UNLESS the shift amount is a constant. We
2908 // mush not change variable sized shifts to a smaller size, because it
2909 // is undefined to shift more bits out than exist in the value.
2910 if (DestBitSize == SrcBitSize ||
2911 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2912 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2913 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2914 }
2915 break;
2916 }
2917 }
2918
Chris Lattner260ab202002-04-18 17:39:14 +00002919 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002920}
2921
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002922/// GetSelectFoldableOperands - We want to turn code that looks like this:
2923/// %C = or %A, %B
2924/// %D = select %cond, %C, %A
2925/// into:
2926/// %C = select %cond, %B, 0
2927/// %D = or %A, %C
2928///
2929/// Assuming that the specified instruction is an operand to the select, return
2930/// a bitmask indicating which operands of this instruction are foldable if they
2931/// equal the other incoming value of the select.
2932///
2933static unsigned GetSelectFoldableOperands(Instruction *I) {
2934 switch (I->getOpcode()) {
2935 case Instruction::Add:
2936 case Instruction::Mul:
2937 case Instruction::And:
2938 case Instruction::Or:
2939 case Instruction::Xor:
2940 return 3; // Can fold through either operand.
2941 case Instruction::Sub: // Can only fold on the amount subtracted.
2942 case Instruction::Shl: // Can only fold on the shift amount.
2943 case Instruction::Shr:
2944 return 1;
2945 default:
2946 return 0; // Cannot fold
2947 }
2948}
2949
2950/// GetSelectFoldableConstant - For the same transformation as the previous
2951/// function, return the identity constant that goes into the select.
2952static Constant *GetSelectFoldableConstant(Instruction *I) {
2953 switch (I->getOpcode()) {
2954 default: assert(0 && "This cannot happen!"); abort();
2955 case Instruction::Add:
2956 case Instruction::Sub:
2957 case Instruction::Or:
2958 case Instruction::Xor:
2959 return Constant::getNullValue(I->getType());
2960 case Instruction::Shl:
2961 case Instruction::Shr:
2962 return Constant::getNullValue(Type::UByteTy);
2963 case Instruction::And:
2964 return ConstantInt::getAllOnesValue(I->getType());
2965 case Instruction::Mul:
2966 return ConstantInt::get(I->getType(), 1);
2967 }
2968}
2969
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002970Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002971 Value *CondVal = SI.getCondition();
2972 Value *TrueVal = SI.getTrueValue();
2973 Value *FalseVal = SI.getFalseValue();
2974
2975 // select true, X, Y -> X
2976 // select false, X, Y -> Y
2977 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002978 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002979 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002980 else {
2981 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002982 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002983 }
Chris Lattner533bc492004-03-30 19:37:13 +00002984
2985 // select C, X, X -> X
2986 if (TrueVal == FalseVal)
2987 return ReplaceInstUsesWith(SI, TrueVal);
2988
Chris Lattner81a7a232004-10-16 18:11:37 +00002989 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2990 return ReplaceInstUsesWith(SI, FalseVal);
2991 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2992 return ReplaceInstUsesWith(SI, TrueVal);
2993 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2994 if (isa<Constant>(TrueVal))
2995 return ReplaceInstUsesWith(SI, TrueVal);
2996 else
2997 return ReplaceInstUsesWith(SI, FalseVal);
2998 }
2999
Chris Lattner1c631e82004-04-08 04:43:23 +00003000 if (SI.getType() == Type::BoolTy)
3001 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3002 if (C == ConstantBool::True) {
3003 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003004 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003005 } else {
3006 // Change: A = select B, false, C --> A = and !B, C
3007 Value *NotCond =
3008 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3009 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003010 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003011 }
3012 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3013 if (C == ConstantBool::False) {
3014 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003015 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003016 } else {
3017 // Change: A = select B, C, true --> A = or !B, C
3018 Value *NotCond =
3019 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3020 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003021 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003022 }
3023 }
3024
Chris Lattner183b3362004-04-09 19:05:30 +00003025 // Selecting between two integer constants?
3026 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3027 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3028 // select C, 1, 0 -> cast C to int
3029 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3030 return new CastInst(CondVal, SI.getType());
3031 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3032 // select C, 0, 1 -> cast !C to int
3033 Value *NotCond =
3034 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003035 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003036 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003037 }
Chris Lattner35167c32004-06-09 07:59:58 +00003038
3039 // If one of the constants is zero (we know they can't both be) and we
3040 // have a setcc instruction with zero, and we have an 'and' with the
3041 // non-constant value, eliminate this whole mess. This corresponds to
3042 // cases like this: ((X & 27) ? 27 : 0)
3043 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3044 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3045 if ((IC->getOpcode() == Instruction::SetEQ ||
3046 IC->getOpcode() == Instruction::SetNE) &&
3047 isa<ConstantInt>(IC->getOperand(1)) &&
3048 cast<Constant>(IC->getOperand(1))->isNullValue())
3049 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3050 if (ICA->getOpcode() == Instruction::And &&
3051 isa<ConstantInt>(ICA->getOperand(1)) &&
3052 (ICA->getOperand(1) == TrueValC ||
3053 ICA->getOperand(1) == FalseValC) &&
3054 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3055 // Okay, now we know that everything is set up, we just don't
3056 // know whether we have a setne or seteq and whether the true or
3057 // false val is the zero.
3058 bool ShouldNotVal = !TrueValC->isNullValue();
3059 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3060 Value *V = ICA;
3061 if (ShouldNotVal)
3062 V = InsertNewInstBefore(BinaryOperator::create(
3063 Instruction::Xor, V, ICA->getOperand(1)), SI);
3064 return ReplaceInstUsesWith(SI, V);
3065 }
Chris Lattner533bc492004-03-30 19:37:13 +00003066 }
Chris Lattner623fba12004-04-10 22:21:27 +00003067
3068 // See if we are selecting two values based on a comparison of the two values.
3069 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3070 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3071 // Transform (X == Y) ? X : Y -> Y
3072 if (SCI->getOpcode() == Instruction::SetEQ)
3073 return ReplaceInstUsesWith(SI, FalseVal);
3074 // Transform (X != Y) ? X : Y -> X
3075 if (SCI->getOpcode() == Instruction::SetNE)
3076 return ReplaceInstUsesWith(SI, TrueVal);
3077 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3078
3079 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3080 // Transform (X == Y) ? Y : X -> X
3081 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003082 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003083 // Transform (X != Y) ? Y : X -> Y
3084 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003085 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003086 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3087 }
3088 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003089
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003090 // See if we can fold the select into one of our operands.
3091 if (SI.getType()->isInteger()) {
3092 // See the comment above GetSelectFoldableOperands for a description of the
3093 // transformation we are doing here.
3094 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3095 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3096 !isa<Constant>(FalseVal))
3097 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3098 unsigned OpToFold = 0;
3099 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3100 OpToFold = 1;
3101 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3102 OpToFold = 2;
3103 }
3104
3105 if (OpToFold) {
3106 Constant *C = GetSelectFoldableConstant(TVI);
3107 std::string Name = TVI->getName(); TVI->setName("");
3108 Instruction *NewSel =
3109 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3110 Name);
3111 InsertNewInstBefore(NewSel, SI);
3112 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3113 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3114 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3115 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3116 else {
3117 assert(0 && "Unknown instruction!!");
3118 }
3119 }
3120 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003121
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003122 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3123 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3124 !isa<Constant>(TrueVal))
3125 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3126 unsigned OpToFold = 0;
3127 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3128 OpToFold = 1;
3129 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3130 OpToFold = 2;
3131 }
3132
3133 if (OpToFold) {
3134 Constant *C = GetSelectFoldableConstant(FVI);
3135 std::string Name = FVI->getName(); FVI->setName("");
3136 Instruction *NewSel =
3137 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3138 Name);
3139 InsertNewInstBefore(NewSel, SI);
3140 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3141 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3142 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3143 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3144 else {
3145 assert(0 && "Unknown instruction!!");
3146 }
3147 }
3148 }
3149 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003150 return 0;
3151}
3152
3153
Chris Lattner970c33a2003-06-19 17:00:31 +00003154// CallInst simplification
3155//
3156Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003157 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3158 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003159 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3160 bool Changed = false;
3161
3162 // memmove/cpy/set of zero bytes is a noop.
3163 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3164 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3165
3166 // FIXME: Increase alignment here.
3167
3168 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3169 if (CI->getRawValue() == 1) {
3170 // Replace the instruction with just byte operations. We would
3171 // transform other cases to loads/stores, but we don't know if
3172 // alignment is sufficient.
3173 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003174 }
3175
Chris Lattner00648e12004-10-12 04:52:52 +00003176 // If we have a memmove and the source operation is a constant global,
3177 // then the source and dest pointers can't alias, so we can change this
3178 // into a call to memcpy.
3179 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3180 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3181 if (GVSrc->isConstant()) {
3182 Module *M = CI.getParent()->getParent()->getParent();
3183 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3184 CI.getCalledFunction()->getFunctionType());
3185 CI.setOperand(0, MemCpy);
3186 Changed = true;
3187 }
3188
3189 if (Changed) return &CI;
3190 }
3191
Chris Lattneraec3d942003-10-07 22:32:43 +00003192 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003193}
3194
3195// InvokeInst simplification
3196//
3197Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003198 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003199}
3200
Chris Lattneraec3d942003-10-07 22:32:43 +00003201// visitCallSite - Improvements for call and invoke instructions.
3202//
3203Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003204 bool Changed = false;
3205
3206 // If the callee is a constexpr cast of a function, attempt to move the cast
3207 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003208 if (transformConstExprCastCall(CS)) return 0;
3209
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003210 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003211
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003212 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3213 // This instruction is not reachable, just remove it. We insert a store to
3214 // undef so that we know that this code is not reachable, despite the fact
3215 // that we can't modify the CFG here.
3216 new StoreInst(ConstantBool::True,
3217 UndefValue::get(PointerType::get(Type::BoolTy)),
3218 CS.getInstruction());
3219
3220 if (!CS.getInstruction()->use_empty())
3221 CS.getInstruction()->
3222 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3223
3224 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3225 // Don't break the CFG, insert a dummy cond branch.
3226 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3227 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003228 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003229 return EraseInstFromFunction(*CS.getInstruction());
3230 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003231
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003232 const PointerType *PTy = cast<PointerType>(Callee->getType());
3233 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3234 if (FTy->isVarArg()) {
3235 // See if we can optimize any arguments passed through the varargs area of
3236 // the call.
3237 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3238 E = CS.arg_end(); I != E; ++I)
3239 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3240 // If this cast does not effect the value passed through the varargs
3241 // area, we can eliminate the use of the cast.
3242 Value *Op = CI->getOperand(0);
3243 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3244 *I = Op;
3245 Changed = true;
3246 }
3247 }
3248 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003249
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003250 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003251}
3252
Chris Lattner970c33a2003-06-19 17:00:31 +00003253// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3254// attempt to move the cast to the arguments of the call/invoke.
3255//
3256bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3257 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3258 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003259 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003260 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003261 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003262 Instruction *Caller = CS.getInstruction();
3263
3264 // Okay, this is a cast from a function to a different type. Unless doing so
3265 // would cause a type conversion of one of our arguments, change this call to
3266 // be a direct call with arguments casted to the appropriate types.
3267 //
3268 const FunctionType *FT = Callee->getFunctionType();
3269 const Type *OldRetTy = Caller->getType();
3270
Chris Lattner1f7942f2004-01-14 06:06:08 +00003271 // Check to see if we are changing the return type...
3272 if (OldRetTy != FT->getReturnType()) {
3273 if (Callee->isExternal() &&
3274 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3275 !Caller->use_empty())
3276 return false; // Cannot transform this return value...
3277
3278 // If the callsite is an invoke instruction, and the return value is used by
3279 // a PHI node in a successor, we cannot change the return type of the call
3280 // because there is no place to put the cast instruction (without breaking
3281 // the critical edge). Bail out in this case.
3282 if (!Caller->use_empty())
3283 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3284 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3285 UI != E; ++UI)
3286 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3287 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003288 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003289 return false;
3290 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003291
3292 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3293 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3294
3295 CallSite::arg_iterator AI = CS.arg_begin();
3296 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3297 const Type *ParamTy = FT->getParamType(i);
3298 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3299 if (Callee->isExternal() && !isConvertible) return false;
3300 }
3301
3302 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3303 Callee->isExternal())
3304 return false; // Do not delete arguments unless we have a function body...
3305
3306 // Okay, we decided that this is a safe thing to do: go ahead and start
3307 // inserting cast instructions as necessary...
3308 std::vector<Value*> Args;
3309 Args.reserve(NumActualArgs);
3310
3311 AI = CS.arg_begin();
3312 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3313 const Type *ParamTy = FT->getParamType(i);
3314 if ((*AI)->getType() == ParamTy) {
3315 Args.push_back(*AI);
3316 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003317 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3318 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003319 }
3320 }
3321
3322 // If the function takes more arguments than the call was taking, add them
3323 // now...
3324 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3325 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3326
3327 // If we are removing arguments to the function, emit an obnoxious warning...
3328 if (FT->getNumParams() < NumActualArgs)
3329 if (!FT->isVarArg()) {
3330 std::cerr << "WARNING: While resolving call to function '"
3331 << Callee->getName() << "' arguments were dropped!\n";
3332 } else {
3333 // Add all of the arguments in their promoted form to the arg list...
3334 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3335 const Type *PTy = getPromotedType((*AI)->getType());
3336 if (PTy != (*AI)->getType()) {
3337 // Must promote to pass through va_arg area!
3338 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3339 InsertNewInstBefore(Cast, *Caller);
3340 Args.push_back(Cast);
3341 } else {
3342 Args.push_back(*AI);
3343 }
3344 }
3345 }
3346
3347 if (FT->getReturnType() == Type::VoidTy)
3348 Caller->setName(""); // Void type should not have a name...
3349
3350 Instruction *NC;
3351 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003352 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003353 Args, Caller->getName(), Caller);
3354 } else {
3355 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3356 }
3357
3358 // Insert a cast of the return type as necessary...
3359 Value *NV = NC;
3360 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3361 if (NV->getType() != Type::VoidTy) {
3362 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003363
3364 // If this is an invoke instruction, we should insert it after the first
3365 // non-phi, instruction in the normal successor block.
3366 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3367 BasicBlock::iterator I = II->getNormalDest()->begin();
3368 while (isa<PHINode>(I)) ++I;
3369 InsertNewInstBefore(NC, *I);
3370 } else {
3371 // Otherwise, it's a call, just insert cast right after the call instr
3372 InsertNewInstBefore(NC, *Caller);
3373 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003374 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003375 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00003376 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00003377 }
3378 }
3379
3380 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3381 Caller->replaceAllUsesWith(NV);
3382 Caller->getParent()->getInstList().erase(Caller);
3383 removeFromWorkList(Caller);
3384 return true;
3385}
3386
3387
Chris Lattner48a44f72002-05-02 17:06:02 +00003388
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003389// PHINode simplification
3390//
Chris Lattner113f4f42002-06-25 16:13:24 +00003391Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00003392 if (Value *V = hasConstantValue(&PN)) {
3393 // If V is an instruction, we have to be certain that it dominates PN.
3394 // However, because we don't have dom info, we can't do a perfect job.
3395 if (Instruction *I = dyn_cast<Instruction>(V)) {
3396 // We know that the instruction dominates the PHI if there are no undef
3397 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00003398 if (I->getParent() != &I->getParent()->getParent()->front() ||
3399 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00003400 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3401 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3402 V = 0;
3403 break;
3404 }
Chris Lattnere29d6342004-10-17 21:22:38 +00003405 }
3406
3407 if (V)
3408 return ReplaceInstUsesWith(PN, V);
3409 }
Chris Lattner4db2d222004-02-16 05:07:08 +00003410
3411 // If the only user of this instruction is a cast instruction, and all of the
3412 // incoming values are constants, change this PHI to merge together the casted
3413 // constants.
3414 if (PN.hasOneUse())
3415 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3416 if (CI->getType() != PN.getType()) { // noop casts will be folded
3417 bool AllConstant = true;
3418 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3419 if (!isa<Constant>(PN.getIncomingValue(i))) {
3420 AllConstant = false;
3421 break;
3422 }
3423 if (AllConstant) {
3424 // Make a new PHI with all casted values.
3425 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3426 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3427 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3428 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3429 PN.getIncomingBlock(i));
3430 }
3431
3432 // Update the cast instruction.
3433 CI->setOperand(0, New);
3434 WorkList.push_back(CI); // revisit the cast instruction to fold.
3435 WorkList.push_back(New); // Make sure to revisit the new Phi
3436 return &PN; // PN is now dead!
3437 }
3438 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003439 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003440}
3441
Chris Lattner69193f92004-04-05 01:30:19 +00003442static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3443 Instruction *InsertPoint,
3444 InstCombiner *IC) {
3445 unsigned PS = IC->getTargetData().getPointerSize();
3446 const Type *VTy = V->getType();
3447 Instruction *Cast;
3448 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3449 // We must insert a cast to ensure we sign-extend.
3450 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3451 V->getName()), *InsertPoint);
3452 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3453 *InsertPoint);
3454}
3455
Chris Lattner48a44f72002-05-02 17:06:02 +00003456
Chris Lattner113f4f42002-06-25 16:13:24 +00003457Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003458 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003459 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003460 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003461 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003462 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003463
Chris Lattner81a7a232004-10-16 18:11:37 +00003464 if (isa<UndefValue>(GEP.getOperand(0)))
3465 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3466
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003467 bool HasZeroPointerIndex = false;
3468 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3469 HasZeroPointerIndex = C->isNullValue();
3470
3471 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003472 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003473
Chris Lattner69193f92004-04-05 01:30:19 +00003474 // Eliminate unneeded casts for indices.
3475 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003476 gep_type_iterator GTI = gep_type_begin(GEP);
3477 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3478 if (isa<SequentialType>(*GTI)) {
3479 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3480 Value *Src = CI->getOperand(0);
3481 const Type *SrcTy = Src->getType();
3482 const Type *DestTy = CI->getType();
3483 if (Src->getType()->isInteger()) {
3484 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3485 // We can always eliminate a cast from ulong or long to the other.
3486 // We can always eliminate a cast from uint to int or the other on
3487 // 32-bit pointer platforms.
3488 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3489 MadeChange = true;
3490 GEP.setOperand(i, Src);
3491 }
3492 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3493 SrcTy->getPrimitiveSize() == 4) {
3494 // We can always eliminate a cast from int to [u]long. We can
3495 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3496 // pointer target.
3497 if (SrcTy->isSigned() ||
3498 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3499 MadeChange = true;
3500 GEP.setOperand(i, Src);
3501 }
Chris Lattner69193f92004-04-05 01:30:19 +00003502 }
3503 }
3504 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003505 // If we are using a wider index than needed for this platform, shrink it
3506 // to what we need. If the incoming value needs a cast instruction,
3507 // insert it. This explicit cast can make subsequent optimizations more
3508 // obvious.
3509 Value *Op = GEP.getOperand(i);
3510 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003511 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003512 GEP.setOperand(i, ConstantExpr::getCast(C,
3513 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003514 MadeChange = true;
3515 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003516 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3517 Op->getName()), GEP);
3518 GEP.setOperand(i, Op);
3519 MadeChange = true;
3520 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003521
3522 // If this is a constant idx, make sure to canonicalize it to be a signed
3523 // operand, otherwise CSE and other optimizations are pessimized.
3524 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3525 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3526 CUI->getType()->getSignedVersion()));
3527 MadeChange = true;
3528 }
Chris Lattner69193f92004-04-05 01:30:19 +00003529 }
3530 if (MadeChange) return &GEP;
3531
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003532 // Combine Indices - If the source pointer to this getelementptr instruction
3533 // is a getelementptr instruction, combine the indices of the two
3534 // getelementptr instructions into a single instruction.
3535 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003536 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003537 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003538 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003539 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003540 if (CE->getOpcode() == Instruction::GetElementPtr)
3541 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3542 }
3543
3544 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003545 // Note that if our source is a gep chain itself that we wait for that
3546 // chain to be resolved before we perform this transformation. This
3547 // avoids us creating a TON of code in some cases.
3548 //
3549 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3550 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3551 return 0; // Wait until our source is folded to completion.
3552
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003553 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003554
3555 // Find out whether the last index in the source GEP is a sequential idx.
3556 bool EndsWithSequential = false;
3557 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3558 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003559 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003560
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003561 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003562 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003563 // Replace: gep (gep %P, long B), long A, ...
3564 // With: T = long A+B; gep %P, T, ...
3565 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003566 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003567 if (SO1 == Constant::getNullValue(SO1->getType())) {
3568 Sum = GO1;
3569 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3570 Sum = SO1;
3571 } else {
3572 // If they aren't the same type, convert both to an integer of the
3573 // target's pointer size.
3574 if (SO1->getType() != GO1->getType()) {
3575 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3576 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3577 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3578 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3579 } else {
3580 unsigned PS = TD->getPointerSize();
3581 Instruction *Cast;
3582 if (SO1->getType()->getPrimitiveSize() == PS) {
3583 // Convert GO1 to SO1's type.
3584 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3585
3586 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3587 // Convert SO1 to GO1's type.
3588 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3589 } else {
3590 const Type *PT = TD->getIntPtrType();
3591 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3592 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3593 }
3594 }
3595 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003596 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3597 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3598 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003599 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3600 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003601 }
Chris Lattner69193f92004-04-05 01:30:19 +00003602 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003603
3604 // Recycle the GEP we already have if possible.
3605 if (SrcGEPOperands.size() == 2) {
3606 GEP.setOperand(0, SrcGEPOperands[0]);
3607 GEP.setOperand(1, Sum);
3608 return &GEP;
3609 } else {
3610 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3611 SrcGEPOperands.end()-1);
3612 Indices.push_back(Sum);
3613 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3614 }
Chris Lattner69193f92004-04-05 01:30:19 +00003615 } else if (isa<Constant>(*GEP.idx_begin()) &&
3616 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003617 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003618 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003619 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3620 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003621 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3622 }
3623
3624 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003625 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003626
Chris Lattner5f667a62004-05-07 22:09:22 +00003627 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003628 // GEP of global variable. If all of the indices for this GEP are
3629 // constants, we can promote this to a constexpr instead of an instruction.
3630
3631 // Scan for nonconstants...
3632 std::vector<Constant*> Indices;
3633 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3634 for (; I != E && isa<Constant>(*I); ++I)
3635 Indices.push_back(cast<Constant>(*I));
3636
3637 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003638 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003639
3640 // Replace all uses of the GEP with the new constexpr...
3641 return ReplaceInstUsesWith(GEP, CE);
3642 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003643 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003644 if (CE->getOpcode() == Instruction::Cast) {
3645 if (HasZeroPointerIndex) {
3646 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3647 // into : GEP [10 x ubyte]* X, long 0, ...
3648 //
3649 // This occurs when the program declares an array extern like "int X[];"
3650 //
3651 Constant *X = CE->getOperand(0);
3652 const PointerType *CPTy = cast<PointerType>(CE->getType());
3653 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3654 if (const ArrayType *XATy =
3655 dyn_cast<ArrayType>(XTy->getElementType()))
3656 if (const ArrayType *CATy =
3657 dyn_cast<ArrayType>(CPTy->getElementType()))
3658 if (CATy->getElementType() == XATy->getElementType()) {
3659 // At this point, we know that the cast source type is a pointer
3660 // to an array of the same type as the destination pointer
3661 // array. Because the array type is never stepped over (there
3662 // is a leading zero) we can fold the cast into this GEP.
3663 GEP.setOperand(0, X);
3664 return &GEP;
3665 }
3666 }
3667 }
Chris Lattnerca081252001-12-14 16:52:21 +00003668 }
3669
Chris Lattnerca081252001-12-14 16:52:21 +00003670 return 0;
3671}
3672
Chris Lattner1085bdf2002-11-04 16:18:53 +00003673Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3674 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3675 if (AI.isArrayAllocation()) // Check C != 1
3676 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3677 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003678 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003679
3680 // Create and insert the replacement instruction...
3681 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003682 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003683 else {
3684 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003685 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003686 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003687
3688 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003689
3690 // Scan to the end of the allocation instructions, to skip over a block of
3691 // allocas if possible...
3692 //
3693 BasicBlock::iterator It = New;
3694 while (isa<AllocationInst>(*It)) ++It;
3695
3696 // Now that I is pointing to the first non-allocation-inst in the block,
3697 // insert our getelementptr instruction...
3698 //
Chris Lattner69193f92004-04-05 01:30:19 +00003699 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003700 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3701
3702 // Now make everything use the getelementptr instead of the original
3703 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003704 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00003705 } else if (isa<UndefValue>(AI.getArraySize())) {
3706 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003707 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003708
3709 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3710 // Note that we only do this for alloca's, because malloc should allocate and
3711 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003712 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3713 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003714 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3715
Chris Lattner1085bdf2002-11-04 16:18:53 +00003716 return 0;
3717}
3718
Chris Lattner8427bff2003-12-07 01:24:23 +00003719Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3720 Value *Op = FI.getOperand(0);
3721
3722 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3723 if (CastInst *CI = dyn_cast<CastInst>(Op))
3724 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3725 FI.setOperand(0, CI->getOperand(0));
3726 return &FI;
3727 }
3728
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003729 // free undef -> unreachable.
3730 if (isa<UndefValue>(Op)) {
3731 // Insert a new store to null because we cannot modify the CFG here.
3732 new StoreInst(ConstantBool::True,
3733 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3734 return EraseInstFromFunction(FI);
3735 }
3736
Chris Lattnerf3a36602004-02-28 04:57:37 +00003737 // If we have 'free null' delete the instruction. This can happen in stl code
3738 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003739 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00003740 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003741
Chris Lattner8427bff2003-12-07 01:24:23 +00003742 return 0;
3743}
3744
3745
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003746/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3747/// constantexpr, return the constant value being addressed by the constant
3748/// expression, or null if something is funny.
3749///
3750static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003751 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003752 return 0; // Do not allow stepping over the value!
3753
3754 // Loop over all of the operands, tracking down which value we are
3755 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003756 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3757 for (++I; I != E; ++I)
3758 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3759 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3760 assert(CU->getValue() < STy->getNumElements() &&
3761 "Struct index out of range!");
3762 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003763 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003764 } else if (isa<ConstantAggregateZero>(C)) {
3765 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003766 } else if (isa<UndefValue>(C)) {
3767 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnered79d8a2004-05-27 17:30:27 +00003768 } else {
3769 return 0;
3770 }
3771 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3772 const ArrayType *ATy = cast<ArrayType>(*I);
3773 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3774 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003775 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003776 else if (isa<ConstantAggregateZero>(C))
3777 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00003778 else if (isa<UndefValue>(C))
3779 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003780 else
3781 return 0;
3782 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003783 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003784 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003785 return C;
3786}
3787
Chris Lattner35e24772004-07-13 01:49:43 +00003788static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3789 User *CI = cast<User>(LI.getOperand(0));
3790
3791 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3792 if (const PointerType *SrcTy =
3793 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3794 const Type *SrcPTy = SrcTy->getElementType();
3795 if (SrcPTy->isSized() && DestPTy->isSized() &&
3796 IC.getTargetData().getTypeSize(SrcPTy) ==
3797 IC.getTargetData().getTypeSize(DestPTy) &&
3798 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3799 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3800 // Okay, we are casting from one integer or pointer type to another of
3801 // the same size. Instead of casting the pointer before the load, cast
3802 // the result of the loaded value.
3803 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003804 CI->getName(),
3805 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003806 // Now cast the result of the load.
3807 return new CastInst(NewLoad, LI.getType());
3808 }
3809 }
3810 return 0;
3811}
3812
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003813/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003814/// from this value cannot trap. If it is not obviously safe to load from the
3815/// specified pointer, we do a quick local scan of the basic block containing
3816/// ScanFrom, to determine if the address is already accessed.
3817static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3818 // If it is an alloca or global variable, it is always safe to load from.
3819 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3820
3821 // Otherwise, be a little bit agressive by scanning the local block where we
3822 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003823 // from/to. If so, the previous load or store would have already trapped,
3824 // so there is no harm doing an extra load (also, CSE will later eliminate
3825 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003826 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3827
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003828 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003829 --BBI;
3830
3831 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3832 if (LI->getOperand(0) == V) return true;
3833 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3834 if (SI->getOperand(1) == V) return true;
3835
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003836 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003837 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003838}
3839
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003840Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3841 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003842
Chris Lattner81a7a232004-10-16 18:11:37 +00003843 if (Constant *C = dyn_cast<Constant>(Op)) {
3844 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003845 !LI.isVolatile()) { // load null/undef -> undef
3846 // Insert a new store to null instruction before the load to indicate that
3847 // this code is not reachable. We do this instead of inserting an
3848 // unreachable instruction directly because we cannot modify the CFG.
3849 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00003850 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003851 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003852
Chris Lattner81a7a232004-10-16 18:11:37 +00003853 // Instcombine load (constant global) into the value loaded.
3854 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3855 if (GV->isConstant() && !GV->isExternal())
3856 return ReplaceInstUsesWith(LI, GV->getInitializer());
3857
3858 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
3859 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3860 if (CE->getOpcode() == Instruction::GetElementPtr) {
3861 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3862 if (GV->isConstant() && !GV->isExternal())
3863 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3864 return ReplaceInstUsesWith(LI, V);
3865 } else if (CE->getOpcode() == Instruction::Cast) {
3866 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3867 return Res;
3868 }
3869 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003870
3871 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003872 if (CastInst *CI = dyn_cast<CastInst>(Op))
3873 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3874 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003875
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003876 if (!LI.isVolatile() && Op->hasOneUse()) {
3877 // Change select and PHI nodes to select values instead of addresses: this
3878 // helps alias analysis out a lot, allows many others simplifications, and
3879 // exposes redundancy in the code.
3880 //
3881 // Note that we cannot do the transformation unless we know that the
3882 // introduced loads cannot trap! Something like this is valid as long as
3883 // the condition is always false: load (select bool %C, int* null, int* %G),
3884 // but it would not be valid if we transformed it to load from null
3885 // unconditionally.
3886 //
3887 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3888 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003889 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3890 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003891 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003892 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003893 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003894 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003895 return new SelectInst(SI->getCondition(), V1, V2);
3896 }
3897
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003898 // load (select (cond, null, P)) -> load P
3899 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3900 if (C->isNullValue()) {
3901 LI.setOperand(0, SI->getOperand(2));
3902 return &LI;
3903 }
3904
3905 // load (select (cond, P, null)) -> load P
3906 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3907 if (C->isNullValue()) {
3908 LI.setOperand(0, SI->getOperand(1));
3909 return &LI;
3910 }
3911
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003912 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3913 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003914 bool Safe = PN->getParent() == LI.getParent();
3915
3916 // Scan all of the instructions between the PHI and the load to make
3917 // sure there are no instructions that might possibly alter the value
3918 // loaded from the PHI.
3919 if (Safe) {
3920 BasicBlock::iterator I = &LI;
3921 for (--I; !isa<PHINode>(I); --I)
3922 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3923 Safe = false;
3924 break;
3925 }
3926 }
3927
3928 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003929 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003930 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003931 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003932
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003933 if (Safe) {
3934 // Create the PHI.
3935 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3936 InsertNewInstBefore(NewPN, *PN);
3937 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3938
3939 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3940 BasicBlock *BB = PN->getIncomingBlock(i);
3941 Value *&TheLoad = LoadMap[BB];
3942 if (TheLoad == 0) {
3943 Value *InVal = PN->getIncomingValue(i);
3944 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3945 InVal->getName()+".val"),
3946 *BB->getTerminator());
3947 }
3948 NewPN->addIncoming(TheLoad, BB);
3949 }
3950 return ReplaceInstUsesWith(LI, NewPN);
3951 }
3952 }
3953 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003954 return 0;
3955}
3956
Chris Lattner9eef8a72003-06-04 04:46:00 +00003957Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3958 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003959 Value *X;
3960 BasicBlock *TrueDest;
3961 BasicBlock *FalseDest;
3962 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3963 !isa<Constant>(X)) {
3964 // Swap Destinations and condition...
3965 BI.setCondition(X);
3966 BI.setSuccessor(0, FalseDest);
3967 BI.setSuccessor(1, TrueDest);
3968 return &BI;
3969 }
3970
3971 // Cannonicalize setne -> seteq
3972 Instruction::BinaryOps Op; Value *Y;
3973 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3974 TrueDest, FalseDest)))
3975 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3976 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3977 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3978 std::string Name = I->getName(); I->setName("");
3979 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3980 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003981 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003982 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003983 BI.setSuccessor(0, FalseDest);
3984 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003985 removeFromWorkList(I);
3986 I->getParent()->getInstList().erase(I);
3987 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003988 return &BI;
3989 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003990
Chris Lattner9eef8a72003-06-04 04:46:00 +00003991 return 0;
3992}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003993
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003994Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3995 Value *Cond = SI.getCondition();
3996 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3997 if (I->getOpcode() == Instruction::Add)
3998 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3999 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4000 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004001 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004002 AddRHS));
4003 SI.setOperand(0, I->getOperand(0));
4004 WorkList.push_back(I);
4005 return &SI;
4006 }
4007 }
4008 return 0;
4009}
4010
Chris Lattnerca081252001-12-14 16:52:21 +00004011
Chris Lattner99f48c62002-09-02 04:59:56 +00004012void InstCombiner::removeFromWorkList(Instruction *I) {
4013 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4014 WorkList.end());
4015}
4016
Chris Lattner113f4f42002-06-25 16:13:24 +00004017bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004018 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004019 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004020
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004021 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4022 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004023
Chris Lattnerca081252001-12-14 16:52:21 +00004024
4025 while (!WorkList.empty()) {
4026 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4027 WorkList.pop_back();
4028
Misha Brukman632df282002-10-29 23:06:16 +00004029 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004030 // Check to see if we can DIE the instruction...
4031 if (isInstructionTriviallyDead(I)) {
4032 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004033 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004034 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004035 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004036
4037 I->getParent()->getInstList().erase(I);
4038 removeFromWorkList(I);
4039 continue;
4040 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004041
Misha Brukman632df282002-10-29 23:06:16 +00004042 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004043 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner6580e092004-10-16 19:44:59 +00004044 if (isa<GetElementPtrInst>(I) &&
4045 cast<Constant>(I->getOperand(0))->isNullValue() &&
4046 !isa<ConstantPointerNull>(C)) {
4047 // If this is a constant expr gep that is effectively computing an
4048 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4049 bool isFoldableGEP = true;
4050 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4051 if (!isa<ConstantInt>(I->getOperand(i)))
4052 isFoldableGEP = false;
4053 if (isFoldableGEP) {
4054 uint64_t Offset = TD->getIndexedOffset(I->getOperand(0)->getType(),
4055 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4056 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004057 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004058 C = ConstantExpr::getCast(C, I->getType());
4059 }
4060 }
4061
Chris Lattner99f48c62002-09-02 04:59:56 +00004062 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004063 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004064 ReplaceInstUsesWith(*I, C);
4065
Chris Lattner99f48c62002-09-02 04:59:56 +00004066 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004067 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004068 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004069 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004070 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004071
Chris Lattnerca081252001-12-14 16:52:21 +00004072 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004073 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004074 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004075 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004076 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004077 DEBUG(std::cerr << "IC: Old = " << *I
4078 << " New = " << *Result);
4079
Chris Lattner396dbfe2004-06-09 05:08:07 +00004080 // Everything uses the new instruction now.
4081 I->replaceAllUsesWith(Result);
4082
4083 // Push the new instruction and any users onto the worklist.
4084 WorkList.push_back(Result);
4085 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004086
4087 // Move the name to the new instruction first...
4088 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004089 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004090
4091 // Insert the new instruction into the basic block...
4092 BasicBlock *InstParent = I->getParent();
4093 InstParent->getInstList().insert(I, Result);
4094
Chris Lattner63d75af2004-05-01 23:27:23 +00004095 // Make sure that we reprocess all operands now that we reduced their
4096 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004097 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4098 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4099 WorkList.push_back(OpI);
4100
Chris Lattner396dbfe2004-06-09 05:08:07 +00004101 // Instructions can end up on the worklist more than once. Make sure
4102 // we do not process an instruction that has been deleted.
4103 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004104
4105 // Erase the old instruction.
4106 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004107 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004108 DEBUG(std::cerr << "IC: MOD = " << *I);
4109
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004110 // If the instruction was modified, it's possible that it is now dead.
4111 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004112 if (isInstructionTriviallyDead(I)) {
4113 // Make sure we process all operands now that we are reducing their
4114 // use counts.
4115 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4116 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4117 WorkList.push_back(OpI);
4118
4119 // Instructions may end up in the worklist more than once. Erase all
4120 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004121 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004122 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004123 } else {
4124 WorkList.push_back(Result);
4125 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004126 }
Chris Lattner053c0932002-05-14 15:24:07 +00004127 }
Chris Lattner260ab202002-04-18 17:39:14 +00004128 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004129 }
4130 }
4131
Chris Lattner260ab202002-04-18 17:39:14 +00004132 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004133}
4134
Brian Gaeke38b79e82004-07-27 17:43:21 +00004135FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00004136 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00004137}
Brian Gaeke960707c2003-11-11 22:41:34 +00004138