blob: 4d0225cf5072a062394e289c89b208c0785e449f [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 Lattner471bd762003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner51ea1272004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
Chris Lattnerc8e66542002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000068
Chris Lattner51ea1272004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner51ea1272004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner99f48c62002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000090 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000092
Chris Lattnerf12cc842002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 }
97
Chris Lattner69193f92004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattner260ab202002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000116 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000117 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000118 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000123 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000124 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000125 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000126 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000127 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000128
129 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000131
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000133 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000134 bool transformConstExprCastCall(CallSite CS);
135
Chris Lattner69193f92004-04-05 01:30:19 +0000136 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
139 //
Chris Lattner623826c2004-09-28 21:48:02 +0000140 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000146 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000147 }
148
Chris Lattner7e794272004-09-24 15:21:34 +0000149 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150 /// This also adds the cast to the worklist. Finally, this returns the
151 /// cast.
152 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153 if (V->getType() == Ty) return V;
154
155 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156 WorkList.push_back(C);
157 return C;
158 }
159
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 // ReplaceInstUsesWith - This method is to be used when an instruction is
161 // found to be dead, replacable with another preexisting expression. Here
162 // we add all uses of I to the worklist, replace all uses of I with the new
163 // value, then return I, so that the inst combiner will know that I was
164 // modified.
165 //
166 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000167 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000168 if (&I != V) {
169 I.replaceAllUsesWith(V);
170 return &I;
171 } else {
172 // If we are replacing the instruction with itself, this must be in a
173 // segment of unreachable code, so just clobber the instruction.
174 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
175 return &I;
176 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000178
179 // EraseInstFromFunction - When dealing with an instruction that has side
180 // effects or produces a void value, we can't rely on DCE to delete the
181 // instruction. Instead, visit methods should return the value returned by
182 // this function.
183 Instruction *EraseInstFromFunction(Instruction &I) {
184 assert(I.use_empty() && "Cannot erase instruction that is used!");
185 AddUsesToWorkList(I);
186 removeFromWorkList(&I);
187 I.getParent()->getInstList().erase(&I);
188 return 0; // Don't do anything with FI
189 }
190
191
Chris Lattner3ac7c262003-08-13 20:16:26 +0000192 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000193 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194 /// InsertBefore instruction. This is specialized a bit to avoid inserting
195 /// casts that are known to not do anything...
196 ///
197 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198 Instruction *InsertBefore);
199
Chris Lattner7fb29e12003-03-11 00:12:48 +0000200 // SimplifyCommutative - This performs a few simplifications for commutative
201 // operators...
202 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000203
204 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
205 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner260ab202002-04-18 17:39:14 +0000206 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000207
Chris Lattnerc8b70922002-07-26 21:12:46 +0000208 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000209}
210
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000211// getComplexity: Assign a complexity or rank value to LLVM Values...
212// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
213static unsigned getComplexity(Value *V) {
214 if (isa<Instruction>(V)) {
215 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
216 return 2;
217 return 3;
218 }
219 if (isa<Argument>(V)) return 2;
220 return isa<Constant>(V) ? 0 : 1;
221}
Chris Lattner260ab202002-04-18 17:39:14 +0000222
Chris Lattner7fb29e12003-03-11 00:12:48 +0000223// isOnlyUse - Return true if this instruction will be deleted if we stop using
224// it.
225static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000226 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000227}
228
Chris Lattnere79e8542004-02-23 06:38:22 +0000229// getPromotedType - Return the specified type promoted as it would be to pass
230// though a va_arg area...
231static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000232 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000233 case Type::SByteTyID:
234 case Type::ShortTyID: return Type::IntTy;
235 case Type::UByteTyID:
236 case Type::UShortTyID: return Type::UIntTy;
237 case Type::FloatTyID: return Type::DoubleTy;
238 default: return Ty;
239 }
240}
241
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000242// SimplifyCommutative - This performs a few simplifications for commutative
243// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000244//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000245// 1. Order operands such that they are listed from right (least complex) to
246// left (most complex). This puts constants before unary operators before
247// binary operators.
248//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000249// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
250// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000251//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000252bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000253 bool Changed = false;
254 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
255 Changed = !I.swapOperands();
256
257 if (!I.isAssociative()) return Changed;
258 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000259 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
260 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
261 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000262 Constant *Folded = ConstantExpr::get(I.getOpcode(),
263 cast<Constant>(I.getOperand(1)),
264 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000265 I.setOperand(0, Op->getOperand(0));
266 I.setOperand(1, Folded);
267 return true;
268 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
269 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
270 isOnlyUse(Op) && isOnlyUse(Op1)) {
271 Constant *C1 = cast<Constant>(Op->getOperand(1));
272 Constant *C2 = cast<Constant>(Op1->getOperand(1));
273
274 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000275 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000276 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
277 Op1->getOperand(0),
278 Op1->getName(), &I);
279 WorkList.push_back(New);
280 I.setOperand(0, New);
281 I.setOperand(1, Folded);
282 return true;
283 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000284 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000285 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000286}
Chris Lattnerca081252001-12-14 16:52:21 +0000287
Chris Lattnerbb74e222003-03-10 23:06:50 +0000288// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
289// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000290//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000291static inline Value *dyn_castNegVal(Value *V) {
292 if (BinaryOperator::isNeg(V))
293 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
294
Chris Lattner9244df62003-04-30 22:19:10 +0000295 // Constants can be considered to be negated values if they can be folded...
296 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000297 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000298 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000299}
300
Chris Lattnerbb74e222003-03-10 23:06:50 +0000301static inline Value *dyn_castNotVal(Value *V) {
302 if (BinaryOperator::isNot(V))
303 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
304
305 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000306 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000307 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000308 return 0;
309}
310
Chris Lattner7fb29e12003-03-11 00:12:48 +0000311// dyn_castFoldableMul - If this value is a multiply that can be folded into
312// other computations (because it has a constant operand), return the
313// non-constant operand of the multiply.
314//
315static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000316 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000317 if (Instruction *I = dyn_cast<Instruction>(V))
318 if (I->getOpcode() == Instruction::Mul)
319 if (isa<Constant>(I->getOperand(1)))
320 return I->getOperand(0);
321 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000322}
Chris Lattner31ae8632002-08-14 17:51:49 +0000323
Chris Lattner3082c5a2003-02-18 19:28:33 +0000324// Log2 - Calculate the log base 2 for the specified value if it is exactly a
325// power of 2.
326static unsigned Log2(uint64_t Val) {
327 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
328 unsigned Count = 0;
329 while (Val != 1) {
330 if (Val & 1) return 0; // Multiple bits set?
331 Val >>= 1;
332 ++Count;
333 }
334 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000335}
336
Chris Lattner623826c2004-09-28 21:48:02 +0000337// AddOne, SubOne - Add or subtract a constant one from an integer constant...
338static Constant *AddOne(ConstantInt *C) {
339 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
340}
341static Constant *SubOne(ConstantInt *C) {
342 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
343}
344
345// isTrueWhenEqual - Return true if the specified setcondinst instruction is
346// true when both operands are equal...
347//
348static bool isTrueWhenEqual(Instruction &I) {
349 return I.getOpcode() == Instruction::SetEQ ||
350 I.getOpcode() == Instruction::SetGE ||
351 I.getOpcode() == Instruction::SetLE;
352}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000353
354/// AssociativeOpt - Perform an optimization on an associative operator. This
355/// function is designed to check a chain of associative operators for a
356/// potential to apply a certain optimization. Since the optimization may be
357/// applicable if the expression was reassociated, this checks the chain, then
358/// reassociates the expression as necessary to expose the optimization
359/// opportunity. This makes use of a special Functor, which must define
360/// 'shouldApply' and 'apply' methods.
361///
362template<typename Functor>
363Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
364 unsigned Opcode = Root.getOpcode();
365 Value *LHS = Root.getOperand(0);
366
367 // Quick check, see if the immediate LHS matches...
368 if (F.shouldApply(LHS))
369 return F.apply(Root);
370
371 // Otherwise, if the LHS is not of the same opcode as the root, return.
372 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000373 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000374 // Should we apply this transform to the RHS?
375 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
376
377 // If not to the RHS, check to see if we should apply to the LHS...
378 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
379 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
380 ShouldApply = true;
381 }
382
383 // If the functor wants to apply the optimization to the RHS of LHSI,
384 // reassociate the expression from ((? op A) op B) to (? op (A op B))
385 if (ShouldApply) {
386 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000387
388 // Now all of the instructions are in the current basic block, go ahead
389 // and perform the reassociation.
390 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
391
392 // First move the selected RHS to the LHS of the root...
393 Root.setOperand(0, LHSI->getOperand(1));
394
395 // Make what used to be the LHS of the root be the user of the root...
396 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000397 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000398 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
399 return 0;
400 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000401 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000402 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000403 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
404 BasicBlock::iterator ARI = &Root; ++ARI;
405 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
406 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000407
408 // Now propagate the ExtraOperand down the chain of instructions until we
409 // get to LHSI.
410 while (TmpLHSI != LHSI) {
411 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000412 // Move the instruction to immediately before the chain we are
413 // constructing to avoid breaking dominance properties.
414 NextLHSI->getParent()->getInstList().remove(NextLHSI);
415 BB->getInstList().insert(ARI, NextLHSI);
416 ARI = NextLHSI;
417
Chris Lattnerb8b97502003-08-13 19:01:45 +0000418 Value *NextOp = NextLHSI->getOperand(1);
419 NextLHSI->setOperand(1, ExtraOperand);
420 TmpLHSI = NextLHSI;
421 ExtraOperand = NextOp;
422 }
423
424 // Now that the instructions are reassociated, have the functor perform
425 // the transformation...
426 return F.apply(Root);
427 }
428
429 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
430 }
431 return 0;
432}
433
434
435// AddRHS - Implements: X + X --> X << 1
436struct AddRHS {
437 Value *RHS;
438 AddRHS(Value *rhs) : RHS(rhs) {}
439 bool shouldApply(Value *LHS) const { return LHS == RHS; }
440 Instruction *apply(BinaryOperator &Add) const {
441 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
442 ConstantInt::get(Type::UByteTy, 1));
443 }
444};
445
446// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
447// iff C1&C2 == 0
448struct AddMaskingAnd {
449 Constant *C2;
450 AddMaskingAnd(Constant *c) : C2(c) {}
451 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000452 ConstantInt *C1;
453 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
454 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000455 }
456 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000457 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000458 }
459};
460
Chris Lattner183b3362004-04-09 19:05:30 +0000461static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
462 InstCombiner *IC) {
463 // Figure out if the constant is the left or the right argument.
464 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
465 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000466
Chris Lattner183b3362004-04-09 19:05:30 +0000467 if (Constant *SOC = dyn_cast<Constant>(SO)) {
468 if (ConstIsRHS)
469 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
470 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
471 }
472
473 Value *Op0 = SO, *Op1 = ConstOperand;
474 if (!ConstIsRHS)
475 std::swap(Op0, Op1);
476 Instruction *New;
477 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
478 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
479 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
480 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000481 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000482 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000483 abort();
484 }
Chris Lattner183b3362004-04-09 19:05:30 +0000485 return IC->InsertNewInstBefore(New, BI);
486}
487
488// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
489// constant as the other operand, try to fold the binary operator into the
490// select arguments.
491static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
492 InstCombiner *IC) {
493 // Don't modify shared select instructions
494 if (!SI->hasOneUse()) return 0;
495 Value *TV = SI->getOperand(1);
496 Value *FV = SI->getOperand(2);
497
498 if (isa<Constant>(TV) || isa<Constant>(FV)) {
499 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
500 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
501
502 return new SelectInst(SI->getCondition(), SelectTrueVal,
503 SelectFalseVal);
504 }
505 return 0;
506}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000507
Chris Lattner113f4f42002-06-25 16:13:24 +0000508Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000509 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000510 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000511
Chris Lattnercf4a9962004-04-10 22:01:55 +0000512 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
513 // X + 0 --> X
514 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
515 RHSC->isNullValue())
516 return ReplaceInstUsesWith(I, LHS);
517
518 // X + (signbit) --> X ^ signbit
519 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
520 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
521 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
522 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000523 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000524 }
525 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000526
Chris Lattnerb8b97502003-08-13 19:01:45 +0000527 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000528 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000529 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000530 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000531
Chris Lattner147e9752002-05-08 22:46:53 +0000532 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000533 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000534 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000535
536 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000537 if (!isa<Constant>(RHS))
538 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000539 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000540
Chris Lattner57c8d992003-02-18 19:57:07 +0000541 // X*C + X --> X * (C+1)
542 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000543 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000544 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000545 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
546 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000547 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000548 }
549
550 // X + X*C --> X * (C+1)
551 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000552 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000553 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000554 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
555 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000556 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000557 }
558
Chris Lattnerb8b97502003-08-13 19:01:45 +0000559 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000560 ConstantInt *C2;
561 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000562 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000563
Chris Lattnerb9cde762003-10-02 15:11:26 +0000564 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000565 Value *X;
566 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
567 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
568 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000569 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000570
571 // Try to fold constant add into select arguments.
572 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
573 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
574 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000575 }
576
Chris Lattner113f4f42002-06-25 16:13:24 +0000577 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000578}
579
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000580// isSignBit - Return true if the value represented by the constant only has the
581// highest order bit set.
582static bool isSignBit(ConstantInt *CI) {
583 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
584 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
585}
586
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000587static unsigned getTypeSizeInBits(const Type *Ty) {
588 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
589}
590
Chris Lattner022167f2004-03-13 00:11:49 +0000591/// RemoveNoopCast - Strip off nonconverting casts from the value.
592///
593static Value *RemoveNoopCast(Value *V) {
594 if (CastInst *CI = dyn_cast<CastInst>(V)) {
595 const Type *CTy = CI->getType();
596 const Type *OpTy = CI->getOperand(0)->getType();
597 if (CTy->isInteger() && OpTy->isInteger()) {
598 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
599 return RemoveNoopCast(CI->getOperand(0));
600 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
601 return RemoveNoopCast(CI->getOperand(0));
602 }
603 return V;
604}
605
Chris Lattner113f4f42002-06-25 16:13:24 +0000606Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000607 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000608
Chris Lattnere6794492002-08-12 21:17:25 +0000609 if (Op0 == Op1) // sub X, X -> 0
610 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000611
Chris Lattnere6794492002-08-12 21:17:25 +0000612 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000613 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000614 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000615
Chris Lattner8f2f5982003-11-05 01:06:05 +0000616 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
617 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000618 if (C->isAllOnesValue())
619 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000620
Chris Lattner8f2f5982003-11-05 01:06:05 +0000621 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000622 Value *X;
623 if (match(Op1, m_Not(m_Value(X))))
624 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000625 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000626 // -((uint)X >> 31) -> ((int)X >> 31)
627 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000628 if (C->isNullValue()) {
629 Value *NoopCastedRHS = RemoveNoopCast(Op1);
630 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000631 if (SI->getOpcode() == Instruction::Shr)
632 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
633 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000634 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000635 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000636 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000637 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000638 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000639 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000640 // Ok, the transformation is safe. Insert a cast of the incoming
641 // value, then the new shift, then the new cast.
642 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
643 SI->getOperand(0)->getName());
644 Value *InV = InsertNewInstBefore(FirstCast, I);
645 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
646 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000647 if (NewShift->getType() == I.getType())
648 return NewShift;
649 else {
650 InV = InsertNewInstBefore(NewShift, I);
651 return new CastInst(NewShift, I.getType());
652 }
Chris Lattner92295c52004-03-12 23:53:13 +0000653 }
654 }
Chris Lattner022167f2004-03-13 00:11:49 +0000655 }
Chris Lattner183b3362004-04-09 19:05:30 +0000656
657 // Try to fold constant sub into select arguments.
658 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
659 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
660 return R;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000661 }
662
Chris Lattner3082c5a2003-02-18 19:28:33 +0000663 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000664 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000665 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
666 // is not used by anyone else...
667 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000668 if (Op1I->getOpcode() == Instruction::Sub &&
669 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000670 // Swap the two operands of the subexpr...
671 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
672 Op1I->setOperand(0, IIOp1);
673 Op1I->setOperand(1, IIOp0);
674
675 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000676 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000677 }
678
679 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
680 //
681 if (Op1I->getOpcode() == Instruction::And &&
682 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
683 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
684
Chris Lattner396dbfe2004-06-09 05:08:07 +0000685 Value *NewNot =
686 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000687 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000688 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000689
690 // X - X*C --> X * (1-C)
691 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000692 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000693 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000694 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000695 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000696 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000697 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000698 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000699
Chris Lattner57c8d992003-02-18 19:57:07 +0000700 // X*C - X --> X * (C-1)
701 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000702 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000703 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000704 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000705 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000706 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000707 }
708
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000709 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000710}
711
Chris Lattnere79e8542004-02-23 06:38:22 +0000712/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
713/// really just returns true if the most significant (sign) bit is set.
714static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
715 if (RHS->getType()->isSigned()) {
716 // True if source is LHS < 0 or LHS <= -1
717 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
718 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
719 } else {
720 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
721 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
722 // the size of the integer type.
723 if (Opcode == Instruction::SetGE)
724 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
725 if (Opcode == Instruction::SetGT)
726 return RHSC->getValue() ==
727 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
728 }
729 return false;
730}
731
Chris Lattner113f4f42002-06-25 16:13:24 +0000732Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000733 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000734 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000735
Chris Lattnere6794492002-08-12 21:17:25 +0000736 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000737 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
738 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000739
740 // ((X << C1)*C2) == (X * (C2 << C1))
741 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
742 if (SI->getOpcode() == Instruction::Shl)
743 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000744 return BinaryOperator::createMul(SI->getOperand(0),
745 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000746
Chris Lattnercce81be2003-09-11 22:24:54 +0000747 if (CI->isNullValue())
748 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
749 if (CI->equalsInt(1)) // X * 1 == X
750 return ReplaceInstUsesWith(I, Op0);
751 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000752 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000753
Chris Lattnercce81be2003-09-11 22:24:54 +0000754 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000755 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
756 return new ShiftInst(Instruction::Shl, Op0,
757 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000758 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000759 if (Op1F->isNullValue())
760 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000761
Chris Lattner3082c5a2003-02-18 19:28:33 +0000762 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
763 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
764 if (Op1F->getValue() == 1.0)
765 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
766 }
Chris Lattner183b3362004-04-09 19:05:30 +0000767
768 // Try to fold constant mul into select arguments.
769 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
770 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
771 return R;
Chris Lattner260ab202002-04-18 17:39:14 +0000772 }
773
Chris Lattner934a64cf2003-03-10 23:23:04 +0000774 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
775 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000776 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000777
Chris Lattner2635b522004-02-23 05:39:21 +0000778 // If one of the operands of the multiply is a cast from a boolean value, then
779 // we know the bool is either zero or one, so this is a 'masking' multiply.
780 // See if we can simplify things based on how the boolean was originally
781 // formed.
782 CastInst *BoolCast = 0;
783 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
784 if (CI->getOperand(0)->getType() == Type::BoolTy)
785 BoolCast = CI;
786 if (!BoolCast)
787 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
788 if (CI->getOperand(0)->getType() == Type::BoolTy)
789 BoolCast = CI;
790 if (BoolCast) {
791 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
792 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
793 const Type *SCOpTy = SCIOp0->getType();
794
Chris Lattnere79e8542004-02-23 06:38:22 +0000795 // If the setcc is true iff the sign bit of X is set, then convert this
796 // multiply into a shift/and combination.
797 if (isa<ConstantInt>(SCIOp1) &&
798 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000799 // Shift the X value right to turn it into "all signbits".
800 Constant *Amt = ConstantUInt::get(Type::UByteTy,
801 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000802 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000803 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000804 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
805 SCIOp0->getName()), I);
806 }
807
808 Value *V =
809 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
810 BoolCast->getOperand(0)->getName()+
811 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000812
813 // If the multiply type is not the same as the source type, sign extend
814 // or truncate to the multiply type.
815 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000816 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000817
818 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000819 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000820 }
821 }
822 }
823
Chris Lattner113f4f42002-06-25 16:13:24 +0000824 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000825}
826
Chris Lattner113f4f42002-06-25 16:13:24 +0000827Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000828 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000829 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000830 if (RHS->equalsInt(1))
831 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000832
Chris Lattnere20c3342004-04-26 14:01:59 +0000833 // div X, -1 == -X
834 if (RHS->isAllOnesValue())
835 return BinaryOperator::createNeg(I.getOperand(0));
836
Chris Lattner272d5ca2004-09-28 18:22:15 +0000837 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
838 if (LHS->getOpcode() == Instruction::Div)
839 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000840 // (X / C1) / C2 -> X / (C1*C2)
841 return BinaryOperator::createDiv(LHS->getOperand(0),
842 ConstantExpr::getMul(RHS, LHSRHS));
843 }
844
Chris Lattner3082c5a2003-02-18 19:28:33 +0000845 // Check to see if this is an unsigned division with an exact power of 2,
846 // if so, convert to a right shift.
847 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
848 if (uint64_t Val = C->getValue()) // Don't break X / 0
849 if (uint64_t C = Log2(Val))
850 return new ShiftInst(Instruction::Shr, I.getOperand(0),
851 ConstantUInt::get(Type::UByteTy, C));
852 }
853
854 // 0 / X == 0, we don't need to preserve faults!
855 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
856 if (LHS->equalsInt(0))
857 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
858
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000859 return 0;
860}
861
862
Chris Lattner113f4f42002-06-25 16:13:24 +0000863Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000864 if (I.getType()->isSigned())
865 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000866 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000867 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000868 // X % -Y -> X % Y
869 AddUsesToWorkList(I);
870 I.setOperand(1, RHSNeg);
871 return &I;
872 }
873
Chris Lattner3082c5a2003-02-18 19:28:33 +0000874 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
875 if (RHS->equalsInt(1)) // X % 1 == 0
876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
877
878 // Check to see if this is an unsigned remainder with an exact power of 2,
879 // if so, convert to a bitwise and.
880 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
881 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000882 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000883 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000884 ConstantUInt::get(I.getType(), Val-1));
885 }
886
887 // 0 % X == 0, we don't need to preserve faults!
888 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
889 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000890 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
891
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000892 return 0;
893}
894
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000895// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000896static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000897 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
898 // Calculate -1 casted to the right type...
899 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
900 uint64_t Val = ~0ULL; // All ones
901 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
902 return CU->getValue() == Val-1;
903 }
904
905 const ConstantSInt *CS = cast<ConstantSInt>(C);
906
907 // Calculate 0111111111..11111
908 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
909 int64_t Val = INT64_MAX; // All ones
910 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
911 return CS->getValue() == Val-1;
912}
913
914// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000915static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000916 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
917 return CU->getValue() == 1;
918
919 const ConstantSInt *CS = cast<ConstantSInt>(C);
920
921 // Calculate 1111111111000000000000
922 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
923 int64_t Val = -1; // All ones
924 Val <<= TypeBits-1; // Shift over to the right spot
925 return CS->getValue() == Val+1;
926}
927
Chris Lattner35167c32004-06-09 07:59:58 +0000928// isOneBitSet - Return true if there is exactly one bit set in the specified
929// constant.
930static bool isOneBitSet(const ConstantInt *CI) {
931 uint64_t V = CI->getRawValue();
932 return V && (V & (V-1)) == 0;
933}
934
Chris Lattner8fc5af42004-09-23 21:46:38 +0000935#if 0 // Currently unused
936// isLowOnes - Return true if the constant is of the form 0+1+.
937static bool isLowOnes(const ConstantInt *CI) {
938 uint64_t V = CI->getRawValue();
939
940 // There won't be bits set in parts that the type doesn't contain.
941 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
942
943 uint64_t U = V+1; // If it is low ones, this should be a power of two.
944 return U && V && (U & V) == 0;
945}
946#endif
947
948// isHighOnes - Return true if the constant is of the form 1+0+.
949// This is the same as lowones(~X).
950static bool isHighOnes(const ConstantInt *CI) {
951 uint64_t V = ~CI->getRawValue();
952
953 // There won't be bits set in parts that the type doesn't contain.
954 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
955
956 uint64_t U = V+1; // If it is low ones, this should be a power of two.
957 return U && V && (U & V) == 0;
958}
959
960
Chris Lattner3ac7c262003-08-13 20:16:26 +0000961/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
962/// are carefully arranged to allow folding of expressions such as:
963///
964/// (A < B) | (A > B) --> (A != B)
965///
966/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
967/// represents that the comparison is true if A == B, and bit value '1' is true
968/// if A < B.
969///
970static unsigned getSetCondCode(const SetCondInst *SCI) {
971 switch (SCI->getOpcode()) {
972 // False -> 0
973 case Instruction::SetGT: return 1;
974 case Instruction::SetEQ: return 2;
975 case Instruction::SetGE: return 3;
976 case Instruction::SetLT: return 4;
977 case Instruction::SetNE: return 5;
978 case Instruction::SetLE: return 6;
979 // True -> 7
980 default:
981 assert(0 && "Invalid SetCC opcode!");
982 return 0;
983 }
984}
985
986/// getSetCCValue - This is the complement of getSetCondCode, which turns an
987/// opcode and two operands into either a constant true or false, or a brand new
988/// SetCC instruction.
989static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
990 switch (Opcode) {
991 case 0: return ConstantBool::False;
992 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
993 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
994 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
995 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
996 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
997 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
998 case 7: return ConstantBool::True;
999 default: assert(0 && "Illegal SetCCCode!"); return 0;
1000 }
1001}
1002
1003// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1004struct FoldSetCCLogical {
1005 InstCombiner &IC;
1006 Value *LHS, *RHS;
1007 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1008 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1009 bool shouldApply(Value *V) const {
1010 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1011 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1012 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1013 return false;
1014 }
1015 Instruction *apply(BinaryOperator &Log) const {
1016 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1017 if (SCI->getOperand(0) != LHS) {
1018 assert(SCI->getOperand(1) == LHS);
1019 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1020 }
1021
1022 unsigned LHSCode = getSetCondCode(SCI);
1023 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1024 unsigned Code;
1025 switch (Log.getOpcode()) {
1026 case Instruction::And: Code = LHSCode & RHSCode; break;
1027 case Instruction::Or: Code = LHSCode | RHSCode; break;
1028 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001029 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001030 }
1031
1032 Value *RV = getSetCCValue(Code, LHS, RHS);
1033 if (Instruction *I = dyn_cast<Instruction>(RV))
1034 return I;
1035 // Otherwise, it's a constant boolean value...
1036 return IC.ReplaceInstUsesWith(Log, RV);
1037 }
1038};
1039
1040
Chris Lattnerba1cb382003-09-19 17:17:26 +00001041// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1042// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1043// guaranteed to be either a shift instruction or a binary operator.
1044Instruction *InstCombiner::OptAndOp(Instruction *Op,
1045 ConstantIntegral *OpRHS,
1046 ConstantIntegral *AndRHS,
1047 BinaryOperator &TheAnd) {
1048 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001049 Constant *Together = 0;
1050 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001051 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001052
Chris Lattnerba1cb382003-09-19 17:17:26 +00001053 switch (Op->getOpcode()) {
1054 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001055 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001056 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001057 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001058 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001059 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1060 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001061 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001062 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001063 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001064 }
1065 break;
1066 case Instruction::Or:
1067 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001068 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001069 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001070 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001071 if (Together == AndRHS) // (X | C) & C --> C
1072 return ReplaceInstUsesWith(TheAnd, AndRHS);
1073
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001074 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001075 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1076 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001077 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001078 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001079 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001080 }
1081 }
1082 break;
1083 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001084 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001085 // Adding a one to a single bit bit-field should be turned into an XOR
1086 // of the bit. First thing to check is to see if this AND is with a
1087 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001088 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001089
1090 // Clear bits that are not part of the constant.
1091 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1092
1093 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001094 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001095 // Ok, at this point, we know that we are masking the result of the
1096 // ADD down to exactly one bit. If the constant we are adding has
1097 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001098 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001099
1100 // Check to see if any bits below the one bit set in AndRHSV are set.
1101 if ((AddRHS & (AndRHSV-1)) == 0) {
1102 // If not, the only thing that can effect the output of the AND is
1103 // the bit specified by AndRHSV. If that bit is set, the effect of
1104 // the XOR is to toggle the bit. If it is clear, then the ADD has
1105 // no effect.
1106 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1107 TheAnd.setOperand(0, X);
1108 return &TheAnd;
1109 } else {
1110 std::string Name = Op->getName(); Op->setName("");
1111 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001112 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001113 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001114 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001115 }
1116 }
1117 }
1118 }
1119 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001120
1121 case Instruction::Shl: {
1122 // We know that the AND will not produce any of the bits shifted in, so if
1123 // the anded constant includes them, clear them now!
1124 //
1125 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001126 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1127 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1128
1129 if (CI == ShlMask) { // Masking out bits that the shift already masks
1130 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1131 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001132 TheAnd.setOperand(1, CI);
1133 return &TheAnd;
1134 }
1135 break;
1136 }
1137 case Instruction::Shr:
1138 // We know that the AND will not produce any of the bits shifted in, so if
1139 // the anded constant includes them, clear them now! This only applies to
1140 // unsigned shifts, because a signed shr may bring in set bits!
1141 //
1142 if (AndRHS->getType()->isUnsigned()) {
1143 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001144 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1145 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1146
1147 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1148 return ReplaceInstUsesWith(TheAnd, Op);
1149 } else if (CI != AndRHS) {
1150 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001151 return &TheAnd;
1152 }
Chris Lattner7e794272004-09-24 15:21:34 +00001153 } else { // Signed shr.
1154 // See if this is shifting in some sign extension, then masking it out
1155 // with an and.
1156 if (Op->hasOneUse()) {
1157 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1158 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1159 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1160 if (CI == ShrMask) { // Masking out bits shifted in.
1161 // Make the argument unsigned.
1162 Value *ShVal = Op->getOperand(0);
1163 ShVal = InsertCastBefore(ShVal,
1164 ShVal->getType()->getUnsignedVersion(),
1165 TheAnd);
1166 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1167 OpRHS, Op->getName()),
1168 TheAnd);
1169 return new CastInst(ShVal, Op->getType());
1170 }
1171 }
Chris Lattner2da29172003-09-19 19:05:02 +00001172 }
1173 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001174 }
1175 return 0;
1176}
1177
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001178
Chris Lattner113f4f42002-06-25 16:13:24 +00001179Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001180 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001181 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001182
1183 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001184 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1185 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001186
1187 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001188 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001189 if (RHS->isAllOnesValue())
1190 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001191
Chris Lattnerba1cb382003-09-19 17:17:26 +00001192 // Optimize a variety of ((val OP C1) & C2) combinations...
1193 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1194 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001195 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001196 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001197 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1198 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001199 }
Chris Lattner183b3362004-04-09 19:05:30 +00001200
1201 // Try to fold constant and into select arguments.
1202 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1203 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1204 return R;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001205 }
1206
Chris Lattnerbb74e222003-03-10 23:06:50 +00001207 Value *Op0NotVal = dyn_castNotVal(Op0);
1208 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001209
Chris Lattner023a4832004-06-18 06:07:51 +00001210 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1211 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1212
Misha Brukman9c003d82004-07-30 12:50:08 +00001213 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001214 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001215 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1216 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001217 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001218 return BinaryOperator::createNot(Or);
1219 }
1220
Chris Lattner623826c2004-09-28 21:48:02 +00001221 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1222 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001223 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1224 return R;
1225
Chris Lattner623826c2004-09-28 21:48:02 +00001226 Value *LHSVal, *RHSVal;
1227 ConstantInt *LHSCst, *RHSCst;
1228 Instruction::BinaryOps LHSCC, RHSCC;
1229 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1230 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1231 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1232 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1233 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1234 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1235 // Ensure that the larger constant is on the RHS.
1236 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1237 SetCondInst *LHS = cast<SetCondInst>(Op0);
1238 if (cast<ConstantBool>(Cmp)->getValue()) {
1239 std::swap(LHS, RHS);
1240 std::swap(LHSCst, RHSCst);
1241 std::swap(LHSCC, RHSCC);
1242 }
1243
1244 // At this point, we know we have have two setcc instructions
1245 // comparing a value against two constants and and'ing the result
1246 // together. Because of the above check, we know that we only have
1247 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1248 // FoldSetCCLogical check above), that the two constants are not
1249 // equal.
1250 assert(LHSCst != RHSCst && "Compares not folded above?");
1251
1252 switch (LHSCC) {
1253 default: assert(0 && "Unknown integer condition code!");
1254 case Instruction::SetEQ:
1255 switch (RHSCC) {
1256 default: assert(0 && "Unknown integer condition code!");
1257 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1258 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1259 return ReplaceInstUsesWith(I, ConstantBool::False);
1260 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1261 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1262 return ReplaceInstUsesWith(I, LHS);
1263 }
1264 case Instruction::SetNE:
1265 switch (RHSCC) {
1266 default: assert(0 && "Unknown integer condition code!");
1267 case Instruction::SetLT:
1268 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1269 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1270 break; // (X != 13 & X < 15) -> no change
1271 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1272 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1273 return ReplaceInstUsesWith(I, RHS);
1274 case Instruction::SetNE:
1275 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1276 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1277 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1278 LHSVal->getName()+".off");
1279 InsertNewInstBefore(Add, I);
1280 const Type *UnsType = Add->getType()->getUnsignedVersion();
1281 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1282 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1283 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1284 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1285 }
1286 break; // (X != 13 & X != 15) -> no change
1287 }
1288 break;
1289 case Instruction::SetLT:
1290 switch (RHSCC) {
1291 default: assert(0 && "Unknown integer condition code!");
1292 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1293 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1294 return ReplaceInstUsesWith(I, ConstantBool::False);
1295 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1296 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1297 return ReplaceInstUsesWith(I, LHS);
1298 }
1299 case Instruction::SetGT:
1300 switch (RHSCC) {
1301 default: assert(0 && "Unknown integer condition code!");
1302 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1303 return ReplaceInstUsesWith(I, LHS);
1304 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1305 return ReplaceInstUsesWith(I, RHS);
1306 case Instruction::SetNE:
1307 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1308 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1309 break; // (X > 13 & X != 15) -> no change
1310 case Instruction::SetLT: { // (X > 13 & X < 15) -> (X-14) <u 1
1311 Constant *AddCST = ConstantExpr::getNeg(AddOne(LHSCst));
1312 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1313 LHSVal->getName()+".off");
1314 InsertNewInstBefore(Add, I);
1315 // Convert to unsigned for the comparison.
1316 const Type *UnsType = Add->getType()->getUnsignedVersion();
1317 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1318 AddCST = ConstantExpr::getAdd(AddCST, RHSCst);
1319 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1320 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1321 }
1322 break;
1323 }
1324 }
1325 }
1326 }
1327
Chris Lattner113f4f42002-06-25 16:13:24 +00001328 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001329}
1330
1331
1332
Chris Lattner113f4f42002-06-25 16:13:24 +00001333Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001334 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001336
1337 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001338 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1339 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001340
1341 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001342 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001343 if (RHS->isAllOnesValue())
1344 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001345
Chris Lattnerd4252a72004-07-30 07:50:03 +00001346 ConstantInt *C1; Value *X;
1347 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1348 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1349 std::string Op0Name = Op0->getName(); Op0->setName("");
1350 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1351 InsertNewInstBefore(Or, I);
1352 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1353 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001354
Chris Lattnerd4252a72004-07-30 07:50:03 +00001355 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1356 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1357 std::string Op0Name = Op0->getName(); Op0->setName("");
1358 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1359 InsertNewInstBefore(Or, I);
1360 return BinaryOperator::createXor(Or,
1361 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001362 }
Chris Lattner183b3362004-04-09 19:05:30 +00001363
1364 // Try to fold constant and into select arguments.
1365 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1366 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1367 return R;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001368 }
1369
Chris Lattner812aab72003-08-12 19:11:07 +00001370 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001371 Value *A, *B; ConstantInt *C1, *C2;
1372 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1373 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1374 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001375
Chris Lattnerd4252a72004-07-30 07:50:03 +00001376 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1377 if (A == Op1) // ~A | A == -1
1378 return ReplaceInstUsesWith(I,
1379 ConstantIntegral::getAllOnesValue(I.getType()));
1380 } else {
1381 A = 0;
1382 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001383
Chris Lattnerd4252a72004-07-30 07:50:03 +00001384 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1385 if (Op0 == B)
1386 return ReplaceInstUsesWith(I,
1387 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001388
Misha Brukman9c003d82004-07-30 12:50:08 +00001389 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001390 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1391 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1392 I.getName()+".demorgan"), I);
1393 return BinaryOperator::createNot(And);
1394 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001395 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001396
Chris Lattner3ac7c262003-08-13 20:16:26 +00001397 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001398 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001399 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1400 return R;
1401
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001402 Value *LHSVal, *RHSVal;
1403 ConstantInt *LHSCst, *RHSCst;
1404 Instruction::BinaryOps LHSCC, RHSCC;
1405 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1406 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1407 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1408 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1409 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1410 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1411 // Ensure that the larger constant is on the RHS.
1412 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1413 SetCondInst *LHS = cast<SetCondInst>(Op0);
1414 if (cast<ConstantBool>(Cmp)->getValue()) {
1415 std::swap(LHS, RHS);
1416 std::swap(LHSCst, RHSCst);
1417 std::swap(LHSCC, RHSCC);
1418 }
1419
1420 // At this point, we know we have have two setcc instructions
1421 // comparing a value against two constants and or'ing the result
1422 // together. Because of the above check, we know that we only have
1423 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1424 // FoldSetCCLogical check above), that the two constants are not
1425 // equal.
1426 assert(LHSCst != RHSCst && "Compares not folded above?");
1427
1428 switch (LHSCC) {
1429 default: assert(0 && "Unknown integer condition code!");
1430 case Instruction::SetEQ:
1431 switch (RHSCC) {
1432 default: assert(0 && "Unknown integer condition code!");
1433 case Instruction::SetEQ:
1434 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1435 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1436 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1437 LHSVal->getName()+".off");
1438 InsertNewInstBefore(Add, I);
1439 const Type *UnsType = Add->getType()->getUnsignedVersion();
1440 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1441 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1442 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1443 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1444 }
1445 break; // (X == 13 | X == 15) -> no change
1446
1447 case Instruction::SetGT:
1448 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1449 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1450 break; // (X == 13 | X > 15) -> no change
1451 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1452 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1453 return ReplaceInstUsesWith(I, RHS);
1454 }
1455 break;
1456 case Instruction::SetNE:
1457 switch (RHSCC) {
1458 default: assert(0 && "Unknown integer condition code!");
1459 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1460 return ReplaceInstUsesWith(I, RHS);
1461 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1462 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1463 return ReplaceInstUsesWith(I, LHS);
1464 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1465 return ReplaceInstUsesWith(I, ConstantBool::True);
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 == 14) -> no change
1472 break;
1473 case Instruction::SetGT: {// (X < 13 | X > 15) -> (X-13) > 2
1474 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1475 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1476 LHSVal->getName()+".off");
1477 InsertNewInstBefore(Add, I);
1478 // Convert to unsigned for the comparison.
1479 const Type *UnsType = Add->getType()->getUnsignedVersion();
1480 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1481 AddCST = ConstantExpr::getAdd(AddCST, RHSCst);
1482 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1483 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1484 }
1485 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1486 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1487 return ReplaceInstUsesWith(I, RHS);
1488 }
1489 break;
1490 case Instruction::SetGT:
1491 switch (RHSCC) {
1492 default: assert(0 && "Unknown integer condition code!");
1493 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1494 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1495 return ReplaceInstUsesWith(I, LHS);
1496 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1497 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1498 return ReplaceInstUsesWith(I, ConstantBool::True);
1499 }
1500 }
1501 }
1502 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001503 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001504}
1505
Chris Lattnerc2076352004-02-16 01:20:27 +00001506// XorSelf - Implements: X ^ X --> 0
1507struct XorSelf {
1508 Value *RHS;
1509 XorSelf(Value *rhs) : RHS(rhs) {}
1510 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1511 Instruction *apply(BinaryOperator &Xor) const {
1512 return &Xor;
1513 }
1514};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001515
1516
Chris Lattner113f4f42002-06-25 16:13:24 +00001517Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001518 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001519 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001520
Chris Lattnerc2076352004-02-16 01:20:27 +00001521 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1522 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1523 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001524 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001525 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001526
Chris Lattner97638592003-07-23 21:37:07 +00001527 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001528 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001529 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001530 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001531
Chris Lattner97638592003-07-23 21:37:07 +00001532 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001533 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001534 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001535 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001536 return new SetCondInst(SCI->getInverseCondition(),
1537 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001538
Chris Lattner8f2f5982003-11-05 01:06:05 +00001539 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001540 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1541 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001542 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1543 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001544 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001545 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001546 }
Chris Lattner023a4832004-06-18 06:07:51 +00001547
1548 // ~(~X & Y) --> (X | ~Y)
1549 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1550 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1551 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1552 Instruction *NotY =
1553 BinaryOperator::createNot(Op0I->getOperand(1),
1554 Op0I->getOperand(1)->getName()+".not");
1555 InsertNewInstBefore(NotY, I);
1556 return BinaryOperator::createOr(Op0NotVal, NotY);
1557 }
1558 }
Chris Lattner97638592003-07-23 21:37:07 +00001559
1560 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001561 switch (Op0I->getOpcode()) {
1562 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001563 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001564 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001565 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1566 return BinaryOperator::createSub(
1567 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001568 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001569 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001570 }
Chris Lattnere5806662003-11-04 23:50:51 +00001571 break;
1572 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001573 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001574 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1575 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001576 break;
1577 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001578 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001579 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001580 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001581 break;
1582 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001583 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001584 }
Chris Lattner183b3362004-04-09 19:05:30 +00001585
1586 // Try to fold constant and into select arguments.
1587 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1588 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1589 return R;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001590 }
1591
Chris Lattnerbb74e222003-03-10 23:06:50 +00001592 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001593 if (X == Op1)
1594 return ReplaceInstUsesWith(I,
1595 ConstantIntegral::getAllOnesValue(I.getType()));
1596
Chris Lattnerbb74e222003-03-10 23:06:50 +00001597 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001598 if (X == Op0)
1599 return ReplaceInstUsesWith(I,
1600 ConstantIntegral::getAllOnesValue(I.getType()));
1601
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001602 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001603 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001604 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1605 cast<BinaryOperator>(Op1I)->swapOperands();
1606 I.swapOperands();
1607 std::swap(Op0, Op1);
1608 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1609 I.swapOperands();
1610 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001611 }
1612 } else if (Op1I->getOpcode() == Instruction::Xor) {
1613 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1614 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1615 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1616 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1617 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001618
1619 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001620 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001621 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1622 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001623 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001624 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1625 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001626 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001627 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001628 } else if (Op0I->getOpcode() == Instruction::Xor) {
1629 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1630 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1631 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1632 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001633 }
1634
Chris Lattner7aa2d472004-08-01 19:42:59 +00001635 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001636 Value *A, *B; ConstantInt *C1, *C2;
1637 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1638 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001639 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001640 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001641
Chris Lattner3ac7c262003-08-13 20:16:26 +00001642 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1643 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1644 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1645 return R;
1646
Chris Lattner113f4f42002-06-25 16:13:24 +00001647 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001648}
1649
Chris Lattner113f4f42002-06-25 16:13:24 +00001650Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001651 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001652 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1653 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001654
1655 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001656 if (Op0 == Op1)
1657 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001658
Chris Lattnerd07283a2003-08-13 05:38:46 +00001659 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1660 if (isa<ConstantPointerNull>(Op1) &&
1661 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001662 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1663
Chris Lattnerd07283a2003-08-13 05:38:46 +00001664
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001665 // setcc's with boolean values can always be turned into bitwise operations
1666 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001667 switch (I.getOpcode()) {
1668 default: assert(0 && "Invalid setcc instruction!");
1669 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001670 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001671 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001672 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001673 }
Chris Lattner4456da62004-08-11 00:50:51 +00001674 case Instruction::SetNE:
1675 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001676
Chris Lattner4456da62004-08-11 00:50:51 +00001677 case Instruction::SetGT:
1678 std::swap(Op0, Op1); // Change setgt -> setlt
1679 // FALL THROUGH
1680 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1681 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1682 InsertNewInstBefore(Not, I);
1683 return BinaryOperator::createAnd(Not, Op1);
1684 }
1685 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001686 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001687 // FALL THROUGH
1688 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1689 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1690 InsertNewInstBefore(Not, I);
1691 return BinaryOperator::createOr(Not, Op1);
1692 }
1693 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001694 }
1695
Chris Lattner2dd01742004-06-09 04:24:29 +00001696 // See if we are doing a comparison between a constant and an instruction that
1697 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001698 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere1e10e12004-05-25 06:32:08 +00001699 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001700 switch (LHSI->getOpcode()) {
1701 case Instruction::And:
1702 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1703 LHSI->getOperand(0)->hasOneUse()) {
1704 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1705 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1706 // happens a LOT in code produced by the C front-end, for bitfield
1707 // access.
1708 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1709 ConstantUInt *ShAmt;
1710 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1711 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1712 const Type *Ty = LHSI->getType();
1713
1714 // We can fold this as long as we can't shift unknown bits
1715 // into the mask. This can only happen with signed shift
1716 // rights, as they sign-extend.
1717 if (ShAmt) {
1718 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001719 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001720 if (!CanFold) {
1721 // To test for the bad case of the signed shr, see if any
1722 // of the bits shifted in could be tested after the mask.
1723 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001724 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001725 Constant *ShVal =
1726 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1727 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1728 CanFold = true;
1729 }
1730
1731 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001732 Constant *NewCst;
1733 if (Shift->getOpcode() == Instruction::Shl)
1734 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1735 else
1736 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001737
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001738 // Check to see if we are shifting out any of the bits being
1739 // compared.
1740 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1741 // If we shifted bits out, the fold is not going to work out.
1742 // As a special case, check to see if this means that the
1743 // result is always true or false now.
1744 if (I.getOpcode() == Instruction::SetEQ)
1745 return ReplaceInstUsesWith(I, ConstantBool::False);
1746 if (I.getOpcode() == Instruction::SetNE)
1747 return ReplaceInstUsesWith(I, ConstantBool::True);
1748 } else {
1749 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00001750 Constant *NewAndCST;
1751 if (Shift->getOpcode() == Instruction::Shl)
1752 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
1753 else
1754 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1755 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001756 LHSI->setOperand(0, Shift->getOperand(0));
1757 WorkList.push_back(Shift); // Shift is dead.
1758 AddUsesToWorkList(I);
1759 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00001760 }
1761 }
Chris Lattner35167c32004-06-09 07:59:58 +00001762 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001763 }
1764 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001765
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001766 case Instruction::Cast: { // (setcc (cast X to larger), CI)
1767 const Type *SrcTy = LHSI->getOperand(0)->getType();
1768 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00001769 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001770 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00001771 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001772 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
1773 if (SrcBits < DestBits) {
1774 // Check to see if the comparison is always true or false.
1775 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
1776 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
1777 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
1778 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
1779 Min = ConstantExpr::getCast(Min, LHSI->getType());
1780 Max = ConstantExpr::getCast(Max, LHSI->getType());
1781 switch (I.getOpcode()) {
1782 default: assert(0 && "unknown integer comparison");
1783 case Instruction::SetEQ:
1784 return ReplaceInstUsesWith(I, ConstantBool::False);
1785 case Instruction::SetNE:
1786 return ReplaceInstUsesWith(I, ConstantBool::True);
1787 case Instruction::SetLT:
1788 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
1789 case Instruction::SetLE:
1790 return ReplaceInstUsesWith(I, ConstantExpr::getSetLE(Max, CI));
1791 case Instruction::SetGT:
1792 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
1793 case Instruction::SetGE:
1794 return ReplaceInstUsesWith(I, ConstantExpr::getSetGE(Min, CI));
1795 }
1796 }
1797
1798 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
1799 ConstantExpr::getCast(CI, SrcTy));
1800 }
1801 }
1802 break;
1803 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00001804 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
1805 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
1806 switch (I.getOpcode()) {
1807 default: break;
1808 case Instruction::SetEQ:
1809 case Instruction::SetNE: {
1810 // If we are comparing against bits always shifted out, the
1811 // comparison cannot succeed.
1812 Constant *Comp =
1813 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
1814 if (Comp != CI) {// Comparing against a bit that we know is zero.
1815 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
1816 Constant *Cst = ConstantBool::get(IsSetNE);
1817 return ReplaceInstUsesWith(I, Cst);
1818 }
1819
1820 if (LHSI->hasOneUse()) {
1821 // Otherwise strength reduce the shift into an and.
1822 unsigned ShAmtVal = ShAmt->getValue();
1823 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
1824 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
1825
1826 Constant *Mask;
1827 if (CI->getType()->isUnsigned()) {
1828 Mask = ConstantUInt::get(CI->getType(), Val);
1829 } else if (ShAmtVal != 0) {
1830 Mask = ConstantSInt::get(CI->getType(), Val);
1831 } else {
1832 Mask = ConstantInt::getAllOnesValue(CI->getType());
1833 }
1834
1835 Instruction *AndI =
1836 BinaryOperator::createAnd(LHSI->getOperand(0),
1837 Mask, LHSI->getName()+".mask");
1838 Value *And = InsertNewInstBefore(AndI, I);
1839 return new SetCondInst(I.getOpcode(), And,
1840 ConstantExpr::getUShr(CI, ShAmt));
1841 }
1842 }
1843 }
1844 }
1845 break;
1846
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001847 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00001848 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00001849 switch (I.getOpcode()) {
1850 default: break;
1851 case Instruction::SetEQ:
1852 case Instruction::SetNE: {
1853 // If we are comparing against bits always shifted out, the
1854 // comparison cannot succeed.
1855 Constant *Comp =
1856 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
1857
1858 if (Comp != CI) {// Comparing against a bit that we know is zero.
1859 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
1860 Constant *Cst = ConstantBool::get(IsSetNE);
1861 return ReplaceInstUsesWith(I, Cst);
1862 }
1863
1864 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001865 unsigned ShAmtVal = ShAmt->getValue();
1866
Chris Lattner1023b872004-09-27 16:18:50 +00001867 // Otherwise strength reduce the shift into an and.
1868 uint64_t Val = ~0ULL; // All ones.
1869 Val <<= ShAmtVal; // Shift over to the right spot.
1870
1871 Constant *Mask;
1872 if (CI->getType()->isUnsigned()) {
1873 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
1874 Val &= (1ULL << TypeBits)-1;
1875 Mask = ConstantUInt::get(CI->getType(), Val);
1876 } else {
1877 Mask = ConstantSInt::get(CI->getType(), Val);
1878 }
1879
1880 Instruction *AndI =
1881 BinaryOperator::createAnd(LHSI->getOperand(0),
1882 Mask, LHSI->getName()+".mask");
1883 Value *And = InsertNewInstBefore(AndI, I);
1884 return new SetCondInst(I.getOpcode(), And,
1885 ConstantExpr::getShl(CI, ShAmt));
1886 }
1887 break;
1888 }
1889 }
1890 }
1891 break;
Chris Lattner7e794272004-09-24 15:21:34 +00001892
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001893 case Instruction::Select:
1894 // If either operand of the select is a constant, we can fold the
1895 // comparison into the select arms, which will cause one to be
1896 // constant folded and the select turned into a bitwise or.
1897 Value *Op1 = 0, *Op2 = 0;
1898 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00001899 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001900 // Fold the known value into the constant operand.
1901 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1902 // Insert a new SetCC of the other select operand.
1903 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001904 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001905 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00001906 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001907 // Fold the known value into the constant operand.
1908 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1909 // Insert a new SetCC of the other select operand.
1910 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001911 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001912 I.getName()), I);
1913 }
Chris Lattner2dd01742004-06-09 04:24:29 +00001914 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001915
1916 if (Op1)
1917 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1918 break;
1919 }
1920
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001921 // Simplify seteq and setne instructions...
1922 if (I.getOpcode() == Instruction::SetEQ ||
1923 I.getOpcode() == Instruction::SetNE) {
1924 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1925
Chris Lattnercfbce7c2003-07-23 17:26:36 +00001926 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001927 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00001928 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1929 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00001930 case Instruction::Rem:
1931 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1932 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
1933 BO->hasOneUse() &&
1934 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
1935 if (unsigned L2 =
1936 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
1937 const Type *UTy = BO->getType()->getUnsignedVersion();
1938 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
1939 UTy, "tmp"), I);
1940 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
1941 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
1942 RHSCst, BO->getName()), I);
1943 return BinaryOperator::create(I.getOpcode(), NewRem,
1944 Constant::getNullValue(UTy));
1945 }
1946 break;
1947
Chris Lattnerc992add2003-08-13 05:33:12 +00001948 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00001949 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1950 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00001951 if (BO->hasOneUse())
1952 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1953 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00001954 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001955 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1956 // efficiently invertible, or if the add has just this one use.
1957 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00001958
Chris Lattnerc992add2003-08-13 05:33:12 +00001959 if (Value *NegVal = dyn_castNegVal(BOp1))
1960 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1961 else if (Value *NegVal = dyn_castNegVal(BOp0))
1962 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001963 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001964 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1965 BO->setName("");
1966 InsertNewInstBefore(Neg, I);
1967 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1968 }
1969 }
1970 break;
1971 case Instruction::Xor:
1972 // For the xor case, we can xor two constants together, eliminating
1973 // the explicit xor.
1974 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1975 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001976 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00001977
1978 // FALLTHROUGH
1979 case Instruction::Sub:
1980 // Replace (([sub|xor] A, B) != 0) with (A != B)
1981 if (CI->isNullValue())
1982 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1983 BO->getOperand(1));
1984 break;
1985
1986 case Instruction::Or:
1987 // If bits are being or'd in that are not present in the constant we
1988 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001989 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001990 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001991 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001992 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001993 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001994 break;
1995
1996 case Instruction::And:
1997 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001998 // If bits are being compared against that are and'd out, then the
1999 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002000 if (!ConstantExpr::getAnd(CI,
2001 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002002 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002003
Chris Lattner35167c32004-06-09 07:59:58 +00002004 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002005 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002006 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2007 Instruction::SetNE, Op0,
2008 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002009
Chris Lattnerc992add2003-08-13 05:33:12 +00002010 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2011 // to be a signed value as appropriate.
2012 if (isSignBit(BOC)) {
2013 Value *X = BO->getOperand(0);
2014 // If 'X' is not signed, insert a cast now...
2015 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002016 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002017 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002018 }
2019 return new SetCondInst(isSetNE ? Instruction::SetLT :
2020 Instruction::SetGE, X,
2021 Constant::getNullValue(X->getType()));
2022 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002023
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002024 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002025 if (CI->isNullValue() && isHighOnes(BOC)) {
2026 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002027 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002028
2029 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002030 if (NegX->getType()->isSigned()) {
2031 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2032 X = InsertCastBefore(X, DestTy, I);
2033 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002034 }
2035
2036 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002037 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002038 }
2039
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002040 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002041 default: break;
2042 }
2043 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002044 } else { // Not a SetEQ/SetNE
2045 // If the LHS is a cast from an integral value of the same size,
2046 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2047 Value *CastOp = Cast->getOperand(0);
2048 const Type *SrcTy = CastOp->getType();
2049 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2050 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2051 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2052 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2053 "Source and destination signednesses should differ!");
2054 if (Cast->getType()->isSigned()) {
2055 // If this is a signed comparison, check for comparisons in the
2056 // vicinity of zero.
2057 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2058 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002059 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002060 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2061 else if (I.getOpcode() == Instruction::SetGT &&
2062 cast<ConstantSInt>(CI)->getValue() == -1)
2063 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002064 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002065 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2066 } else {
2067 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2068 if (I.getOpcode() == Instruction::SetLT &&
2069 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2070 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002071 return BinaryOperator::createSetGT(CastOp,
2072 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002073 else if (I.getOpcode() == Instruction::SetGT &&
2074 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2075 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002076 return BinaryOperator::createSetLT(CastOp,
2077 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002078 }
2079 }
2080 }
Chris Lattnere967b342003-06-04 05:10:11 +00002081 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00002082
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002083 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00002084 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002085 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2086 return ReplaceInstUsesWith(I, ConstantBool::False);
2087 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2088 return ReplaceInstUsesWith(I, ConstantBool::True);
2089 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002090 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002091 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002092 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002093
Chris Lattnere6794492002-08-12 21:17:25 +00002094 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002095 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2096 return ReplaceInstUsesWith(I, ConstantBool::False);
2097 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2098 return ReplaceInstUsesWith(I, ConstantBool::True);
2099 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002100 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002101 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002102 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002103
2104 // Comparing against a value really close to min or max?
2105 } else if (isMinValuePlusOne(CI)) {
2106 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002107 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002108 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002109 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002110
2111 } else if (isMaxValueMinusOne(CI)) {
2112 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002113 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002114 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002115 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002116 }
Chris Lattner59611142004-02-23 05:47:48 +00002117
2118 // If we still have a setle or setge instruction, turn it into the
2119 // appropriate setlt or setgt instruction. Since the border cases have
2120 // already been handled above, this requires little checking.
2121 //
2122 if (I.getOpcode() == Instruction::SetLE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002123 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner59611142004-02-23 05:47:48 +00002124 if (I.getOpcode() == Instruction::SetGE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002125 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002126 }
2127
Chris Lattner16930792003-11-03 04:25:02 +00002128 // Test to see if the operands of the setcc are casted versions of other
2129 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002130 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2131 Value *CastOp0 = CI->getOperand(0);
2132 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002133 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002134 (I.getOpcode() == Instruction::SetEQ ||
2135 I.getOpcode() == Instruction::SetNE)) {
2136 // We keep moving the cast from the left operand over to the right
2137 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002138 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002139
2140 // If operand #1 is a cast instruction, see if we can eliminate it as
2141 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002142 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2143 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002144 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002145 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002146
2147 // If Op1 is a constant, we can fold the cast into the constant.
2148 if (Op1->getType() != Op0->getType())
2149 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2150 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2151 } else {
2152 // Otherwise, cast the RHS right before the setcc
2153 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2154 InsertNewInstBefore(cast<Instruction>(Op1), I);
2155 }
2156 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2157 }
2158
Chris Lattner6444c372003-11-03 05:17:03 +00002159 // Handle the special case of: setcc (cast bool to X), <cst>
2160 // This comes up when you have code like
2161 // int X = A < B;
2162 // if (X) ...
2163 // For generality, we handle any zero-extension of any operand comparison
2164 // with a constant.
2165 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2166 const Type *SrcTy = CastOp0->getType();
2167 const Type *DestTy = Op0->getType();
2168 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2169 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2170 // Ok, we have an expansion of operand 0 into a new type. Get the
2171 // constant value, masink off bits which are not set in the RHS. These
2172 // could be set if the destination value is signed.
2173 uint64_t ConstVal = ConstantRHS->getRawValue();
2174 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2175
2176 // If the constant we are comparing it with has high bits set, which
2177 // don't exist in the original value, the values could never be equal,
2178 // because the source would be zero extended.
2179 unsigned SrcBits =
2180 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002181 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2182 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002183 switch (I.getOpcode()) {
2184 default: assert(0 && "Unknown comparison type!");
2185 case Instruction::SetEQ:
2186 return ReplaceInstUsesWith(I, ConstantBool::False);
2187 case Instruction::SetNE:
2188 return ReplaceInstUsesWith(I, ConstantBool::True);
2189 case Instruction::SetLT:
2190 case Instruction::SetLE:
2191 if (DestTy->isSigned() && HasSignBit)
2192 return ReplaceInstUsesWith(I, ConstantBool::False);
2193 return ReplaceInstUsesWith(I, ConstantBool::True);
2194 case Instruction::SetGT:
2195 case Instruction::SetGE:
2196 if (DestTy->isSigned() && HasSignBit)
2197 return ReplaceInstUsesWith(I, ConstantBool::True);
2198 return ReplaceInstUsesWith(I, ConstantBool::False);
2199 }
2200 }
2201
2202 // Otherwise, we can replace the setcc with a setcc of the smaller
2203 // operand value.
2204 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2205 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2206 }
2207 }
2208 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002209 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002210}
2211
2212
2213
Chris Lattnere8d6c602003-03-10 19:16:08 +00002214Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002215 assert(I.getOperand(1)->getType() == Type::UByteTy);
2216 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002217 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002218
2219 // shl X, 0 == X and shr X, 0 == X
2220 // shl 0, X == 0 and shr 0, X == 0
2221 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002222 Op0 == Constant::getNullValue(Op0->getType()))
2223 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002224
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002225 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2226 if (!isLeftShift)
2227 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2228 if (CSI->isAllOnesValue())
2229 return ReplaceInstUsesWith(I, CSI);
2230
Chris Lattner183b3362004-04-09 19:05:30 +00002231 // Try to fold constant and into select arguments.
2232 if (isa<Constant>(Op0))
2233 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2234 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2235 return R;
2236
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002237 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002238 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2239 // of a signed value.
2240 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002241 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002242 if (CUI->getValue() >= TypeBits) {
2243 if (!Op0->getType()->isSigned() || isLeftShift)
2244 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2245 else {
2246 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2247 return &I;
2248 }
2249 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002250
Chris Lattnerede3fe02003-08-13 04:18:28 +00002251 // ((X*C1) << C2) == (X * (C1 << C2))
2252 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2253 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2254 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002255 return BinaryOperator::createMul(BO->getOperand(0),
2256 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002257
Chris Lattner183b3362004-04-09 19:05:30 +00002258 // Try to fold constant and into select arguments.
2259 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2260 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2261 return R;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002262
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002263 // If the operand is an bitwise operator with a constant RHS, and the
2264 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002265 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002266 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2267 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2268 bool isValid = true; // Valid only for And, Or, Xor
2269 bool highBitSet = false; // Transform if high bit of constant set?
2270
2271 switch (Op0BO->getOpcode()) {
2272 default: isValid = false; break; // Do not perform transform!
2273 case Instruction::Or:
2274 case Instruction::Xor:
2275 highBitSet = false;
2276 break;
2277 case Instruction::And:
2278 highBitSet = true;
2279 break;
2280 }
2281
2282 // If this is a signed shift right, and the high bit is modified
2283 // by the logical operation, do not perform the transformation.
2284 // The highBitSet boolean indicates the value of the high bit of
2285 // the constant which would cause it to be modified for this
2286 // operation.
2287 //
2288 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2289 uint64_t Val = Op0C->getRawValue();
2290 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2291 }
2292
2293 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002294 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002295
2296 Instruction *NewShift =
2297 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2298 Op0BO->getName());
2299 Op0BO->setName("");
2300 InsertNewInstBefore(NewShift, I);
2301
2302 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2303 NewRHS);
2304 }
2305 }
2306
Chris Lattner3204d4e2003-07-24 17:52:58 +00002307 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002308 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002309 if (ConstantUInt *ShiftAmt1C =
2310 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002311 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2312 unsigned ShiftAmt2 = CUI->getValue();
2313
2314 // Check for (A << c1) << c2 and (A >> c1) >> c2
2315 if (I.getOpcode() == Op0SI->getOpcode()) {
2316 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002317 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2318 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002319 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2320 ConstantUInt::get(Type::UByteTy, Amt));
2321 }
2322
Chris Lattnerab780df2003-07-24 18:38:56 +00002323 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2324 // signed types, we can only support the (A >> c1) << c2 configuration,
2325 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002326 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002327 // Calculate bitmask for what gets shifted off the edge...
2328 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002329 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002330 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002331 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002332 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002333
2334 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002335 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2336 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002337 InsertNewInstBefore(Mask, I);
2338
2339 // Figure out what flavor of shift we should use...
2340 if (ShiftAmt1 == ShiftAmt2)
2341 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2342 else if (ShiftAmt1 < ShiftAmt2) {
2343 return new ShiftInst(I.getOpcode(), Mask,
2344 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2345 } else {
2346 return new ShiftInst(Op0SI->getOpcode(), Mask,
2347 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2348 }
2349 }
2350 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002351 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002352
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002353 return 0;
2354}
2355
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002356enum CastType {
2357 Noop = 0,
2358 Truncate = 1,
2359 Signext = 2,
2360 Zeroext = 3
2361};
2362
2363/// getCastType - In the future, we will split the cast instruction into these
2364/// various types. Until then, we have to do the analysis here.
2365static CastType getCastType(const Type *Src, const Type *Dest) {
2366 assert(Src->isIntegral() && Dest->isIntegral() &&
2367 "Only works on integral types!");
2368 unsigned SrcSize = Src->getPrimitiveSize()*8;
2369 if (Src == Type::BoolTy) SrcSize = 1;
2370 unsigned DestSize = Dest->getPrimitiveSize()*8;
2371 if (Dest == Type::BoolTy) DestSize = 1;
2372
2373 if (SrcSize == DestSize) return Noop;
2374 if (SrcSize > DestSize) return Truncate;
2375 if (Src->isSigned()) return Signext;
2376 return Zeroext;
2377}
2378
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002379
Chris Lattner48a44f72002-05-02 17:06:02 +00002380// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2381// instruction.
2382//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002383static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002384 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002385
Chris Lattner650b6da2002-08-02 20:00:25 +00002386 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2387 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002388 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002389 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002390 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002391
Chris Lattner4fbad962004-07-21 04:27:24 +00002392 // If we are casting between pointer and integer types, treat pointers as
2393 // integers of the appropriate size for the code below.
2394 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2395 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2396 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002397
Chris Lattner48a44f72002-05-02 17:06:02 +00002398 // Allow free casting and conversion of sizes as long as the sign doesn't
2399 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002400 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002401 CastType FirstCast = getCastType(SrcTy, MidTy);
2402 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002403
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002404 // Capture the effect of these two casts. If the result is a legal cast,
2405 // the CastType is stored here, otherwise a special code is used.
2406 static const unsigned CastResult[] = {
2407 // First cast is noop
2408 0, 1, 2, 3,
2409 // First cast is a truncate
2410 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2411 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002412 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002413 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002414 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002415 };
2416
2417 unsigned Result = CastResult[FirstCast*4+SecondCast];
2418 switch (Result) {
2419 default: assert(0 && "Illegal table value!");
2420 case 0:
2421 case 1:
2422 case 2:
2423 case 3:
2424 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2425 // truncates, we could eliminate more casts.
2426 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2427 case 4:
2428 return false; // Not possible to eliminate this here.
2429 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002430 // Sign or zero extend followed by truncate is always ok if the result
2431 // is a truncate or noop.
2432 CastType ResultCast = getCastType(SrcTy, DstTy);
2433 if (ResultCast == Noop || ResultCast == Truncate)
2434 return true;
2435 // Otherwise we are still growing the value, we are only safe if the
2436 // result will match the sign/zeroextendness of the result.
2437 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002438 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002439 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002440 return false;
2441}
2442
Chris Lattner11ffd592004-07-20 05:21:00 +00002443static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002444 if (V->getType() == Ty || isa<Constant>(V)) return false;
2445 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002446 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2447 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002448 return false;
2449 return true;
2450}
2451
2452/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2453/// InsertBefore instruction. This is specialized a bit to avoid inserting
2454/// casts that are known to not do anything...
2455///
2456Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2457 Instruction *InsertBefore) {
2458 if (V->getType() == DestTy) return V;
2459 if (Constant *C = dyn_cast<Constant>(V))
2460 return ConstantExpr::getCast(C, DestTy);
2461
2462 CastInst *CI = new CastInst(V, DestTy, V->getName());
2463 InsertNewInstBefore(CI, *InsertBefore);
2464 return CI;
2465}
Chris Lattner48a44f72002-05-02 17:06:02 +00002466
2467// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002468//
Chris Lattner113f4f42002-06-25 16:13:24 +00002469Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002470 Value *Src = CI.getOperand(0);
2471
Chris Lattner48a44f72002-05-02 17:06:02 +00002472 // If the user is casting a value to the same type, eliminate this cast
2473 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002474 if (CI.getType() == Src->getType())
2475 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002476
Chris Lattner48a44f72002-05-02 17:06:02 +00002477 // If casting the result of another cast instruction, try to eliminate this
2478 // one!
2479 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002480 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002481 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002482 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002483 // This instruction now refers directly to the cast's src operand. This
2484 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002485 CI.setOperand(0, CSrc->getOperand(0));
2486 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002487 }
2488
Chris Lattner650b6da2002-08-02 20:00:25 +00002489 // If this is an A->B->A cast, and we are dealing with integral types, try
2490 // to convert this into a logical 'and' instruction.
2491 //
2492 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002493 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002494 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2495 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2496 assert(CSrc->getType() != Type::ULongTy &&
2497 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002498 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002499 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002500 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002501 }
2502 }
2503
Chris Lattner03841652004-05-25 04:29:21 +00002504 // If this is a cast to bool, turn it into the appropriate setne instruction.
2505 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002506 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002507 Constant::getNullValue(CI.getOperand(0)->getType()));
2508
Chris Lattnerd0d51602003-06-21 23:12:02 +00002509 // If casting the result of a getelementptr instruction with no offset, turn
2510 // this into a cast of the original pointer!
2511 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002512 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002513 bool AllZeroOperands = true;
2514 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2515 if (!isa<Constant>(GEP->getOperand(i)) ||
2516 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2517 AllZeroOperands = false;
2518 break;
2519 }
2520 if (AllZeroOperands) {
2521 CI.setOperand(0, GEP->getOperand(0));
2522 return &CI;
2523 }
2524 }
2525
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002526 // If we are casting a malloc or alloca to a pointer to a type of the same
2527 // size, rewrite the allocation instruction to allocate the "right" type.
2528 //
2529 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002530 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002531 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2532 // Get the type really allocated and the type casted to...
2533 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002534 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002535 if (AllocElTy->isSized() && CastElTy->isSized()) {
2536 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2537 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002538
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002539 // If the allocation is for an even multiple of the cast type size
2540 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2541 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002542 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002543 std::string Name = AI->getName(); AI->setName("");
2544 AllocationInst *New;
2545 if (isa<MallocInst>(AI))
2546 New = new MallocInst(CastElTy, Amt, Name);
2547 else
2548 New = new AllocaInst(CastElTy, Amt, Name);
2549 InsertNewInstBefore(New, *AI);
2550 return ReplaceInstUsesWith(CI, New);
2551 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002552 }
2553 }
2554
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002555 // If the source value is an instruction with only this use, we can attempt to
2556 // propagate the cast into the instruction. Also, only handle integral types
2557 // for now.
2558 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002559 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002560 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2561 const Type *DestTy = CI.getType();
2562 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2563 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2564
2565 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2566 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2567
2568 switch (SrcI->getOpcode()) {
2569 case Instruction::Add:
2570 case Instruction::Mul:
2571 case Instruction::And:
2572 case Instruction::Or:
2573 case Instruction::Xor:
2574 // If we are discarding information, or just changing the sign, rewrite.
2575 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2576 // Don't insert two casts if they cannot be eliminated. We allow two
2577 // casts to be inserted if the sizes are the same. This could only be
2578 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002579 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2580 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002581 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2582 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2583 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2584 ->getOpcode(), Op0c, Op1c);
2585 }
2586 }
2587 break;
2588 case Instruction::Shl:
2589 // Allow changing the sign of the source operand. Do not allow changing
2590 // the size of the shift, UNLESS the shift amount is a constant. We
2591 // mush not change variable sized shifts to a smaller size, because it
2592 // is undefined to shift more bits out than exist in the value.
2593 if (DestBitSize == SrcBitSize ||
2594 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2595 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2596 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2597 }
2598 break;
2599 }
2600 }
2601
Chris Lattner260ab202002-04-18 17:39:14 +00002602 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002603}
2604
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002605/// GetSelectFoldableOperands - We want to turn code that looks like this:
2606/// %C = or %A, %B
2607/// %D = select %cond, %C, %A
2608/// into:
2609/// %C = select %cond, %B, 0
2610/// %D = or %A, %C
2611///
2612/// Assuming that the specified instruction is an operand to the select, return
2613/// a bitmask indicating which operands of this instruction are foldable if they
2614/// equal the other incoming value of the select.
2615///
2616static unsigned GetSelectFoldableOperands(Instruction *I) {
2617 switch (I->getOpcode()) {
2618 case Instruction::Add:
2619 case Instruction::Mul:
2620 case Instruction::And:
2621 case Instruction::Or:
2622 case Instruction::Xor:
2623 return 3; // Can fold through either operand.
2624 case Instruction::Sub: // Can only fold on the amount subtracted.
2625 case Instruction::Shl: // Can only fold on the shift amount.
2626 case Instruction::Shr:
2627 return 1;
2628 default:
2629 return 0; // Cannot fold
2630 }
2631}
2632
2633/// GetSelectFoldableConstant - For the same transformation as the previous
2634/// function, return the identity constant that goes into the select.
2635static Constant *GetSelectFoldableConstant(Instruction *I) {
2636 switch (I->getOpcode()) {
2637 default: assert(0 && "This cannot happen!"); abort();
2638 case Instruction::Add:
2639 case Instruction::Sub:
2640 case Instruction::Or:
2641 case Instruction::Xor:
2642 return Constant::getNullValue(I->getType());
2643 case Instruction::Shl:
2644 case Instruction::Shr:
2645 return Constant::getNullValue(Type::UByteTy);
2646 case Instruction::And:
2647 return ConstantInt::getAllOnesValue(I->getType());
2648 case Instruction::Mul:
2649 return ConstantInt::get(I->getType(), 1);
2650 }
2651}
2652
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002653Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002654 Value *CondVal = SI.getCondition();
2655 Value *TrueVal = SI.getTrueValue();
2656 Value *FalseVal = SI.getFalseValue();
2657
2658 // select true, X, Y -> X
2659 // select false, X, Y -> Y
2660 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002661 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002662 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002663 else {
2664 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002665 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002666 }
Chris Lattner533bc492004-03-30 19:37:13 +00002667
2668 // select C, X, X -> X
2669 if (TrueVal == FalseVal)
2670 return ReplaceInstUsesWith(SI, TrueVal);
2671
Chris Lattner1c631e82004-04-08 04:43:23 +00002672 if (SI.getType() == Type::BoolTy)
2673 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2674 if (C == ConstantBool::True) {
2675 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002676 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002677 } else {
2678 // Change: A = select B, false, C --> A = and !B, C
2679 Value *NotCond =
2680 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2681 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002682 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002683 }
2684 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2685 if (C == ConstantBool::False) {
2686 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002687 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002688 } else {
2689 // Change: A = select B, C, true --> A = or !B, C
2690 Value *NotCond =
2691 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2692 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002693 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002694 }
2695 }
2696
Chris Lattner183b3362004-04-09 19:05:30 +00002697 // Selecting between two integer constants?
2698 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2699 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2700 // select C, 1, 0 -> cast C to int
2701 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2702 return new CastInst(CondVal, SI.getType());
2703 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2704 // select C, 0, 1 -> cast !C to int
2705 Value *NotCond =
2706 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002707 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002708 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002709 }
Chris Lattner35167c32004-06-09 07:59:58 +00002710
2711 // If one of the constants is zero (we know they can't both be) and we
2712 // have a setcc instruction with zero, and we have an 'and' with the
2713 // non-constant value, eliminate this whole mess. This corresponds to
2714 // cases like this: ((X & 27) ? 27 : 0)
2715 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2716 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2717 if ((IC->getOpcode() == Instruction::SetEQ ||
2718 IC->getOpcode() == Instruction::SetNE) &&
2719 isa<ConstantInt>(IC->getOperand(1)) &&
2720 cast<Constant>(IC->getOperand(1))->isNullValue())
2721 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2722 if (ICA->getOpcode() == Instruction::And &&
2723 isa<ConstantInt>(ICA->getOperand(1)) &&
2724 (ICA->getOperand(1) == TrueValC ||
2725 ICA->getOperand(1) == FalseValC) &&
2726 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2727 // Okay, now we know that everything is set up, we just don't
2728 // know whether we have a setne or seteq and whether the true or
2729 // false val is the zero.
2730 bool ShouldNotVal = !TrueValC->isNullValue();
2731 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2732 Value *V = ICA;
2733 if (ShouldNotVal)
2734 V = InsertNewInstBefore(BinaryOperator::create(
2735 Instruction::Xor, V, ICA->getOperand(1)), SI);
2736 return ReplaceInstUsesWith(SI, V);
2737 }
Chris Lattner533bc492004-03-30 19:37:13 +00002738 }
Chris Lattner623fba12004-04-10 22:21:27 +00002739
2740 // See if we are selecting two values based on a comparison of the two values.
2741 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2742 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2743 // Transform (X == Y) ? X : Y -> Y
2744 if (SCI->getOpcode() == Instruction::SetEQ)
2745 return ReplaceInstUsesWith(SI, FalseVal);
2746 // Transform (X != Y) ? X : Y -> X
2747 if (SCI->getOpcode() == Instruction::SetNE)
2748 return ReplaceInstUsesWith(SI, TrueVal);
2749 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2750
2751 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2752 // Transform (X == Y) ? Y : X -> X
2753 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00002754 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002755 // Transform (X != Y) ? Y : X -> Y
2756 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00002757 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002758 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2759 }
2760 }
Chris Lattner1c631e82004-04-08 04:43:23 +00002761
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002762 // See if we can fold the select into one of our operands.
2763 if (SI.getType()->isInteger()) {
2764 // See the comment above GetSelectFoldableOperands for a description of the
2765 // transformation we are doing here.
2766 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2767 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2768 !isa<Constant>(FalseVal))
2769 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2770 unsigned OpToFold = 0;
2771 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2772 OpToFold = 1;
2773 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2774 OpToFold = 2;
2775 }
2776
2777 if (OpToFold) {
2778 Constant *C = GetSelectFoldableConstant(TVI);
2779 std::string Name = TVI->getName(); TVI->setName("");
2780 Instruction *NewSel =
2781 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2782 Name);
2783 InsertNewInstBefore(NewSel, SI);
2784 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2785 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2786 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2787 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2788 else {
2789 assert(0 && "Unknown instruction!!");
2790 }
2791 }
2792 }
2793
2794 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2795 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2796 !isa<Constant>(TrueVal))
2797 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2798 unsigned OpToFold = 0;
2799 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2800 OpToFold = 1;
2801 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2802 OpToFold = 2;
2803 }
2804
2805 if (OpToFold) {
2806 Constant *C = GetSelectFoldableConstant(FVI);
2807 std::string Name = FVI->getName(); FVI->setName("");
2808 Instruction *NewSel =
2809 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2810 Name);
2811 InsertNewInstBefore(NewSel, SI);
2812 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2813 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2814 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2815 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2816 else {
2817 assert(0 && "Unknown instruction!!");
2818 }
2819 }
2820 }
2821 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002822 return 0;
2823}
2824
2825
Chris Lattner970c33a2003-06-19 17:00:31 +00002826// CallInst simplification
2827//
2828Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00002829 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2830 // visitCallSite.
2831 if (Function *F = CI.getCalledFunction())
2832 switch (F->getIntrinsicID()) {
2833 case Intrinsic::memmove:
2834 case Intrinsic::memcpy:
2835 case Intrinsic::memset:
2836 // memmove/cpy/set of zero bytes is a noop.
2837 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2838 if (NumBytes->isNullValue())
2839 return EraseInstFromFunction(CI);
2840 }
2841 break;
2842 default:
2843 break;
2844 }
2845
Chris Lattneraec3d942003-10-07 22:32:43 +00002846 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00002847}
2848
2849// InvokeInst simplification
2850//
2851Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00002852 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00002853}
2854
Chris Lattneraec3d942003-10-07 22:32:43 +00002855// visitCallSite - Improvements for call and invoke instructions.
2856//
2857Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002858 bool Changed = false;
2859
2860 // If the callee is a constexpr cast of a function, attempt to move the cast
2861 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00002862 if (transformConstExprCastCall(CS)) return 0;
2863
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002864 Value *Callee = CS.getCalledValue();
2865 const PointerType *PTy = cast<PointerType>(Callee->getType());
2866 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2867 if (FTy->isVarArg()) {
2868 // See if we can optimize any arguments passed through the varargs area of
2869 // the call.
2870 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2871 E = CS.arg_end(); I != E; ++I)
2872 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2873 // If this cast does not effect the value passed through the varargs
2874 // area, we can eliminate the use of the cast.
2875 Value *Op = CI->getOperand(0);
2876 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2877 *I = Op;
2878 Changed = true;
2879 }
2880 }
2881 }
Chris Lattneraec3d942003-10-07 22:32:43 +00002882
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002883 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00002884}
2885
Chris Lattner970c33a2003-06-19 17:00:31 +00002886// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2887// attempt to move the cast to the arguments of the call/invoke.
2888//
2889bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2890 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2891 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00002892 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00002893 return false;
Reid Spencer87436872004-07-18 00:38:32 +00002894 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00002895 Instruction *Caller = CS.getInstruction();
2896
2897 // Okay, this is a cast from a function to a different type. Unless doing so
2898 // would cause a type conversion of one of our arguments, change this call to
2899 // be a direct call with arguments casted to the appropriate types.
2900 //
2901 const FunctionType *FT = Callee->getFunctionType();
2902 const Type *OldRetTy = Caller->getType();
2903
Chris Lattner1f7942f2004-01-14 06:06:08 +00002904 // Check to see if we are changing the return type...
2905 if (OldRetTy != FT->getReturnType()) {
2906 if (Callee->isExternal() &&
2907 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2908 !Caller->use_empty())
2909 return false; // Cannot transform this return value...
2910
2911 // If the callsite is an invoke instruction, and the return value is used by
2912 // a PHI node in a successor, we cannot change the return type of the call
2913 // because there is no place to put the cast instruction (without breaking
2914 // the critical edge). Bail out in this case.
2915 if (!Caller->use_empty())
2916 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2917 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2918 UI != E; ++UI)
2919 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2920 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002921 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00002922 return false;
2923 }
Chris Lattner970c33a2003-06-19 17:00:31 +00002924
2925 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2926 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2927
2928 CallSite::arg_iterator AI = CS.arg_begin();
2929 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2930 const Type *ParamTy = FT->getParamType(i);
2931 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2932 if (Callee->isExternal() && !isConvertible) return false;
2933 }
2934
2935 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2936 Callee->isExternal())
2937 return false; // Do not delete arguments unless we have a function body...
2938
2939 // Okay, we decided that this is a safe thing to do: go ahead and start
2940 // inserting cast instructions as necessary...
2941 std::vector<Value*> Args;
2942 Args.reserve(NumActualArgs);
2943
2944 AI = CS.arg_begin();
2945 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2946 const Type *ParamTy = FT->getParamType(i);
2947 if ((*AI)->getType() == ParamTy) {
2948 Args.push_back(*AI);
2949 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00002950 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2951 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00002952 }
2953 }
2954
2955 // If the function takes more arguments than the call was taking, add them
2956 // now...
2957 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2958 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2959
2960 // If we are removing arguments to the function, emit an obnoxious warning...
2961 if (FT->getNumParams() < NumActualArgs)
2962 if (!FT->isVarArg()) {
2963 std::cerr << "WARNING: While resolving call to function '"
2964 << Callee->getName() << "' arguments were dropped!\n";
2965 } else {
2966 // Add all of the arguments in their promoted form to the arg list...
2967 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2968 const Type *PTy = getPromotedType((*AI)->getType());
2969 if (PTy != (*AI)->getType()) {
2970 // Must promote to pass through va_arg area!
2971 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2972 InsertNewInstBefore(Cast, *Caller);
2973 Args.push_back(Cast);
2974 } else {
2975 Args.push_back(*AI);
2976 }
2977 }
2978 }
2979
2980 if (FT->getReturnType() == Type::VoidTy)
2981 Caller->setName(""); // Void type should not have a name...
2982
2983 Instruction *NC;
2984 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002985 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00002986 Args, Caller->getName(), Caller);
2987 } else {
2988 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2989 }
2990
2991 // Insert a cast of the return type as necessary...
2992 Value *NV = NC;
2993 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2994 if (NV->getType() != Type::VoidTy) {
2995 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00002996
2997 // If this is an invoke instruction, we should insert it after the first
2998 // non-phi, instruction in the normal successor block.
2999 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3000 BasicBlock::iterator I = II->getNormalDest()->begin();
3001 while (isa<PHINode>(I)) ++I;
3002 InsertNewInstBefore(NC, *I);
3003 } else {
3004 // Otherwise, it's a call, just insert cast right after the call instr
3005 InsertNewInstBefore(NC, *Caller);
3006 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003007 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003008 } else {
3009 NV = Constant::getNullValue(Caller->getType());
3010 }
3011 }
3012
3013 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3014 Caller->replaceAllUsesWith(NV);
3015 Caller->getParent()->getInstList().erase(Caller);
3016 removeFromWorkList(Caller);
3017 return true;
3018}
3019
3020
Chris Lattner48a44f72002-05-02 17:06:02 +00003021
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003022// PHINode simplification
3023//
Chris Lattner113f4f42002-06-25 16:13:24 +00003024Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00003025 if (Value *V = hasConstantValue(&PN))
3026 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00003027
3028 // If the only user of this instruction is a cast instruction, and all of the
3029 // incoming values are constants, change this PHI to merge together the casted
3030 // constants.
3031 if (PN.hasOneUse())
3032 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3033 if (CI->getType() != PN.getType()) { // noop casts will be folded
3034 bool AllConstant = true;
3035 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3036 if (!isa<Constant>(PN.getIncomingValue(i))) {
3037 AllConstant = false;
3038 break;
3039 }
3040 if (AllConstant) {
3041 // Make a new PHI with all casted values.
3042 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3043 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3044 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3045 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3046 PN.getIncomingBlock(i));
3047 }
3048
3049 // Update the cast instruction.
3050 CI->setOperand(0, New);
3051 WorkList.push_back(CI); // revisit the cast instruction to fold.
3052 WorkList.push_back(New); // Make sure to revisit the new Phi
3053 return &PN; // PN is now dead!
3054 }
3055 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003056 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003057}
3058
Chris Lattner69193f92004-04-05 01:30:19 +00003059static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3060 Instruction *InsertPoint,
3061 InstCombiner *IC) {
3062 unsigned PS = IC->getTargetData().getPointerSize();
3063 const Type *VTy = V->getType();
3064 Instruction *Cast;
3065 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3066 // We must insert a cast to ensure we sign-extend.
3067 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3068 V->getName()), *InsertPoint);
3069 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3070 *InsertPoint);
3071}
3072
Chris Lattner48a44f72002-05-02 17:06:02 +00003073
Chris Lattner113f4f42002-06-25 16:13:24 +00003074Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003075 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003076 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003077 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003078 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003079 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003080
3081 bool HasZeroPointerIndex = false;
3082 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3083 HasZeroPointerIndex = C->isNullValue();
3084
3085 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003086 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003087
Chris Lattner69193f92004-04-05 01:30:19 +00003088 // Eliminate unneeded casts for indices.
3089 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003090 gep_type_iterator GTI = gep_type_begin(GEP);
3091 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3092 if (isa<SequentialType>(*GTI)) {
3093 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3094 Value *Src = CI->getOperand(0);
3095 const Type *SrcTy = Src->getType();
3096 const Type *DestTy = CI->getType();
3097 if (Src->getType()->isInteger()) {
3098 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3099 // We can always eliminate a cast from ulong or long to the other.
3100 // We can always eliminate a cast from uint to int or the other on
3101 // 32-bit pointer platforms.
3102 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3103 MadeChange = true;
3104 GEP.setOperand(i, Src);
3105 }
3106 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3107 SrcTy->getPrimitiveSize() == 4) {
3108 // We can always eliminate a cast from int to [u]long. We can
3109 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3110 // pointer target.
3111 if (SrcTy->isSigned() ||
3112 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3113 MadeChange = true;
3114 GEP.setOperand(i, Src);
3115 }
Chris Lattner69193f92004-04-05 01:30:19 +00003116 }
3117 }
3118 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003119 // If we are using a wider index than needed for this platform, shrink it
3120 // to what we need. If the incoming value needs a cast instruction,
3121 // insert it. This explicit cast can make subsequent optimizations more
3122 // obvious.
3123 Value *Op = GEP.getOperand(i);
3124 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003125 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003126 GEP.setOperand(i, ConstantExpr::getCast(C,
3127 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003128 MadeChange = true;
3129 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003130 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3131 Op->getName()), GEP);
3132 GEP.setOperand(i, Op);
3133 MadeChange = true;
3134 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003135
3136 // If this is a constant idx, make sure to canonicalize it to be a signed
3137 // operand, otherwise CSE and other optimizations are pessimized.
3138 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3139 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3140 CUI->getType()->getSignedVersion()));
3141 MadeChange = true;
3142 }
Chris Lattner69193f92004-04-05 01:30:19 +00003143 }
3144 if (MadeChange) return &GEP;
3145
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003146 // Combine Indices - If the source pointer to this getelementptr instruction
3147 // is a getelementptr instruction, combine the indices of the two
3148 // getelementptr instructions into a single instruction.
3149 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003150 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003151 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003152 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003153 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003154 if (CE->getOpcode() == Instruction::GetElementPtr)
3155 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3156 }
3157
3158 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003159 // Note that if our source is a gep chain itself that we wait for that
3160 // chain to be resolved before we perform this transformation. This
3161 // avoids us creating a TON of code in some cases.
3162 //
3163 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3164 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3165 return 0; // Wait until our source is folded to completion.
3166
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003167 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003168
3169 // Find out whether the last index in the source GEP is a sequential idx.
3170 bool EndsWithSequential = false;
3171 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3172 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003173 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003174
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003175 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003176 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003177 // Replace: gep (gep %P, long B), long A, ...
3178 // With: T = long A+B; gep %P, T, ...
3179 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003180 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003181 if (SO1 == Constant::getNullValue(SO1->getType())) {
3182 Sum = GO1;
3183 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3184 Sum = SO1;
3185 } else {
3186 // If they aren't the same type, convert both to an integer of the
3187 // target's pointer size.
3188 if (SO1->getType() != GO1->getType()) {
3189 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3190 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3191 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3192 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3193 } else {
3194 unsigned PS = TD->getPointerSize();
3195 Instruction *Cast;
3196 if (SO1->getType()->getPrimitiveSize() == PS) {
3197 // Convert GO1 to SO1's type.
3198 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3199
3200 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3201 // Convert SO1 to GO1's type.
3202 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3203 } else {
3204 const Type *PT = TD->getIntPtrType();
3205 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3206 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3207 }
3208 }
3209 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003210 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3211 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3212 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003213 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3214 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003215 }
Chris Lattner69193f92004-04-05 01:30:19 +00003216 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003217
3218 // Recycle the GEP we already have if possible.
3219 if (SrcGEPOperands.size() == 2) {
3220 GEP.setOperand(0, SrcGEPOperands[0]);
3221 GEP.setOperand(1, Sum);
3222 return &GEP;
3223 } else {
3224 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3225 SrcGEPOperands.end()-1);
3226 Indices.push_back(Sum);
3227 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3228 }
Chris Lattner69193f92004-04-05 01:30:19 +00003229 } else if (isa<Constant>(*GEP.idx_begin()) &&
3230 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003231 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003232 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003233 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3234 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003235 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3236 }
3237
3238 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003239 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003240
Chris Lattner5f667a62004-05-07 22:09:22 +00003241 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003242 // GEP of global variable. If all of the indices for this GEP are
3243 // constants, we can promote this to a constexpr instead of an instruction.
3244
3245 // Scan for nonconstants...
3246 std::vector<Constant*> Indices;
3247 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3248 for (; I != E && isa<Constant>(*I); ++I)
3249 Indices.push_back(cast<Constant>(*I));
3250
3251 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003252 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003253
3254 // Replace all uses of the GEP with the new constexpr...
3255 return ReplaceInstUsesWith(GEP, CE);
3256 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003257 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003258 if (CE->getOpcode() == Instruction::Cast) {
3259 if (HasZeroPointerIndex) {
3260 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3261 // into : GEP [10 x ubyte]* X, long 0, ...
3262 //
3263 // This occurs when the program declares an array extern like "int X[];"
3264 //
3265 Constant *X = CE->getOperand(0);
3266 const PointerType *CPTy = cast<PointerType>(CE->getType());
3267 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3268 if (const ArrayType *XATy =
3269 dyn_cast<ArrayType>(XTy->getElementType()))
3270 if (const ArrayType *CATy =
3271 dyn_cast<ArrayType>(CPTy->getElementType()))
3272 if (CATy->getElementType() == XATy->getElementType()) {
3273 // At this point, we know that the cast source type is a pointer
3274 // to an array of the same type as the destination pointer
3275 // array. Because the array type is never stepped over (there
3276 // is a leading zero) we can fold the cast into this GEP.
3277 GEP.setOperand(0, X);
3278 return &GEP;
3279 }
3280 }
3281 }
Chris Lattnerca081252001-12-14 16:52:21 +00003282 }
3283
Chris Lattnerca081252001-12-14 16:52:21 +00003284 return 0;
3285}
3286
Chris Lattner1085bdf2002-11-04 16:18:53 +00003287Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3288 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3289 if (AI.isArrayAllocation()) // Check C != 1
3290 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3291 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003292 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003293
3294 // Create and insert the replacement instruction...
3295 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003296 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003297 else {
3298 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003299 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003300 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003301
3302 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003303
3304 // Scan to the end of the allocation instructions, to skip over a block of
3305 // allocas if possible...
3306 //
3307 BasicBlock::iterator It = New;
3308 while (isa<AllocationInst>(*It)) ++It;
3309
3310 // Now that I is pointing to the first non-allocation-inst in the block,
3311 // insert our getelementptr instruction...
3312 //
Chris Lattner69193f92004-04-05 01:30:19 +00003313 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003314 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3315
3316 // Now make everything use the getelementptr instead of the original
3317 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003318 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003319 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003320
3321 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3322 // Note that we only do this for alloca's, because malloc should allocate and
3323 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003324 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3325 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003326 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3327
Chris Lattner1085bdf2002-11-04 16:18:53 +00003328 return 0;
3329}
3330
Chris Lattner8427bff2003-12-07 01:24:23 +00003331Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3332 Value *Op = FI.getOperand(0);
3333
3334 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3335 if (CastInst *CI = dyn_cast<CastInst>(Op))
3336 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3337 FI.setOperand(0, CI->getOperand(0));
3338 return &FI;
3339 }
3340
Chris Lattnerf3a36602004-02-28 04:57:37 +00003341 // If we have 'free null' delete the instruction. This can happen in stl code
3342 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00003343 if (isa<ConstantPointerNull>(Op))
3344 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003345
Chris Lattner8427bff2003-12-07 01:24:23 +00003346 return 0;
3347}
3348
3349
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003350/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3351/// constantexpr, return the constant value being addressed by the constant
3352/// expression, or null if something is funny.
3353///
3354static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003355 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003356 return 0; // Do not allow stepping over the value!
3357
3358 // Loop over all of the operands, tracking down which value we are
3359 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003360 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3361 for (++I; I != E; ++I)
3362 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3363 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3364 assert(CU->getValue() < STy->getNumElements() &&
3365 "Struct index out of range!");
3366 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003367 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003368 } else if (isa<ConstantAggregateZero>(C)) {
3369 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3370 } else {
3371 return 0;
3372 }
3373 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3374 const ArrayType *ATy = cast<ArrayType>(*I);
3375 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3376 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003377 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003378 else if (isa<ConstantAggregateZero>(C))
3379 C = Constant::getNullValue(ATy->getElementType());
3380 else
3381 return 0;
3382 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003383 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003384 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003385 return C;
3386}
3387
Chris Lattner35e24772004-07-13 01:49:43 +00003388static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3389 User *CI = cast<User>(LI.getOperand(0));
3390
3391 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3392 if (const PointerType *SrcTy =
3393 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3394 const Type *SrcPTy = SrcTy->getElementType();
3395 if (SrcPTy->isSized() && DestPTy->isSized() &&
3396 IC.getTargetData().getTypeSize(SrcPTy) ==
3397 IC.getTargetData().getTypeSize(DestPTy) &&
3398 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3399 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3400 // Okay, we are casting from one integer or pointer type to another of
3401 // the same size. Instead of casting the pointer before the load, cast
3402 // the result of the loaded value.
3403 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003404 CI->getName(),
3405 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003406 // Now cast the result of the load.
3407 return new CastInst(NewLoad, LI.getType());
3408 }
3409 }
3410 return 0;
3411}
3412
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003413/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003414/// from this value cannot trap. If it is not obviously safe to load from the
3415/// specified pointer, we do a quick local scan of the basic block containing
3416/// ScanFrom, to determine if the address is already accessed.
3417static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3418 // If it is an alloca or global variable, it is always safe to load from.
3419 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3420
3421 // Otherwise, be a little bit agressive by scanning the local block where we
3422 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003423 // from/to. If so, the previous load or store would have already trapped,
3424 // so there is no harm doing an extra load (also, CSE will later eliminate
3425 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003426 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3427
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003428 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003429 --BBI;
3430
3431 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3432 if (LI->getOperand(0) == V) return true;
3433 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3434 if (SI->getOperand(1) == V) return true;
3435
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003436 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003437 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003438}
3439
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003440Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3441 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003442
Chris Lattner6679e462004-04-14 03:28:36 +00003443 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003444 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattner6679e462004-04-14 03:28:36 +00003445 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003446
3447 // Instcombine load (constant global) into the value loaded...
3448 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00003449 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003450 return ReplaceInstUsesWith(LI, GV->getInitializer());
3451
3452 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3453 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattner35e24772004-07-13 01:49:43 +00003454 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer87436872004-07-18 00:38:32 +00003455 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3456 if (GV->isConstant() && !GV->isExternal())
3457 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3458 return ReplaceInstUsesWith(LI, V);
Chris Lattner35e24772004-07-13 01:49:43 +00003459 } else if (CE->getOpcode() == Instruction::Cast) {
3460 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3461 return Res;
3462 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003463
3464 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003465 if (CastInst *CI = dyn_cast<CastInst>(Op))
3466 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3467 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003468
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003469 if (!LI.isVolatile() && Op->hasOneUse()) {
3470 // Change select and PHI nodes to select values instead of addresses: this
3471 // helps alias analysis out a lot, allows many others simplifications, and
3472 // exposes redundancy in the code.
3473 //
3474 // Note that we cannot do the transformation unless we know that the
3475 // introduced loads cannot trap! Something like this is valid as long as
3476 // the condition is always false: load (select bool %C, int* null, int* %G),
3477 // but it would not be valid if we transformed it to load from null
3478 // unconditionally.
3479 //
3480 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3481 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003482 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3483 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003484 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003485 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003486 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003487 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003488 return new SelectInst(SI->getCondition(), V1, V2);
3489 }
3490
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003491 // load (select (cond, null, P)) -> load P
3492 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3493 if (C->isNullValue()) {
3494 LI.setOperand(0, SI->getOperand(2));
3495 return &LI;
3496 }
3497
3498 // load (select (cond, P, null)) -> load P
3499 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3500 if (C->isNullValue()) {
3501 LI.setOperand(0, SI->getOperand(1));
3502 return &LI;
3503 }
3504
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003505 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3506 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003507 bool Safe = PN->getParent() == LI.getParent();
3508
3509 // Scan all of the instructions between the PHI and the load to make
3510 // sure there are no instructions that might possibly alter the value
3511 // loaded from the PHI.
3512 if (Safe) {
3513 BasicBlock::iterator I = &LI;
3514 for (--I; !isa<PHINode>(I); --I)
3515 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3516 Safe = false;
3517 break;
3518 }
3519 }
3520
3521 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003522 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003523 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003524 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003525
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003526 if (Safe) {
3527 // Create the PHI.
3528 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3529 InsertNewInstBefore(NewPN, *PN);
3530 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3531
3532 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3533 BasicBlock *BB = PN->getIncomingBlock(i);
3534 Value *&TheLoad = LoadMap[BB];
3535 if (TheLoad == 0) {
3536 Value *InVal = PN->getIncomingValue(i);
3537 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3538 InVal->getName()+".val"),
3539 *BB->getTerminator());
3540 }
3541 NewPN->addIncoming(TheLoad, BB);
3542 }
3543 return ReplaceInstUsesWith(LI, NewPN);
3544 }
3545 }
3546 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003547 return 0;
3548}
3549
3550
Chris Lattner9eef8a72003-06-04 04:46:00 +00003551Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3552 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003553 Value *X;
3554 BasicBlock *TrueDest;
3555 BasicBlock *FalseDest;
3556 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3557 !isa<Constant>(X)) {
3558 // Swap Destinations and condition...
3559 BI.setCondition(X);
3560 BI.setSuccessor(0, FalseDest);
3561 BI.setSuccessor(1, TrueDest);
3562 return &BI;
3563 }
3564
3565 // Cannonicalize setne -> seteq
3566 Instruction::BinaryOps Op; Value *Y;
3567 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3568 TrueDest, FalseDest)))
3569 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3570 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3571 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3572 std::string Name = I->getName(); I->setName("");
3573 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3574 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003575 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003576 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003577 BI.setSuccessor(0, FalseDest);
3578 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003579 removeFromWorkList(I);
3580 I->getParent()->getInstList().erase(I);
3581 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003582 return &BI;
3583 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003584
Chris Lattner9eef8a72003-06-04 04:46:00 +00003585 return 0;
3586}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003587
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003588Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3589 Value *Cond = SI.getCondition();
3590 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3591 if (I->getOpcode() == Instruction::Add)
3592 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3593 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3594 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3595 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3596 AddRHS));
3597 SI.setOperand(0, I->getOperand(0));
3598 WorkList.push_back(I);
3599 return &SI;
3600 }
3601 }
3602 return 0;
3603}
3604
Chris Lattnerca081252001-12-14 16:52:21 +00003605
Chris Lattner99f48c62002-09-02 04:59:56 +00003606void InstCombiner::removeFromWorkList(Instruction *I) {
3607 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3608 WorkList.end());
3609}
3610
Chris Lattner113f4f42002-06-25 16:13:24 +00003611bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003612 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003613 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003614
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003615 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3616 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003617
Chris Lattnerca081252001-12-14 16:52:21 +00003618
3619 while (!WorkList.empty()) {
3620 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3621 WorkList.pop_back();
3622
Misha Brukman632df282002-10-29 23:06:16 +00003623 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003624 // Check to see if we can DIE the instruction...
3625 if (isInstructionTriviallyDead(I)) {
3626 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003627 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003628 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003629 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003630
3631 I->getParent()->getInstList().erase(I);
3632 removeFromWorkList(I);
3633 continue;
3634 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003635
Misha Brukman632df282002-10-29 23:06:16 +00003636 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003637 if (Constant *C = ConstantFoldInstruction(I)) {
3638 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003639 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003640 ReplaceInstUsesWith(*I, C);
3641
Chris Lattner99f48c62002-09-02 04:59:56 +00003642 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003643 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003644 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003645 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003646 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003647
Chris Lattnerca081252001-12-14 16:52:21 +00003648 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003649 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003650 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003651 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003652 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003653 DEBUG(std::cerr << "IC: Old = " << *I
3654 << " New = " << *Result);
3655
Chris Lattner396dbfe2004-06-09 05:08:07 +00003656 // Everything uses the new instruction now.
3657 I->replaceAllUsesWith(Result);
3658
3659 // Push the new instruction and any users onto the worklist.
3660 WorkList.push_back(Result);
3661 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003662
3663 // Move the name to the new instruction first...
3664 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003665 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003666
3667 // Insert the new instruction into the basic block...
3668 BasicBlock *InstParent = I->getParent();
3669 InstParent->getInstList().insert(I, Result);
3670
Chris Lattner63d75af2004-05-01 23:27:23 +00003671 // Make sure that we reprocess all operands now that we reduced their
3672 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003673 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3674 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3675 WorkList.push_back(OpI);
3676
Chris Lattner396dbfe2004-06-09 05:08:07 +00003677 // Instructions can end up on the worklist more than once. Make sure
3678 // we do not process an instruction that has been deleted.
3679 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003680
3681 // Erase the old instruction.
3682 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003683 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003684 DEBUG(std::cerr << "IC: MOD = " << *I);
3685
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003686 // If the instruction was modified, it's possible that it is now dead.
3687 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003688 if (isInstructionTriviallyDead(I)) {
3689 // Make sure we process all operands now that we are reducing their
3690 // use counts.
3691 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3692 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3693 WorkList.push_back(OpI);
3694
3695 // Instructions may end up in the worklist more than once. Erase all
3696 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003697 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003698 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003699 } else {
3700 WorkList.push_back(Result);
3701 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003702 }
Chris Lattner053c0932002-05-14 15:24:07 +00003703 }
Chris Lattner260ab202002-04-18 17:39:14 +00003704 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003705 }
3706 }
3707
Chris Lattner260ab202002-04-18 17:39:14 +00003708 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003709}
3710
Brian Gaeke38b79e82004-07-27 17:43:21 +00003711FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003712 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003713}
Brian Gaeke960707c2003-11-11 22:41:34 +00003714