blob: 826e2c765e7b92a10aa11d262aa84c323ca8bb10 [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 Lattner7d2a5392004-03-13 23:54:27 +000051#include "Support/Debug.h"
Chris Lattnerbf3a0992002-10-01 22:38:41 +000052#include "Support/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000054using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000055
Chris Lattner260ab202002-04-18 17:39:14 +000056namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000057 Statistic<> NumCombined ("instcombine", "Number of insts combined");
58 Statistic<> NumConstProp("instcombine", "Number of constant folds");
59 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
60
Chris Lattnerc8e66542002-04-27 06:56:12 +000061 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000062 public InstVisitor<InstCombiner, Instruction*> {
63 // Worklist of all of the instructions that need to be simplified.
64 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000065 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000066
Chris Lattner51ea1272004-02-28 05:22:00 +000067 /// AddUsersToWorkList - When an instruction is simplified, add all users of
68 /// the instruction to the work lists because they might get more simplified
69 /// now.
70 ///
71 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000072 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000073 UI != UE; ++UI)
74 WorkList.push_back(cast<Instruction>(*UI));
75 }
76
Chris Lattner51ea1272004-02-28 05:22:00 +000077 /// AddUsesToWorkList - When an instruction is simplified, add operands to
78 /// the work lists because they might get more simplified now.
79 ///
80 void AddUsesToWorkList(Instruction &I) {
81 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83 WorkList.push_back(Op);
84 }
85
Chris Lattner99f48c62002-09-02 04:59:56 +000086 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000088 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000089 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000090
Chris Lattnerf12cc842002-04-28 21:27:06 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000092 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000093 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000094 }
95
Chris Lattner69193f92004-04-05 01:30:19 +000096 TargetData &getTargetData() const { return *TD; }
97
Chris Lattner260ab202002-04-18 17:39:14 +000098 // Visitation implementation - Implement instruction combining for different
99 // instruction types. The semantics are as follows:
100 // Return Value:
101 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000102 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // otherwise - Change was made, replace I with returned instruction
104 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000105 Instruction *visitAdd(BinaryOperator &I);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitMul(BinaryOperator &I);
108 Instruction *visitDiv(BinaryOperator &I);
109 Instruction *visitRem(BinaryOperator &I);
110 Instruction *visitAnd(BinaryOperator &I);
111 Instruction *visitOr (BinaryOperator &I);
112 Instruction *visitXor(BinaryOperator &I);
113 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000114 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000115 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000116 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000121 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000122 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000123 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000124 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner260ab202002-04-18 17:39:14 +0000125
126 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000127 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000128
Chris Lattner970c33a2003-06-19 17:00:31 +0000129 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000130 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000131 bool transformConstExprCastCall(CallSite CS);
132
Chris Lattner69193f92004-04-05 01:30:19 +0000133 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000134 // InsertNewInstBefore - insert an instruction New before instruction Old
135 // in the program. Add the new instruction to the worklist.
136 //
Chris Lattnere79e8542004-02-23 06:38:22 +0000137 Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000138 assert(New && New->getParent() == 0 &&
139 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000140 BasicBlock *BB = Old.getParent();
141 BB->getInstList().insert(&Old, New); // Insert inst
142 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000143 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000144 }
145
146 // ReplaceInstUsesWith - This method is to be used when an instruction is
147 // found to be dead, replacable with another preexisting expression. Here
148 // we add all uses of I to the worklist, replace all uses of I with the new
149 // value, then return I, so that the inst combiner will know that I was
150 // modified.
151 //
152 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000153 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000154 if (&I != V) {
155 I.replaceAllUsesWith(V);
156 return &I;
157 } else {
158 // If we are replacing the instruction with itself, this must be in a
159 // segment of unreachable code, so just clobber the instruction.
160 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
161 return &I;
162 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000163 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000164
165 // EraseInstFromFunction - When dealing with an instruction that has side
166 // effects or produces a void value, we can't rely on DCE to delete the
167 // instruction. Instead, visit methods should return the value returned by
168 // this function.
169 Instruction *EraseInstFromFunction(Instruction &I) {
170 assert(I.use_empty() && "Cannot erase instruction that is used!");
171 AddUsesToWorkList(I);
172 removeFromWorkList(&I);
173 I.getParent()->getInstList().erase(&I);
174 return 0; // Don't do anything with FI
175 }
176
177
Chris Lattner3ac7c262003-08-13 20:16:26 +0000178 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000179 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
180 /// InsertBefore instruction. This is specialized a bit to avoid inserting
181 /// casts that are known to not do anything...
182 ///
183 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
184 Instruction *InsertBefore);
185
Chris Lattner7fb29e12003-03-11 00:12:48 +0000186 // SimplifyCommutative - This performs a few simplifications for commutative
187 // operators...
188 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000189
190 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
191 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner260ab202002-04-18 17:39:14 +0000192 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000193
Chris Lattnerc8b70922002-07-26 21:12:46 +0000194 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000195}
196
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000197// getComplexity: Assign a complexity or rank value to LLVM Values...
198// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
199static unsigned getComplexity(Value *V) {
200 if (isa<Instruction>(V)) {
201 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
202 return 2;
203 return 3;
204 }
205 if (isa<Argument>(V)) return 2;
206 return isa<Constant>(V) ? 0 : 1;
207}
Chris Lattner260ab202002-04-18 17:39:14 +0000208
Chris Lattner7fb29e12003-03-11 00:12:48 +0000209// isOnlyUse - Return true if this instruction will be deleted if we stop using
210// it.
211static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000212 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000213}
214
Chris Lattnere79e8542004-02-23 06:38:22 +0000215// getPromotedType - Return the specified type promoted as it would be to pass
216// though a va_arg area...
217static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000218 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000219 case Type::SByteTyID:
220 case Type::ShortTyID: return Type::IntTy;
221 case Type::UByteTyID:
222 case Type::UShortTyID: return Type::UIntTy;
223 case Type::FloatTyID: return Type::DoubleTy;
224 default: return Ty;
225 }
226}
227
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000228// SimplifyCommutative - This performs a few simplifications for commutative
229// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000230//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000231// 1. Order operands such that they are listed from right (least complex) to
232// left (most complex). This puts constants before unary operators before
233// binary operators.
234//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000235// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
236// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000237//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000238bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000239 bool Changed = false;
240 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
241 Changed = !I.swapOperands();
242
243 if (!I.isAssociative()) return Changed;
244 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000245 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
246 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
247 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000248 Constant *Folded = ConstantExpr::get(I.getOpcode(),
249 cast<Constant>(I.getOperand(1)),
250 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000251 I.setOperand(0, Op->getOperand(0));
252 I.setOperand(1, Folded);
253 return true;
254 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
255 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
256 isOnlyUse(Op) && isOnlyUse(Op1)) {
257 Constant *C1 = cast<Constant>(Op->getOperand(1));
258 Constant *C2 = cast<Constant>(Op1->getOperand(1));
259
260 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000261 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000262 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
263 Op1->getOperand(0),
264 Op1->getName(), &I);
265 WorkList.push_back(New);
266 I.setOperand(0, New);
267 I.setOperand(1, Folded);
268 return true;
269 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000271 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000272}
Chris Lattnerca081252001-12-14 16:52:21 +0000273
Chris Lattnerbb74e222003-03-10 23:06:50 +0000274// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
275// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000276//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000277static inline Value *dyn_castNegVal(Value *V) {
278 if (BinaryOperator::isNeg(V))
279 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
280
Chris Lattner9244df62003-04-30 22:19:10 +0000281 // Constants can be considered to be negated values if they can be folded...
282 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000283 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000284 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000285}
286
Chris Lattnerbb74e222003-03-10 23:06:50 +0000287static inline Value *dyn_castNotVal(Value *V) {
288 if (BinaryOperator::isNot(V))
289 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
290
291 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000292 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000293 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000294 return 0;
295}
296
Chris Lattner7fb29e12003-03-11 00:12:48 +0000297// dyn_castFoldableMul - If this value is a multiply that can be folded into
298// other computations (because it has a constant operand), return the
299// non-constant operand of the multiply.
300//
301static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000302 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000303 if (Instruction *I = dyn_cast<Instruction>(V))
304 if (I->getOpcode() == Instruction::Mul)
305 if (isa<Constant>(I->getOperand(1)))
306 return I->getOperand(0);
307 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000308}
Chris Lattner31ae8632002-08-14 17:51:49 +0000309
Chris Lattner7fb29e12003-03-11 00:12:48 +0000310// dyn_castMaskingAnd - If this value is an And instruction masking a value with
311// a constant, return the constant being anded with.
312//
Chris Lattner01d56392003-08-12 19:17:27 +0000313template<class ValueType>
314static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000315 if (Instruction *I = dyn_cast<Instruction>(V))
316 if (I->getOpcode() == Instruction::And)
317 return dyn_cast<Constant>(I->getOperand(1));
318
319 // If this is a constant, it acts just like we were masking with it.
320 return dyn_cast<Constant>(V);
321}
Chris Lattner3082c5a2003-02-18 19:28:33 +0000322
323// Log2 - Calculate the log base 2 for the specified value if it is exactly a
324// power of 2.
325static unsigned Log2(uint64_t Val) {
326 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
327 unsigned Count = 0;
328 while (Val != 1) {
329 if (Val & 1) return 0; // Multiple bits set?
330 Val >>= 1;
331 ++Count;
332 }
333 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000334}
335
Chris Lattnerb8b97502003-08-13 19:01:45 +0000336
337/// AssociativeOpt - Perform an optimization on an associative operator. This
338/// function is designed to check a chain of associative operators for a
339/// potential to apply a certain optimization. Since the optimization may be
340/// applicable if the expression was reassociated, this checks the chain, then
341/// reassociates the expression as necessary to expose the optimization
342/// opportunity. This makes use of a special Functor, which must define
343/// 'shouldApply' and 'apply' methods.
344///
345template<typename Functor>
346Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
347 unsigned Opcode = Root.getOpcode();
348 Value *LHS = Root.getOperand(0);
349
350 // Quick check, see if the immediate LHS matches...
351 if (F.shouldApply(LHS))
352 return F.apply(Root);
353
354 // Otherwise, if the LHS is not of the same opcode as the root, return.
355 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000356 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000357 // Should we apply this transform to the RHS?
358 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
359
360 // If not to the RHS, check to see if we should apply to the LHS...
361 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
362 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
363 ShouldApply = true;
364 }
365
366 // If the functor wants to apply the optimization to the RHS of LHSI,
367 // reassociate the expression from ((? op A) op B) to (? op (A op B))
368 if (ShouldApply) {
369 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000370
371 // Now all of the instructions are in the current basic block, go ahead
372 // and perform the reassociation.
373 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
374
375 // First move the selected RHS to the LHS of the root...
376 Root.setOperand(0, LHSI->getOperand(1));
377
378 // Make what used to be the LHS of the root be the user of the root...
379 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000380 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000381 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
382 return 0;
383 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000384 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000385 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000386 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
387 BasicBlock::iterator ARI = &Root; ++ARI;
388 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
389 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000390
391 // Now propagate the ExtraOperand down the chain of instructions until we
392 // get to LHSI.
393 while (TmpLHSI != LHSI) {
394 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000395 // Move the instruction to immediately before the chain we are
396 // constructing to avoid breaking dominance properties.
397 NextLHSI->getParent()->getInstList().remove(NextLHSI);
398 BB->getInstList().insert(ARI, NextLHSI);
399 ARI = NextLHSI;
400
Chris Lattnerb8b97502003-08-13 19:01:45 +0000401 Value *NextOp = NextLHSI->getOperand(1);
402 NextLHSI->setOperand(1, ExtraOperand);
403 TmpLHSI = NextLHSI;
404 ExtraOperand = NextOp;
405 }
406
407 // Now that the instructions are reassociated, have the functor perform
408 // the transformation...
409 return F.apply(Root);
410 }
411
412 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
413 }
414 return 0;
415}
416
417
418// AddRHS - Implements: X + X --> X << 1
419struct AddRHS {
420 Value *RHS;
421 AddRHS(Value *rhs) : RHS(rhs) {}
422 bool shouldApply(Value *LHS) const { return LHS == RHS; }
423 Instruction *apply(BinaryOperator &Add) const {
424 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
425 ConstantInt::get(Type::UByteTy, 1));
426 }
427};
428
429// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
430// iff C1&C2 == 0
431struct AddMaskingAnd {
432 Constant *C2;
433 AddMaskingAnd(Constant *c) : C2(c) {}
434 bool shouldApply(Value *LHS) const {
435 if (Constant *C1 = dyn_castMaskingAnd(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000436 return ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000437 return false;
438 }
439 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000440 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000441 }
442};
443
Chris Lattner183b3362004-04-09 19:05:30 +0000444static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
445 InstCombiner *IC) {
446 // Figure out if the constant is the left or the right argument.
447 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
448 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000449
Chris Lattner183b3362004-04-09 19:05:30 +0000450 if (Constant *SOC = dyn_cast<Constant>(SO)) {
451 if (ConstIsRHS)
452 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
453 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
454 }
455
456 Value *Op0 = SO, *Op1 = ConstOperand;
457 if (!ConstIsRHS)
458 std::swap(Op0, Op1);
459 Instruction *New;
460 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
461 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
462 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
463 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000464 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000465 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000466 abort();
467 }
Chris Lattner183b3362004-04-09 19:05:30 +0000468 return IC->InsertNewInstBefore(New, BI);
469}
470
471// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
472// constant as the other operand, try to fold the binary operator into the
473// select arguments.
474static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
475 InstCombiner *IC) {
476 // Don't modify shared select instructions
477 if (!SI->hasOneUse()) return 0;
478 Value *TV = SI->getOperand(1);
479 Value *FV = SI->getOperand(2);
480
481 if (isa<Constant>(TV) || isa<Constant>(FV)) {
482 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
483 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
484
485 return new SelectInst(SI->getCondition(), SelectTrueVal,
486 SelectFalseVal);
487 }
488 return 0;
489}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000490
Chris Lattner113f4f42002-06-25 16:13:24 +0000491Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000492 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000493 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000494
Chris Lattnercf4a9962004-04-10 22:01:55 +0000495 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
496 // X + 0 --> X
497 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
498 RHSC->isNullValue())
499 return ReplaceInstUsesWith(I, LHS);
500
501 // X + (signbit) --> X ^ signbit
502 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
503 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
504 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
505 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000506 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000507 }
508 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000509
Chris Lattnerb8b97502003-08-13 19:01:45 +0000510 // X + X --> X << 1
511 if (I.getType()->isInteger())
512 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattnerede3fe02003-08-13 04:18:28 +0000513
Chris Lattner147e9752002-05-08 22:46:53 +0000514 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000515 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000516 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000517
518 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000519 if (!isa<Constant>(RHS))
520 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000521 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000522
Chris Lattner57c8d992003-02-18 19:57:07 +0000523 // X*C + X --> X * (C+1)
524 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000525 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000526 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000527 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
528 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000529 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000530 }
531
532 // X + X*C --> X * (C+1)
533 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000534 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000535 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000536 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
537 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000538 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000539 }
540
Chris Lattnerb8b97502003-08-13 19:01:45 +0000541 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
542 if (Constant *C2 = dyn_castMaskingAnd(RHS))
543 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000544
Chris Lattnerb9cde762003-10-02 15:11:26 +0000545 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
546 if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
547 switch (ILHS->getOpcode()) {
548 case Instruction::Xor:
549 // ~X + C --> (C-1) - X
550 if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
551 if (XorRHS->isAllOnesValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000552 return BinaryOperator::createSub(ConstantExpr::getSub(CRHS,
553 ConstantInt::get(I.getType(), 1)),
Chris Lattnerb9cde762003-10-02 15:11:26 +0000554 ILHS->getOperand(0));
555 break;
Chris Lattner183b3362004-04-09 19:05:30 +0000556 case Instruction::Select:
557 // Try to fold constant add into select arguments.
558 if (Instruction *R = FoldBinOpIntoSelect(I,cast<SelectInst>(ILHS),this))
559 return R;
560
Chris Lattnerb9cde762003-10-02 15:11:26 +0000561 default: break;
562 }
563 }
564 }
565
Chris Lattner113f4f42002-06-25 16:13:24 +0000566 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000567}
568
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000569// isSignBit - Return true if the value represented by the constant only has the
570// highest order bit set.
571static bool isSignBit(ConstantInt *CI) {
572 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
573 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
574}
575
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000576static unsigned getTypeSizeInBits(const Type *Ty) {
577 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
578}
579
Chris Lattner022167f2004-03-13 00:11:49 +0000580/// RemoveNoopCast - Strip off nonconverting casts from the value.
581///
582static Value *RemoveNoopCast(Value *V) {
583 if (CastInst *CI = dyn_cast<CastInst>(V)) {
584 const Type *CTy = CI->getType();
585 const Type *OpTy = CI->getOperand(0)->getType();
586 if (CTy->isInteger() && OpTy->isInteger()) {
587 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
588 return RemoveNoopCast(CI->getOperand(0));
589 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
590 return RemoveNoopCast(CI->getOperand(0));
591 }
592 return V;
593}
594
Chris Lattner113f4f42002-06-25 16:13:24 +0000595Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000596 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000597
Chris Lattnere6794492002-08-12 21:17:25 +0000598 if (Op0 == Op1) // sub X, X -> 0
599 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000600
Chris Lattnere6794492002-08-12 21:17:25 +0000601 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000602 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000603 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000604
Chris Lattner8f2f5982003-11-05 01:06:05 +0000605 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
606 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000607 if (C->isAllOnesValue())
608 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000609
Chris Lattner8f2f5982003-11-05 01:06:05 +0000610 // C - ~X == X + (1+C)
611 if (BinaryOperator::isNot(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000612 return BinaryOperator::createAdd(
613 BinaryOperator::getNotArgument(cast<BinaryOperator>(Op1)),
614 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000615 // -((uint)X >> 31) -> ((int)X >> 31)
616 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000617 if (C->isNullValue()) {
618 Value *NoopCastedRHS = RemoveNoopCast(Op1);
619 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000620 if (SI->getOpcode() == Instruction::Shr)
621 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
622 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000623 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000624 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000625 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000626 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000627 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000628 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000629 // Ok, the transformation is safe. Insert a cast of the incoming
630 // value, then the new shift, then the new cast.
631 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
632 SI->getOperand(0)->getName());
633 Value *InV = InsertNewInstBefore(FirstCast, I);
634 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
635 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000636 if (NewShift->getType() == I.getType())
637 return NewShift;
638 else {
639 InV = InsertNewInstBefore(NewShift, I);
640 return new CastInst(NewShift, I.getType());
641 }
Chris Lattner92295c52004-03-12 23:53:13 +0000642 }
643 }
Chris Lattner022167f2004-03-13 00:11:49 +0000644 }
Chris Lattner183b3362004-04-09 19:05:30 +0000645
646 // Try to fold constant sub into select arguments.
647 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
648 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
649 return R;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000650 }
651
Chris Lattner3082c5a2003-02-18 19:28:33 +0000652 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000653 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000654 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
655 // is not used by anyone else...
656 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000657 if (Op1I->getOpcode() == Instruction::Sub &&
658 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000659 // Swap the two operands of the subexpr...
660 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
661 Op1I->setOperand(0, IIOp1);
662 Op1I->setOperand(1, IIOp0);
663
664 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000665 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000666 }
667
668 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
669 //
670 if (Op1I->getOpcode() == Instruction::And &&
671 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
672 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
673
Chris Lattner396dbfe2004-06-09 05:08:07 +0000674 Value *NewNot =
675 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000676 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000677 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000678
679 // X - X*C --> X * (1-C)
680 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000681 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000682 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000683 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000684 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000685 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000686 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000687 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000688
Chris Lattner57c8d992003-02-18 19:57:07 +0000689 // X*C - X --> X * (C-1)
690 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000691 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000692 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000693 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000694 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000695 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000696 }
697
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000698 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000699}
700
Chris Lattnere79e8542004-02-23 06:38:22 +0000701/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
702/// really just returns true if the most significant (sign) bit is set.
703static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
704 if (RHS->getType()->isSigned()) {
705 // True if source is LHS < 0 or LHS <= -1
706 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
707 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
708 } else {
709 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
710 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
711 // the size of the integer type.
712 if (Opcode == Instruction::SetGE)
713 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
714 if (Opcode == Instruction::SetGT)
715 return RHSC->getValue() ==
716 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
717 }
718 return false;
719}
720
Chris Lattner113f4f42002-06-25 16:13:24 +0000721Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000722 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000723 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000724
Chris Lattnere6794492002-08-12 21:17:25 +0000725 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000726 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
727 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000728
729 // ((X << C1)*C2) == (X * (C2 << C1))
730 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
731 if (SI->getOpcode() == Instruction::Shl)
732 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000733 return BinaryOperator::createMul(SI->getOperand(0),
734 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000735
Chris Lattnercce81be2003-09-11 22:24:54 +0000736 if (CI->isNullValue())
737 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
738 if (CI->equalsInt(1)) // X * 1 == X
739 return ReplaceInstUsesWith(I, Op0);
740 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000741 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000742
Chris Lattnercce81be2003-09-11 22:24:54 +0000743 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000744 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
745 return new ShiftInst(Instruction::Shl, Op0,
746 ConstantUInt::get(Type::UByteTy, C));
747 } else {
748 ConstantFP *Op1F = cast<ConstantFP>(Op1);
749 if (Op1F->isNullValue())
750 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000751
Chris Lattner3082c5a2003-02-18 19:28:33 +0000752 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
753 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
754 if (Op1F->getValue() == 1.0)
755 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
756 }
Chris Lattner183b3362004-04-09 19:05:30 +0000757
758 // Try to fold constant mul into select arguments.
759 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
760 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
761 return R;
Chris Lattner260ab202002-04-18 17:39:14 +0000762 }
763
Chris Lattner934a64cf2003-03-10 23:23:04 +0000764 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
765 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000766 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000767
Chris Lattner2635b522004-02-23 05:39:21 +0000768 // If one of the operands of the multiply is a cast from a boolean value, then
769 // we know the bool is either zero or one, so this is a 'masking' multiply.
770 // See if we can simplify things based on how the boolean was originally
771 // formed.
772 CastInst *BoolCast = 0;
773 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
774 if (CI->getOperand(0)->getType() == Type::BoolTy)
775 BoolCast = CI;
776 if (!BoolCast)
777 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
778 if (CI->getOperand(0)->getType() == Type::BoolTy)
779 BoolCast = CI;
780 if (BoolCast) {
781 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
782 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
783 const Type *SCOpTy = SCIOp0->getType();
784
Chris Lattnere79e8542004-02-23 06:38:22 +0000785 // If the setcc is true iff the sign bit of X is set, then convert this
786 // multiply into a shift/and combination.
787 if (isa<ConstantInt>(SCIOp1) &&
788 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000789 // Shift the X value right to turn it into "all signbits".
790 Constant *Amt = ConstantUInt::get(Type::UByteTy,
791 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000792 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000793 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000794 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
795 SCIOp0->getName()), I);
796 }
797
798 Value *V =
799 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
800 BoolCast->getOperand(0)->getName()+
801 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000802
803 // If the multiply type is not the same as the source type, sign extend
804 // or truncate to the multiply type.
805 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000806 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000807
808 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000809 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000810 }
811 }
812 }
813
Chris Lattner113f4f42002-06-25 16:13:24 +0000814 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000815}
816
Chris Lattner113f4f42002-06-25 16:13:24 +0000817Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000818 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000819 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000820 if (RHS->equalsInt(1))
821 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000822
Chris Lattnere20c3342004-04-26 14:01:59 +0000823 // div X, -1 == -X
824 if (RHS->isAllOnesValue())
825 return BinaryOperator::createNeg(I.getOperand(0));
826
Chris Lattner3082c5a2003-02-18 19:28:33 +0000827 // Check to see if this is an unsigned division with an exact power of 2,
828 // if so, convert to a right shift.
829 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
830 if (uint64_t Val = C->getValue()) // Don't break X / 0
831 if (uint64_t C = Log2(Val))
832 return new ShiftInst(Instruction::Shr, I.getOperand(0),
833 ConstantUInt::get(Type::UByteTy, C));
834 }
835
836 // 0 / X == 0, we don't need to preserve faults!
837 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
838 if (LHS->equalsInt(0))
839 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
840
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000841 return 0;
842}
843
844
Chris Lattner113f4f42002-06-25 16:13:24 +0000845Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000846 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
847 if (RHS->equalsInt(1)) // X % 1 == 0
848 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner56b50512004-03-26 16:11:24 +0000849 if (RHS->isAllOnesValue()) // X % -1 == 0
850 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000851
852 // Check to see if this is an unsigned remainder with an exact power of 2,
853 // if so, convert to a bitwise and.
854 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
855 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000856 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000857 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000858 ConstantUInt::get(I.getType(), Val-1));
859 }
860
861 // 0 % X == 0, we don't need to preserve faults!
862 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
863 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000864 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
865
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000866 return 0;
867}
868
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000869// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000870static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000871 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
872 // Calculate -1 casted to the right type...
873 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
874 uint64_t Val = ~0ULL; // All ones
875 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
876 return CU->getValue() == Val-1;
877 }
878
879 const ConstantSInt *CS = cast<ConstantSInt>(C);
880
881 // Calculate 0111111111..11111
882 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
883 int64_t Val = INT64_MAX; // All ones
884 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
885 return CS->getValue() == Val-1;
886}
887
888// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000889static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000890 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
891 return CU->getValue() == 1;
892
893 const ConstantSInt *CS = cast<ConstantSInt>(C);
894
895 // Calculate 1111111111000000000000
896 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
897 int64_t Val = -1; // All ones
898 Val <<= TypeBits-1; // Shift over to the right spot
899 return CS->getValue() == Val+1;
900}
901
Chris Lattner35167c32004-06-09 07:59:58 +0000902// isOneBitSet - Return true if there is exactly one bit set in the specified
903// constant.
904static bool isOneBitSet(const ConstantInt *CI) {
905 uint64_t V = CI->getRawValue();
906 return V && (V & (V-1)) == 0;
907}
908
Chris Lattner3ac7c262003-08-13 20:16:26 +0000909/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
910/// are carefully arranged to allow folding of expressions such as:
911///
912/// (A < B) | (A > B) --> (A != B)
913///
914/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
915/// represents that the comparison is true if A == B, and bit value '1' is true
916/// if A < B.
917///
918static unsigned getSetCondCode(const SetCondInst *SCI) {
919 switch (SCI->getOpcode()) {
920 // False -> 0
921 case Instruction::SetGT: return 1;
922 case Instruction::SetEQ: return 2;
923 case Instruction::SetGE: return 3;
924 case Instruction::SetLT: return 4;
925 case Instruction::SetNE: return 5;
926 case Instruction::SetLE: return 6;
927 // True -> 7
928 default:
929 assert(0 && "Invalid SetCC opcode!");
930 return 0;
931 }
932}
933
934/// getSetCCValue - This is the complement of getSetCondCode, which turns an
935/// opcode and two operands into either a constant true or false, or a brand new
936/// SetCC instruction.
937static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
938 switch (Opcode) {
939 case 0: return ConstantBool::False;
940 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
941 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
942 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
943 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
944 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
945 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
946 case 7: return ConstantBool::True;
947 default: assert(0 && "Illegal SetCCCode!"); return 0;
948 }
949}
950
951// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
952struct FoldSetCCLogical {
953 InstCombiner &IC;
954 Value *LHS, *RHS;
955 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
956 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
957 bool shouldApply(Value *V) const {
958 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
959 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
960 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
961 return false;
962 }
963 Instruction *apply(BinaryOperator &Log) const {
964 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
965 if (SCI->getOperand(0) != LHS) {
966 assert(SCI->getOperand(1) == LHS);
967 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
968 }
969
970 unsigned LHSCode = getSetCondCode(SCI);
971 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
972 unsigned Code;
973 switch (Log.getOpcode()) {
974 case Instruction::And: Code = LHSCode & RHSCode; break;
975 case Instruction::Or: Code = LHSCode | RHSCode; break;
976 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +0000977 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +0000978 }
979
980 Value *RV = getSetCCValue(Code, LHS, RHS);
981 if (Instruction *I = dyn_cast<Instruction>(RV))
982 return I;
983 // Otherwise, it's a constant boolean value...
984 return IC.ReplaceInstUsesWith(Log, RV);
985 }
986};
987
988
Chris Lattnerba1cb382003-09-19 17:17:26 +0000989// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
990// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
991// guaranteed to be either a shift instruction or a binary operator.
992Instruction *InstCombiner::OptAndOp(Instruction *Op,
993 ConstantIntegral *OpRHS,
994 ConstantIntegral *AndRHS,
995 BinaryOperator &TheAnd) {
996 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +0000997 Constant *Together = 0;
998 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000999 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001000
Chris Lattnerba1cb382003-09-19 17:17:26 +00001001 switch (Op->getOpcode()) {
1002 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001003 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001004 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001005 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001006 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001007 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1008 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001009 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001010 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001011 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001012 }
1013 break;
1014 case Instruction::Or:
1015 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001016 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001017 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001018 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001019 if (Together == AndRHS) // (X | C) & C --> C
1020 return ReplaceInstUsesWith(TheAnd, AndRHS);
1021
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001022 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001023 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1024 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001025 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001026 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001027 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001028 }
1029 }
1030 break;
1031 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001032 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001033 // Adding a one to a single bit bit-field should be turned into an XOR
1034 // of the bit. First thing to check is to see if this AND is with a
1035 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001036 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001037
1038 // Clear bits that are not part of the constant.
1039 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1040
1041 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001042 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001043 // Ok, at this point, we know that we are masking the result of the
1044 // ADD down to exactly one bit. If the constant we are adding has
1045 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001046 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001047
1048 // Check to see if any bits below the one bit set in AndRHSV are set.
1049 if ((AddRHS & (AndRHSV-1)) == 0) {
1050 // If not, the only thing that can effect the output of the AND is
1051 // the bit specified by AndRHSV. If that bit is set, the effect of
1052 // the XOR is to toggle the bit. If it is clear, then the ADD has
1053 // no effect.
1054 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1055 TheAnd.setOperand(0, X);
1056 return &TheAnd;
1057 } else {
1058 std::string Name = Op->getName(); Op->setName("");
1059 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001060 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001061 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001062 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001063 }
1064 }
1065 }
1066 }
1067 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001068
1069 case Instruction::Shl: {
1070 // We know that the AND will not produce any of the bits shifted in, so if
1071 // the anded constant includes them, clear them now!
1072 //
1073 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001074 Constant *CI = ConstantExpr::getAnd(AndRHS,
1075 ConstantExpr::getShl(AllOne, OpRHS));
Chris Lattner2da29172003-09-19 19:05:02 +00001076 if (CI != AndRHS) {
1077 TheAnd.setOperand(1, CI);
1078 return &TheAnd;
1079 }
1080 break;
1081 }
1082 case Instruction::Shr:
1083 // We know that the AND will not produce any of the bits shifted in, so if
1084 // the anded constant includes them, clear them now! This only applies to
1085 // unsigned shifts, because a signed shr may bring in set bits!
1086 //
1087 if (AndRHS->getType()->isUnsigned()) {
1088 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001089 Constant *CI = ConstantExpr::getAnd(AndRHS,
1090 ConstantExpr::getShr(AllOne, OpRHS));
Chris Lattner2da29172003-09-19 19:05:02 +00001091 if (CI != AndRHS) {
1092 TheAnd.setOperand(1, CI);
1093 return &TheAnd;
1094 }
1095 }
1096 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001097 }
1098 return 0;
1099}
1100
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001101
Chris Lattner113f4f42002-06-25 16:13:24 +00001102Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001103 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001104 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001105
1106 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001107 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1108 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001109
1110 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001111 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001112 if (RHS->isAllOnesValue())
1113 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001114
Chris Lattnerba1cb382003-09-19 17:17:26 +00001115 // Optimize a variety of ((val OP C1) & C2) combinations...
1116 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1117 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001118 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001119 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001120 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1121 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001122 }
Chris Lattner183b3362004-04-09 19:05:30 +00001123
1124 // Try to fold constant and into select arguments.
1125 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1126 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1127 return R;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001128 }
1129
Chris Lattnerbb74e222003-03-10 23:06:50 +00001130 Value *Op0NotVal = dyn_castNotVal(Op0);
1131 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001132
Chris Lattner023a4832004-06-18 06:07:51 +00001133 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1134 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1135
Chris Lattner3082c5a2003-02-18 19:28:33 +00001136 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001137 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001138 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1139 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001140 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001141 return BinaryOperator::createNot(Or);
1142 }
1143
Chris Lattner3ac7c262003-08-13 20:16:26 +00001144 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1145 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1146 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1147 return R;
1148
Chris Lattner113f4f42002-06-25 16:13:24 +00001149 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001150}
1151
1152
1153
Chris Lattner113f4f42002-06-25 16:13:24 +00001154Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001155 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001157
1158 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001159 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1160 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001161
1162 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001163 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001164 if (RHS->isAllOnesValue())
1165 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001166
Chris Lattner8f0d1562003-07-23 18:29:44 +00001167 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1168 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1169 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
1170 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1171 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001172 Instruction *Or = BinaryOperator::createOr(Op0I->getOperand(0), RHS,
1173 Op0Name);
Chris Lattner8f0d1562003-07-23 18:29:44 +00001174 InsertNewInstBefore(Or, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001175 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, Op0CI));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001176 }
1177
1178 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1179 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
1180 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1181 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001182 Instruction *Or = BinaryOperator::createOr(Op0I->getOperand(0), RHS,
1183 Op0Name);
Chris Lattner8f0d1562003-07-23 18:29:44 +00001184 InsertNewInstBefore(Or, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001185 return BinaryOperator::createXor(Or,
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001186 ConstantExpr::getAnd(Op0CI,
1187 ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001188 }
1189 }
Chris Lattner183b3362004-04-09 19:05:30 +00001190
1191 // Try to fold constant and into select arguments.
1192 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1193 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1194 return R;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001195 }
1196
Chris Lattner812aab72003-08-12 19:11:07 +00001197 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattner01d56392003-08-12 19:17:27 +00001198 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
1199 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
1200 if (LHS->getOperand(0) == RHS->getOperand(0))
1201 if (Constant *C0 = dyn_castMaskingAnd(LHS))
1202 if (Constant *C1 = dyn_castMaskingAnd(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001203 return BinaryOperator::createAnd(LHS->getOperand(0),
1204 ConstantExpr::getOr(C0, C1));
Chris Lattner812aab72003-08-12 19:11:07 +00001205
Chris Lattner3e327a42003-03-10 23:13:59 +00001206 Value *Op0NotVal = dyn_castNotVal(Op0);
1207 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001208
Chris Lattner3e327a42003-03-10 23:13:59 +00001209 if (Op1 == Op0NotVal) // ~A | A == -1
1210 return ReplaceInstUsesWith(I,
1211 ConstantIntegral::getAllOnesValue(I.getType()));
1212
1213 if (Op0 == Op1NotVal) // A | ~A == -1
1214 return ReplaceInstUsesWith(I,
1215 ConstantIntegral::getAllOnesValue(I.getType()));
1216
1217 // (~A | ~B) == (~(A & B)) - Demorgan's Law
1218 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner396dbfe2004-06-09 05:08:07 +00001219 Value *And = InsertNewInstBefore(
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001220 BinaryOperator::createAnd(Op0NotVal,
1221 Op1NotVal,I.getName()+".demorgan"),I);
Chris Lattner3e327a42003-03-10 23:13:59 +00001222 return BinaryOperator::createNot(And);
1223 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001224
Chris Lattner3ac7c262003-08-13 20:16:26 +00001225 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1226 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1227 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1228 return R;
1229
Chris Lattner113f4f42002-06-25 16:13:24 +00001230 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001231}
1232
Chris Lattnerc2076352004-02-16 01:20:27 +00001233// XorSelf - Implements: X ^ X --> 0
1234struct XorSelf {
1235 Value *RHS;
1236 XorSelf(Value *rhs) : RHS(rhs) {}
1237 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1238 Instruction *apply(BinaryOperator &Xor) const {
1239 return &Xor;
1240 }
1241};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001242
1243
Chris Lattner113f4f42002-06-25 16:13:24 +00001244Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001245 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001246 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001247
Chris Lattnerc2076352004-02-16 01:20:27 +00001248 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1249 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1250 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001251 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001252 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001253
Chris Lattner97638592003-07-23 21:37:07 +00001254 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001255 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001256 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001257 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001258
Chris Lattner97638592003-07-23 21:37:07 +00001259 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001260 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001261 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001262 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001263 return new SetCondInst(SCI->getInverseCondition(),
1264 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001265
Chris Lattner8f2f5982003-11-05 01:06:05 +00001266 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001267 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1268 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001269 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1270 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001271 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001272 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001273 }
Chris Lattner023a4832004-06-18 06:07:51 +00001274
1275 // ~(~X & Y) --> (X | ~Y)
1276 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1277 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1278 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1279 Instruction *NotY =
1280 BinaryOperator::createNot(Op0I->getOperand(1),
1281 Op0I->getOperand(1)->getName()+".not");
1282 InsertNewInstBefore(NotY, I);
1283 return BinaryOperator::createOr(Op0NotVal, NotY);
1284 }
1285 }
Chris Lattner97638592003-07-23 21:37:07 +00001286
1287 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001288 switch (Op0I->getOpcode()) {
1289 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001290 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001291 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001292 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1293 return BinaryOperator::createSub(
1294 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001295 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001296 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001297 }
Chris Lattnere5806662003-11-04 23:50:51 +00001298 break;
1299 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001300 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001301 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1302 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001303 break;
1304 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001305 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001306 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001307 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001308 break;
1309 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001310 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001311 }
Chris Lattner183b3362004-04-09 19:05:30 +00001312
1313 // Try to fold constant and into select arguments.
1314 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1315 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1316 return R;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001317 }
1318
Chris Lattnerbb74e222003-03-10 23:06:50 +00001319 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001320 if (X == Op1)
1321 return ReplaceInstUsesWith(I,
1322 ConstantIntegral::getAllOnesValue(I.getType()));
1323
Chris Lattnerbb74e222003-03-10 23:06:50 +00001324 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001325 if (X == Op0)
1326 return ReplaceInstUsesWith(I,
1327 ConstantIntegral::getAllOnesValue(I.getType()));
1328
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001329 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001330 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001331 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1332 cast<BinaryOperator>(Op1I)->swapOperands();
1333 I.swapOperands();
1334 std::swap(Op0, Op1);
1335 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1336 I.swapOperands();
1337 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001338 }
1339 } else if (Op1I->getOpcode() == Instruction::Xor) {
1340 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1341 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1342 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1343 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1344 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001345
1346 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001347 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001348 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1349 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001350 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001351 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1352 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001353 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001354 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001355 } else if (Op0I->getOpcode() == Instruction::Xor) {
1356 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1357 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1358 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1359 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001360 }
1361
Chris Lattner7fb29e12003-03-11 00:12:48 +00001362 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1363 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1364 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001365 if (ConstantExpr::getAnd(C1, C2)->isNullValue())
1366 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001367
Chris Lattner3ac7c262003-08-13 20:16:26 +00001368 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1369 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1370 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1371 return R;
1372
Chris Lattner113f4f42002-06-25 16:13:24 +00001373 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001374}
1375
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001376// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1377static Constant *AddOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001378 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001379}
1380static Constant *SubOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001381 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001382}
1383
Chris Lattner1fc23f32002-05-09 20:11:54 +00001384// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1385// true when both operands are equal...
1386//
Chris Lattner113f4f42002-06-25 16:13:24 +00001387static bool isTrueWhenEqual(Instruction &I) {
1388 return I.getOpcode() == Instruction::SetEQ ||
1389 I.getOpcode() == Instruction::SetGE ||
1390 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +00001391}
1392
Chris Lattner113f4f42002-06-25 16:13:24 +00001393Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001394 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001395 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1396 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001397
1398 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001399 if (Op0 == Op1)
1400 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001401
Chris Lattnerd07283a2003-08-13 05:38:46 +00001402 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1403 if (isa<ConstantPointerNull>(Op1) &&
1404 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001405 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1406
Chris Lattnerd07283a2003-08-13 05:38:46 +00001407
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001408 // setcc's with boolean values can always be turned into bitwise operations
1409 if (Ty == Type::BoolTy) {
1410 // If this is <, >, or !=, we can change this into a simple xor instruction
1411 if (!isTrueWhenEqual(I))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001412 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001413
1414 // Otherwise we need to make a temporary intermediate instruction and insert
1415 // it into the instruction stream. This is what we are after:
1416 //
1417 // seteq bool %A, %B -> ~(A^B)
1418 // setle bool %A, %B -> ~A | B
1419 // setge bool %A, %B -> A | ~B
1420 //
1421 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001422 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001423 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001424 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001425 }
1426
1427 // Handle the setXe cases...
1428 assert(I.getOpcode() == Instruction::SetGE ||
1429 I.getOpcode() == Instruction::SetLE);
1430
1431 if (I.getOpcode() == Instruction::SetGE)
1432 std::swap(Op0, Op1); // Change setge -> setle
1433
1434 // Now we just have the SetLE case.
Chris Lattner31ae8632002-08-14 17:51:49 +00001435 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001436 InsertNewInstBefore(Not, I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001437 return BinaryOperator::createOr(Not, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001438 }
1439
Chris Lattner2dd01742004-06-09 04:24:29 +00001440 // See if we are doing a comparison between a constant and an instruction that
1441 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001442 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere1e10e12004-05-25 06:32:08 +00001443 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner2dd01742004-06-09 04:24:29 +00001444 if (LHSI->hasOneUse())
Chris Lattner35167c32004-06-09 07:59:58 +00001445 switch (LHSI->getOpcode()) {
1446 case Instruction::And:
1447 if (isa<ConstantInt>(LHSI->getOperand(1))) {
1448
Chris Lattnere1e10e12004-05-25 06:32:08 +00001449
Chris Lattner35167c32004-06-09 07:59:58 +00001450 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1451 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1452 // happens a LOT in code produced by the C front-end, for bitfield
1453 // access.
1454 if (LHSI->getOperand(0)->hasOneUse())
1455 if (ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0)))
1456 if (ConstantUInt *ShAmt =
1457 dyn_cast<ConstantUInt>(Shift->getOperand(1))) {
1458 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1459
1460 // We can fold this as long as we can't shift unknown bits
1461 // into the mask. This can only happen with signed shift
1462 // rights, as they sign-extend.
1463 const Type *Ty = Shift->getType();
1464 if (Shift->getOpcode() != Instruction::Shr ||
1465 Shift->getType()->isUnsigned() ||
1466 // To test for the bad case of the signed shr, see if any
1467 // of the bits shifted in could be tested after the mask.
1468 ConstantExpr::getAnd(ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), ConstantUInt::get(Type::UByteTy, Ty->getPrimitiveSize()*8-ShAmt->getValue())), AndCST)->isNullValue()) {
1469 unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
1470 ? Instruction::Shr : Instruction::Shl;
1471 I.setOperand(1, ConstantExpr::get(ShiftOp, CI, ShAmt));
1472 LHSI->setOperand(1,ConstantExpr::get(ShiftOp,AndCST,ShAmt));
1473 LHSI->setOperand(0, Shift->getOperand(0));
1474 WorkList.push_back(Shift); // Shift is probably dead.
1475 AddUsesToWorkList(I);
1476 return &I;
1477 }
Chris Lattner2dd01742004-06-09 04:24:29 +00001478 }
Chris Lattner35167c32004-06-09 07:59:58 +00001479 }
1480 break;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001481 case Instruction::Div:
1482 if (0 && isa<ConstantInt>(LHSI->getOperand(1))) {
1483 std::cerr << "COULD FOLD: " << *LHSI;
1484 std::cerr << "COULD FOLD: " << I << "\n";
1485 }
1486 break;
Chris Lattner35167c32004-06-09 07:59:58 +00001487 case Instruction::Select:
Chris Lattner2dd01742004-06-09 04:24:29 +00001488 // If either operand of the select is a constant, we can fold the
1489 // comparison into the select arms, which will cause one to be
1490 // constant folded and the select turned into a bitwise or.
1491 Value *Op1 = 0, *Op2 = 0;
Chris Lattner35167c32004-06-09 07:59:58 +00001492 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001493 // Fold the known value into the constant operand.
1494 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1495 // Insert a new SetCC of the other select operand.
1496 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001497 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001498 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00001499 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001500 // Fold the known value into the constant operand.
1501 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1502 // Insert a new SetCC of the other select operand.
1503 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001504 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001505 I.getName()), I);
1506 }
1507
1508 if (Op1)
Chris Lattner35167c32004-06-09 07:59:58 +00001509 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1510 break;
Chris Lattner2dd01742004-06-09 04:24:29 +00001511 }
Chris Lattnere1e10e12004-05-25 06:32:08 +00001512
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001513 // Simplify seteq and setne instructions...
1514 if (I.getOpcode() == Instruction::SetEQ ||
1515 I.getOpcode() == Instruction::SetNE) {
1516 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1517
Chris Lattnercfbce7c2003-07-23 17:26:36 +00001518 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001519 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00001520 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1521 switch (BO->getOpcode()) {
1522 case Instruction::Add:
1523 if (CI->isNullValue()) {
1524 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1525 // efficiently invertible, or if the add has just this one use.
1526 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1527 if (Value *NegVal = dyn_castNegVal(BOp1))
1528 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1529 else if (Value *NegVal = dyn_castNegVal(BOp0))
1530 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001531 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001532 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1533 BO->setName("");
1534 InsertNewInstBefore(Neg, I);
1535 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1536 }
1537 }
1538 break;
1539 case Instruction::Xor:
1540 // For the xor case, we can xor two constants together, eliminating
1541 // the explicit xor.
1542 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1543 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001544 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00001545
1546 // FALLTHROUGH
1547 case Instruction::Sub:
1548 // Replace (([sub|xor] A, B) != 0) with (A != B)
1549 if (CI->isNullValue())
1550 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1551 BO->getOperand(1));
1552 break;
1553
1554 case Instruction::Or:
1555 // If bits are being or'd in that are not present in the constant we
1556 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001557 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001558 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001559 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001560 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001561 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001562 break;
1563
1564 case Instruction::And:
1565 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001566 // If bits are being compared against that are and'd out, then the
1567 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001568 if (!ConstantExpr::getAnd(CI,
1569 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001570 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00001571
Chris Lattner35167c32004-06-09 07:59:58 +00001572 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00001573 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00001574 return new SetCondInst(isSetNE ? Instruction::SetEQ :
1575 Instruction::SetNE, Op0,
1576 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00001577
Chris Lattnerc992add2003-08-13 05:33:12 +00001578 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1579 // to be a signed value as appropriate.
1580 if (isSignBit(BOC)) {
1581 Value *X = BO->getOperand(0);
1582 // If 'X' is not signed, insert a cast now...
1583 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001584 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerc992add2003-08-13 05:33:12 +00001585 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1586 InsertNewInstBefore(NewCI, I);
1587 X = NewCI;
1588 }
1589 return new SetCondInst(isSetNE ? Instruction::SetLT :
1590 Instruction::SetGE, X,
1591 Constant::getNullValue(X->getType()));
1592 }
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001593 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001594 default: break;
1595 }
1596 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00001597 } else { // Not a SetEQ/SetNE
1598 // If the LHS is a cast from an integral value of the same size,
1599 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1600 Value *CastOp = Cast->getOperand(0);
1601 const Type *SrcTy = CastOp->getType();
1602 unsigned SrcTySize = SrcTy->getPrimitiveSize();
1603 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1604 SrcTySize == Cast->getType()->getPrimitiveSize()) {
1605 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
1606 "Source and destination signednesses should differ!");
1607 if (Cast->getType()->isSigned()) {
1608 // If this is a signed comparison, check for comparisons in the
1609 // vicinity of zero.
1610 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1611 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001612 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001613 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1614 else if (I.getOpcode() == Instruction::SetGT &&
1615 cast<ConstantSInt>(CI)->getValue() == -1)
1616 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001617 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001618 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1619 } else {
1620 ConstantUInt *CUI = cast<ConstantUInt>(CI);
1621 if (I.getOpcode() == Instruction::SetLT &&
1622 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1623 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001624 return BinaryOperator::createSetGT(CastOp,
1625 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001626 else if (I.getOpcode() == Instruction::SetGT &&
1627 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1628 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001629 return BinaryOperator::createSetLT(CastOp,
1630 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001631 }
1632 }
1633 }
Chris Lattnere967b342003-06-04 05:10:11 +00001634 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00001635
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001636 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00001637 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001638 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1639 return ReplaceInstUsesWith(I, ConstantBool::False);
1640 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1641 return ReplaceInstUsesWith(I, ConstantBool::True);
1642 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001643 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001644 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001645 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001646
Chris Lattnere6794492002-08-12 21:17:25 +00001647 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001648 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1649 return ReplaceInstUsesWith(I, ConstantBool::False);
1650 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1651 return ReplaceInstUsesWith(I, ConstantBool::True);
1652 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001653 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001654 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001655 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001656
1657 // Comparing against a value really close to min or max?
1658 } else if (isMinValuePlusOne(CI)) {
1659 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001660 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001661 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001662 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001663
1664 } else if (isMaxValueMinusOne(CI)) {
1665 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001666 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001667 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001668 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001669 }
Chris Lattner59611142004-02-23 05:47:48 +00001670
1671 // If we still have a setle or setge instruction, turn it into the
1672 // appropriate setlt or setgt instruction. Since the border cases have
1673 // already been handled above, this requires little checking.
1674 //
1675 if (I.getOpcode() == Instruction::SetLE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001676 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner59611142004-02-23 05:47:48 +00001677 if (I.getOpcode() == Instruction::SetGE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001678 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001679 }
1680
Chris Lattner16930792003-11-03 04:25:02 +00001681 // Test to see if the operands of the setcc are casted versions of other
1682 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00001683 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1684 Value *CastOp0 = CI->getOperand(0);
1685 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00001686 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00001687 (I.getOpcode() == Instruction::SetEQ ||
1688 I.getOpcode() == Instruction::SetNE)) {
1689 // We keep moving the cast from the left operand over to the right
1690 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00001691 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00001692
1693 // If operand #1 is a cast instruction, see if we can eliminate it as
1694 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00001695 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1696 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00001697 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00001698 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00001699
1700 // If Op1 is a constant, we can fold the cast into the constant.
1701 if (Op1->getType() != Op0->getType())
1702 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1703 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1704 } else {
1705 // Otherwise, cast the RHS right before the setcc
1706 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1707 InsertNewInstBefore(cast<Instruction>(Op1), I);
1708 }
1709 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1710 }
1711
Chris Lattner6444c372003-11-03 05:17:03 +00001712 // Handle the special case of: setcc (cast bool to X), <cst>
1713 // This comes up when you have code like
1714 // int X = A < B;
1715 // if (X) ...
1716 // For generality, we handle any zero-extension of any operand comparison
1717 // with a constant.
1718 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1719 const Type *SrcTy = CastOp0->getType();
1720 const Type *DestTy = Op0->getType();
1721 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1722 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1723 // Ok, we have an expansion of operand 0 into a new type. Get the
1724 // constant value, masink off bits which are not set in the RHS. These
1725 // could be set if the destination value is signed.
1726 uint64_t ConstVal = ConstantRHS->getRawValue();
1727 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1728
1729 // If the constant we are comparing it with has high bits set, which
1730 // don't exist in the original value, the values could never be equal,
1731 // because the source would be zero extended.
1732 unsigned SrcBits =
1733 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00001734 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1735 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00001736 switch (I.getOpcode()) {
1737 default: assert(0 && "Unknown comparison type!");
1738 case Instruction::SetEQ:
1739 return ReplaceInstUsesWith(I, ConstantBool::False);
1740 case Instruction::SetNE:
1741 return ReplaceInstUsesWith(I, ConstantBool::True);
1742 case Instruction::SetLT:
1743 case Instruction::SetLE:
1744 if (DestTy->isSigned() && HasSignBit)
1745 return ReplaceInstUsesWith(I, ConstantBool::False);
1746 return ReplaceInstUsesWith(I, ConstantBool::True);
1747 case Instruction::SetGT:
1748 case Instruction::SetGE:
1749 if (DestTy->isSigned() && HasSignBit)
1750 return ReplaceInstUsesWith(I, ConstantBool::True);
1751 return ReplaceInstUsesWith(I, ConstantBool::False);
1752 }
1753 }
1754
1755 // Otherwise, we can replace the setcc with a setcc of the smaller
1756 // operand value.
1757 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1758 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1759 }
1760 }
1761 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001762 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001763}
1764
1765
1766
Chris Lattnere8d6c602003-03-10 19:16:08 +00001767Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001768 assert(I.getOperand(1)->getType() == Type::UByteTy);
1769 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001770 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001771
1772 // shl X, 0 == X and shr X, 0 == X
1773 // shl 0, X == 0 and shr 0, X == 0
1774 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001775 Op0 == Constant::getNullValue(Op0->getType()))
1776 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001777
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001778 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1779 if (!isLeftShift)
1780 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1781 if (CSI->isAllOnesValue())
1782 return ReplaceInstUsesWith(I, CSI);
1783
Chris Lattner183b3362004-04-09 19:05:30 +00001784 // Try to fold constant and into select arguments.
1785 if (isa<Constant>(Op0))
1786 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1787 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1788 return R;
1789
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001790 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001791 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1792 // of a signed value.
1793 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00001794 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001795 if (CUI->getValue() >= TypeBits) {
1796 if (!Op0->getType()->isSigned() || isLeftShift)
1797 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1798 else {
1799 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1800 return &I;
1801 }
1802 }
Chris Lattner55f3d942002-09-10 23:04:09 +00001803
Chris Lattnerede3fe02003-08-13 04:18:28 +00001804 // ((X*C1) << C2) == (X * (C1 << C2))
1805 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1806 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1807 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001808 return BinaryOperator::createMul(BO->getOperand(0),
1809 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00001810
Chris Lattner183b3362004-04-09 19:05:30 +00001811 // Try to fold constant and into select arguments.
1812 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1813 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1814 return R;
Chris Lattnerede3fe02003-08-13 04:18:28 +00001815
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001816 // If the operand is an bitwise operator with a constant RHS, and the
1817 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001818 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001819 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1820 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1821 bool isValid = true; // Valid only for And, Or, Xor
1822 bool highBitSet = false; // Transform if high bit of constant set?
1823
1824 switch (Op0BO->getOpcode()) {
1825 default: isValid = false; break; // Do not perform transform!
1826 case Instruction::Or:
1827 case Instruction::Xor:
1828 highBitSet = false;
1829 break;
1830 case Instruction::And:
1831 highBitSet = true;
1832 break;
1833 }
1834
1835 // If this is a signed shift right, and the high bit is modified
1836 // by the logical operation, do not perform the transformation.
1837 // The highBitSet boolean indicates the value of the high bit of
1838 // the constant which would cause it to be modified for this
1839 // operation.
1840 //
1841 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1842 uint64_t Val = Op0C->getRawValue();
1843 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1844 }
1845
1846 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001847 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001848
1849 Instruction *NewShift =
1850 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1851 Op0BO->getName());
1852 Op0BO->setName("");
1853 InsertNewInstBefore(NewShift, I);
1854
1855 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1856 NewRHS);
1857 }
1858 }
1859
Chris Lattner3204d4e2003-07-24 17:52:58 +00001860 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001861 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00001862 if (ConstantUInt *ShiftAmt1C =
1863 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001864 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1865 unsigned ShiftAmt2 = CUI->getValue();
1866
1867 // Check for (A << c1) << c2 and (A >> c1) >> c2
1868 if (I.getOpcode() == Op0SI->getOpcode()) {
1869 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001870 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
1871 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00001872 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1873 ConstantUInt::get(Type::UByteTy, Amt));
1874 }
1875
Chris Lattnerab780df2003-07-24 18:38:56 +00001876 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1877 // signed types, we can only support the (A >> c1) << c2 configuration,
1878 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001879 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001880 // Calculate bitmask for what gets shifted off the edge...
1881 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001882 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001883 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001884 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001885 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00001886
1887 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001888 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
1889 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00001890 InsertNewInstBefore(Mask, I);
1891
1892 // Figure out what flavor of shift we should use...
1893 if (ShiftAmt1 == ShiftAmt2)
1894 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1895 else if (ShiftAmt1 < ShiftAmt2) {
1896 return new ShiftInst(I.getOpcode(), Mask,
1897 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1898 } else {
1899 return new ShiftInst(Op0SI->getOpcode(), Mask,
1900 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1901 }
1902 }
1903 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001904 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00001905
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001906 return 0;
1907}
1908
1909
Chris Lattner48a44f72002-05-02 17:06:02 +00001910// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1911// instruction.
1912//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001913static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1914 const Type *DstTy) {
Chris Lattner48a44f72002-05-02 17:06:02 +00001915
Chris Lattner650b6da2002-08-02 20:00:25 +00001916 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1917 // are identical and the bits don't get reinterpreted (for example
Chris Lattner0bb75912002-08-14 23:21:10 +00001918 // int->float->int would not be allowed)
Misha Brukmane5838c42003-05-20 18:45:36 +00001919 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00001920 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00001921
1922 // Allow free casting and conversion of sizes as long as the sign doesn't
1923 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00001924 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00001925 unsigned SrcSize = SrcTy->getPrimitiveSize();
1926 unsigned MidSize = MidTy->getPrimitiveSize();
1927 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner650b6da2002-08-02 20:00:25 +00001928
Chris Lattner3732aca2002-08-15 16:15:25 +00001929 // Cases where we are monotonically decreasing the size of the type are
1930 // always ok, regardless of what sign changes are going on.
1931 //
Chris Lattner0bb75912002-08-14 23:21:10 +00001932 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner650b6da2002-08-02 20:00:25 +00001933 return true;
Chris Lattner3732aca2002-08-15 16:15:25 +00001934
Chris Lattner555518c2002-09-23 23:39:43 +00001935 // Cases where the source and destination type are the same, but the middle
1936 // type is bigger are noops.
1937 //
1938 if (SrcSize == DstSize && MidSize > SrcSize)
1939 return true;
1940
Chris Lattner3732aca2002-08-15 16:15:25 +00001941 // If we are monotonically growing, things are more complex.
1942 //
1943 if (SrcSize <= MidSize && MidSize <= DstSize) {
1944 // We have eight combinations of signedness to worry about. Here's the
1945 // table:
1946 static const int SignTable[8] = {
1947 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1948 1, // U U U Always ok
1949 1, // U U S Always ok
1950 3, // U S U Ok iff SrcSize != MidSize
1951 3, // U S S Ok iff SrcSize != MidSize
1952 0, // S U U Never ok
1953 2, // S U S Ok iff MidSize == DstSize
1954 1, // S S U Always ok
1955 1, // S S S Always ok
1956 };
1957
1958 // Choose an action based on the current entry of the signtable that this
1959 // cast of cast refers to...
1960 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1961 switch (SignTable[Row]) {
1962 case 0: return false; // Never ok
1963 case 1: return true; // Always ok
1964 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1965 case 3: // Ok iff SrcSize != MidSize
1966 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1967 default: assert(0 && "Bad entry in sign table!");
1968 }
Chris Lattner3732aca2002-08-15 16:15:25 +00001969 }
Chris Lattner650b6da2002-08-02 20:00:25 +00001970 }
Chris Lattner48a44f72002-05-02 17:06:02 +00001971
1972 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1973 // like: short -> ushort -> uint, because this can create wrong results if
1974 // the input short is negative!
1975 //
1976 return false;
1977}
1978
Chris Lattnerdfae8be2003-07-24 17:35:25 +00001979static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1980 if (V->getType() == Ty || isa<Constant>(V)) return false;
1981 if (const CastInst *CI = dyn_cast<CastInst>(V))
1982 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1983 return false;
1984 return true;
1985}
1986
1987/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1988/// InsertBefore instruction. This is specialized a bit to avoid inserting
1989/// casts that are known to not do anything...
1990///
1991Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1992 Instruction *InsertBefore) {
1993 if (V->getType() == DestTy) return V;
1994 if (Constant *C = dyn_cast<Constant>(V))
1995 return ConstantExpr::getCast(C, DestTy);
1996
1997 CastInst *CI = new CastInst(V, DestTy, V->getName());
1998 InsertNewInstBefore(CI, *InsertBefore);
1999 return CI;
2000}
Chris Lattner48a44f72002-05-02 17:06:02 +00002001
2002// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002003//
Chris Lattner113f4f42002-06-25 16:13:24 +00002004Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002005 Value *Src = CI.getOperand(0);
2006
Chris Lattner48a44f72002-05-02 17:06:02 +00002007 // If the user is casting a value to the same type, eliminate this cast
2008 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002009 if (CI.getType() == Src->getType())
2010 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002011
Chris Lattner48a44f72002-05-02 17:06:02 +00002012 // If casting the result of another cast instruction, try to eliminate this
2013 // one!
2014 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002015 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002016 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
2017 CSrc->getType(), CI.getType())) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002018 // This instruction now refers directly to the cast's src operand. This
2019 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002020 CI.setOperand(0, CSrc->getOperand(0));
2021 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002022 }
2023
Chris Lattner650b6da2002-08-02 20:00:25 +00002024 // If this is an A->B->A cast, and we are dealing with integral types, try
2025 // to convert this into a logical 'and' instruction.
2026 //
2027 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002028 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002029 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2030 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2031 assert(CSrc->getType() != Type::ULongTy &&
2032 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002033 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002034 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002035 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002036 }
2037 }
2038
Chris Lattner03841652004-05-25 04:29:21 +00002039 // If this is a cast to bool, turn it into the appropriate setne instruction.
2040 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002041 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002042 Constant::getNullValue(CI.getOperand(0)->getType()));
2043
Chris Lattnerd0d51602003-06-21 23:12:02 +00002044 // If casting the result of a getelementptr instruction with no offset, turn
2045 // this into a cast of the original pointer!
2046 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002047 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002048 bool AllZeroOperands = true;
2049 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2050 if (!isa<Constant>(GEP->getOperand(i)) ||
2051 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2052 AllZeroOperands = false;
2053 break;
2054 }
2055 if (AllZeroOperands) {
2056 CI.setOperand(0, GEP->getOperand(0));
2057 return &CI;
2058 }
2059 }
2060
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002061 // If we are casting a malloc or alloca to a pointer to a type of the same
2062 // size, rewrite the allocation instruction to allocate the "right" type.
2063 //
2064 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002065 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002066 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2067 // Get the type really allocated and the type casted to...
2068 const Type *AllocElTy = AI->getAllocatedType();
2069 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2070 const Type *CastElTy = PTy->getElementType();
2071 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002072
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002073 // If the allocation is for an even multiple of the cast type size
Chris Lattneraf789322003-11-03 01:29:41 +00002074 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002075 Value *Amt = ConstantUInt::get(Type::UIntTy,
2076 AllocElTySize/CastElTySize);
2077 std::string Name = AI->getName(); AI->setName("");
2078 AllocationInst *New;
2079 if (isa<MallocInst>(AI))
2080 New = new MallocInst(CastElTy, Amt, Name);
2081 else
2082 New = new AllocaInst(CastElTy, Amt, Name);
Chris Lattner652064e2004-04-30 04:37:52 +00002083 InsertNewInstBefore(New, *AI);
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002084 return ReplaceInstUsesWith(CI, New);
2085 }
2086 }
2087
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002088 // If the source value is an instruction with only this use, we can attempt to
2089 // propagate the cast into the instruction. Also, only handle integral types
2090 // for now.
2091 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002092 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002093 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2094 const Type *DestTy = CI.getType();
2095 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2096 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2097
2098 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2099 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2100
2101 switch (SrcI->getOpcode()) {
2102 case Instruction::Add:
2103 case Instruction::Mul:
2104 case Instruction::And:
2105 case Instruction::Or:
2106 case Instruction::Xor:
2107 // If we are discarding information, or just changing the sign, rewrite.
2108 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2109 // Don't insert two casts if they cannot be eliminated. We allow two
2110 // casts to be inserted if the sizes are the same. This could only be
2111 // converting signedness, which is a noop.
2112 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
2113 !ValueRequiresCast(Op0, DestTy)) {
2114 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2115 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2116 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2117 ->getOpcode(), Op0c, Op1c);
2118 }
2119 }
2120 break;
2121 case Instruction::Shl:
2122 // Allow changing the sign of the source operand. Do not allow changing
2123 // the size of the shift, UNLESS the shift amount is a constant. We
2124 // mush not change variable sized shifts to a smaller size, because it
2125 // is undefined to shift more bits out than exist in the value.
2126 if (DestBitSize == SrcBitSize ||
2127 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2128 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2129 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2130 }
2131 break;
2132 }
2133 }
2134
Chris Lattner260ab202002-04-18 17:39:14 +00002135 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002136}
2137
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002138/// GetSelectFoldableOperands - We want to turn code that looks like this:
2139/// %C = or %A, %B
2140/// %D = select %cond, %C, %A
2141/// into:
2142/// %C = select %cond, %B, 0
2143/// %D = or %A, %C
2144///
2145/// Assuming that the specified instruction is an operand to the select, return
2146/// a bitmask indicating which operands of this instruction are foldable if they
2147/// equal the other incoming value of the select.
2148///
2149static unsigned GetSelectFoldableOperands(Instruction *I) {
2150 switch (I->getOpcode()) {
2151 case Instruction::Add:
2152 case Instruction::Mul:
2153 case Instruction::And:
2154 case Instruction::Or:
2155 case Instruction::Xor:
2156 return 3; // Can fold through either operand.
2157 case Instruction::Sub: // Can only fold on the amount subtracted.
2158 case Instruction::Shl: // Can only fold on the shift amount.
2159 case Instruction::Shr:
2160 return 1;
2161 default:
2162 return 0; // Cannot fold
2163 }
2164}
2165
2166/// GetSelectFoldableConstant - For the same transformation as the previous
2167/// function, return the identity constant that goes into the select.
2168static Constant *GetSelectFoldableConstant(Instruction *I) {
2169 switch (I->getOpcode()) {
2170 default: assert(0 && "This cannot happen!"); abort();
2171 case Instruction::Add:
2172 case Instruction::Sub:
2173 case Instruction::Or:
2174 case Instruction::Xor:
2175 return Constant::getNullValue(I->getType());
2176 case Instruction::Shl:
2177 case Instruction::Shr:
2178 return Constant::getNullValue(Type::UByteTy);
2179 case Instruction::And:
2180 return ConstantInt::getAllOnesValue(I->getType());
2181 case Instruction::Mul:
2182 return ConstantInt::get(I->getType(), 1);
2183 }
2184}
2185
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002186Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002187 Value *CondVal = SI.getCondition();
2188 Value *TrueVal = SI.getTrueValue();
2189 Value *FalseVal = SI.getFalseValue();
2190
2191 // select true, X, Y -> X
2192 // select false, X, Y -> Y
2193 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002194 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002195 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002196 else {
2197 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002198 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002199 }
Chris Lattner533bc492004-03-30 19:37:13 +00002200
2201 // select C, X, X -> X
2202 if (TrueVal == FalseVal)
2203 return ReplaceInstUsesWith(SI, TrueVal);
2204
Chris Lattner1c631e82004-04-08 04:43:23 +00002205 if (SI.getType() == Type::BoolTy)
2206 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2207 if (C == ConstantBool::True) {
2208 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002209 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002210 } else {
2211 // Change: A = select B, false, C --> A = and !B, C
2212 Value *NotCond =
2213 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2214 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002215 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002216 }
2217 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2218 if (C == ConstantBool::False) {
2219 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002220 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002221 } else {
2222 // Change: A = select B, C, true --> A = or !B, C
2223 Value *NotCond =
2224 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2225 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002226 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002227 }
2228 }
2229
Chris Lattner183b3362004-04-09 19:05:30 +00002230 // Selecting between two integer constants?
2231 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2232 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2233 // select C, 1, 0 -> cast C to int
2234 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2235 return new CastInst(CondVal, SI.getType());
2236 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2237 // select C, 0, 1 -> cast !C to int
2238 Value *NotCond =
2239 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002240 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002241 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002242 }
Chris Lattner35167c32004-06-09 07:59:58 +00002243
2244 // If one of the constants is zero (we know they can't both be) and we
2245 // have a setcc instruction with zero, and we have an 'and' with the
2246 // non-constant value, eliminate this whole mess. This corresponds to
2247 // cases like this: ((X & 27) ? 27 : 0)
2248 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2249 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2250 if ((IC->getOpcode() == Instruction::SetEQ ||
2251 IC->getOpcode() == Instruction::SetNE) &&
2252 isa<ConstantInt>(IC->getOperand(1)) &&
2253 cast<Constant>(IC->getOperand(1))->isNullValue())
2254 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2255 if (ICA->getOpcode() == Instruction::And &&
2256 isa<ConstantInt>(ICA->getOperand(1)) &&
2257 (ICA->getOperand(1) == TrueValC ||
2258 ICA->getOperand(1) == FalseValC) &&
2259 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2260 // Okay, now we know that everything is set up, we just don't
2261 // know whether we have a setne or seteq and whether the true or
2262 // false val is the zero.
2263 bool ShouldNotVal = !TrueValC->isNullValue();
2264 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2265 Value *V = ICA;
2266 if (ShouldNotVal)
2267 V = InsertNewInstBefore(BinaryOperator::create(
2268 Instruction::Xor, V, ICA->getOperand(1)), SI);
2269 return ReplaceInstUsesWith(SI, V);
2270 }
Chris Lattner533bc492004-03-30 19:37:13 +00002271 }
Chris Lattner623fba12004-04-10 22:21:27 +00002272
2273 // See if we are selecting two values based on a comparison of the two values.
2274 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2275 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2276 // Transform (X == Y) ? X : Y -> Y
2277 if (SCI->getOpcode() == Instruction::SetEQ)
2278 return ReplaceInstUsesWith(SI, FalseVal);
2279 // Transform (X != Y) ? X : Y -> X
2280 if (SCI->getOpcode() == Instruction::SetNE)
2281 return ReplaceInstUsesWith(SI, TrueVal);
2282 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2283
2284 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2285 // Transform (X == Y) ? Y : X -> X
2286 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00002287 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002288 // Transform (X != Y) ? Y : X -> Y
2289 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00002290 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002291 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2292 }
2293 }
Chris Lattner1c631e82004-04-08 04:43:23 +00002294
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002295 // See if we can fold the select into one of our operands.
2296 if (SI.getType()->isInteger()) {
2297 // See the comment above GetSelectFoldableOperands for a description of the
2298 // transformation we are doing here.
2299 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2300 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2301 !isa<Constant>(FalseVal))
2302 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2303 unsigned OpToFold = 0;
2304 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2305 OpToFold = 1;
2306 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2307 OpToFold = 2;
2308 }
2309
2310 if (OpToFold) {
2311 Constant *C = GetSelectFoldableConstant(TVI);
2312 std::string Name = TVI->getName(); TVI->setName("");
2313 Instruction *NewSel =
2314 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2315 Name);
2316 InsertNewInstBefore(NewSel, SI);
2317 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2318 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2319 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2320 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2321 else {
2322 assert(0 && "Unknown instruction!!");
2323 }
2324 }
2325 }
2326
2327 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2328 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2329 !isa<Constant>(TrueVal))
2330 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2331 unsigned OpToFold = 0;
2332 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2333 OpToFold = 1;
2334 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2335 OpToFold = 2;
2336 }
2337
2338 if (OpToFold) {
2339 Constant *C = GetSelectFoldableConstant(FVI);
2340 std::string Name = FVI->getName(); FVI->setName("");
2341 Instruction *NewSel =
2342 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2343 Name);
2344 InsertNewInstBefore(NewSel, SI);
2345 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2346 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2347 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2348 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2349 else {
2350 assert(0 && "Unknown instruction!!");
2351 }
2352 }
2353 }
2354 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002355 return 0;
2356}
2357
2358
Chris Lattner970c33a2003-06-19 17:00:31 +00002359// CallInst simplification
2360//
2361Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00002362 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2363 // visitCallSite.
2364 if (Function *F = CI.getCalledFunction())
2365 switch (F->getIntrinsicID()) {
2366 case Intrinsic::memmove:
2367 case Intrinsic::memcpy:
2368 case Intrinsic::memset:
2369 // memmove/cpy/set of zero bytes is a noop.
2370 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2371 if (NumBytes->isNullValue())
2372 return EraseInstFromFunction(CI);
2373 }
2374 break;
2375 default:
2376 break;
2377 }
2378
Chris Lattneraec3d942003-10-07 22:32:43 +00002379 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00002380}
2381
2382// InvokeInst simplification
2383//
2384Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00002385 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00002386}
2387
Chris Lattneraec3d942003-10-07 22:32:43 +00002388// visitCallSite - Improvements for call and invoke instructions.
2389//
2390Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002391 bool Changed = false;
2392
2393 // If the callee is a constexpr cast of a function, attempt to move the cast
2394 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00002395 if (transformConstExprCastCall(CS)) return 0;
2396
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002397 Value *Callee = CS.getCalledValue();
2398 const PointerType *PTy = cast<PointerType>(Callee->getType());
2399 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2400 if (FTy->isVarArg()) {
2401 // See if we can optimize any arguments passed through the varargs area of
2402 // the call.
2403 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2404 E = CS.arg_end(); I != E; ++I)
2405 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2406 // If this cast does not effect the value passed through the varargs
2407 // area, we can eliminate the use of the cast.
2408 Value *Op = CI->getOperand(0);
2409 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2410 *I = Op;
2411 Changed = true;
2412 }
2413 }
2414 }
Chris Lattneraec3d942003-10-07 22:32:43 +00002415
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002416 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00002417}
2418
Chris Lattner970c33a2003-06-19 17:00:31 +00002419// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2420// attempt to move the cast to the arguments of the call/invoke.
2421//
2422bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2423 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2424 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
2425 if (CE->getOpcode() != Instruction::Cast ||
2426 !isa<ConstantPointerRef>(CE->getOperand(0)))
2427 return false;
2428 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
2429 if (!isa<Function>(CPR->getValue())) return false;
2430 Function *Callee = cast<Function>(CPR->getValue());
2431 Instruction *Caller = CS.getInstruction();
2432
2433 // Okay, this is a cast from a function to a different type. Unless doing so
2434 // would cause a type conversion of one of our arguments, change this call to
2435 // be a direct call with arguments casted to the appropriate types.
2436 //
2437 const FunctionType *FT = Callee->getFunctionType();
2438 const Type *OldRetTy = Caller->getType();
2439
Chris Lattner1f7942f2004-01-14 06:06:08 +00002440 // Check to see if we are changing the return type...
2441 if (OldRetTy != FT->getReturnType()) {
2442 if (Callee->isExternal() &&
2443 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2444 !Caller->use_empty())
2445 return false; // Cannot transform this return value...
2446
2447 // If the callsite is an invoke instruction, and the return value is used by
2448 // a PHI node in a successor, we cannot change the return type of the call
2449 // because there is no place to put the cast instruction (without breaking
2450 // the critical edge). Bail out in this case.
2451 if (!Caller->use_empty())
2452 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2453 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2454 UI != E; ++UI)
2455 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2456 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002457 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00002458 return false;
2459 }
Chris Lattner970c33a2003-06-19 17:00:31 +00002460
2461 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2462 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2463
2464 CallSite::arg_iterator AI = CS.arg_begin();
2465 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2466 const Type *ParamTy = FT->getParamType(i);
2467 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2468 if (Callee->isExternal() && !isConvertible) return false;
2469 }
2470
2471 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2472 Callee->isExternal())
2473 return false; // Do not delete arguments unless we have a function body...
2474
2475 // Okay, we decided that this is a safe thing to do: go ahead and start
2476 // inserting cast instructions as necessary...
2477 std::vector<Value*> Args;
2478 Args.reserve(NumActualArgs);
2479
2480 AI = CS.arg_begin();
2481 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2482 const Type *ParamTy = FT->getParamType(i);
2483 if ((*AI)->getType() == ParamTy) {
2484 Args.push_back(*AI);
2485 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00002486 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2487 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00002488 }
2489 }
2490
2491 // If the function takes more arguments than the call was taking, add them
2492 // now...
2493 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2494 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2495
2496 // If we are removing arguments to the function, emit an obnoxious warning...
2497 if (FT->getNumParams() < NumActualArgs)
2498 if (!FT->isVarArg()) {
2499 std::cerr << "WARNING: While resolving call to function '"
2500 << Callee->getName() << "' arguments were dropped!\n";
2501 } else {
2502 // Add all of the arguments in their promoted form to the arg list...
2503 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2504 const Type *PTy = getPromotedType((*AI)->getType());
2505 if (PTy != (*AI)->getType()) {
2506 // Must promote to pass through va_arg area!
2507 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2508 InsertNewInstBefore(Cast, *Caller);
2509 Args.push_back(Cast);
2510 } else {
2511 Args.push_back(*AI);
2512 }
2513 }
2514 }
2515
2516 if (FT->getReturnType() == Type::VoidTy)
2517 Caller->setName(""); // Void type should not have a name...
2518
2519 Instruction *NC;
2520 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002521 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00002522 Args, Caller->getName(), Caller);
2523 } else {
2524 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2525 }
2526
2527 // Insert a cast of the return type as necessary...
2528 Value *NV = NC;
2529 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2530 if (NV->getType() != Type::VoidTy) {
2531 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00002532
2533 // If this is an invoke instruction, we should insert it after the first
2534 // non-phi, instruction in the normal successor block.
2535 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2536 BasicBlock::iterator I = II->getNormalDest()->begin();
2537 while (isa<PHINode>(I)) ++I;
2538 InsertNewInstBefore(NC, *I);
2539 } else {
2540 // Otherwise, it's a call, just insert cast right after the call instr
2541 InsertNewInstBefore(NC, *Caller);
2542 }
Chris Lattner51ea1272004-02-28 05:22:00 +00002543 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00002544 } else {
2545 NV = Constant::getNullValue(Caller->getType());
2546 }
2547 }
2548
2549 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2550 Caller->replaceAllUsesWith(NV);
2551 Caller->getParent()->getInstList().erase(Caller);
2552 removeFromWorkList(Caller);
2553 return true;
2554}
2555
2556
Chris Lattner48a44f72002-05-02 17:06:02 +00002557
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002558// PHINode simplification
2559//
Chris Lattner113f4f42002-06-25 16:13:24 +00002560Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00002561 if (Value *V = hasConstantValue(&PN))
2562 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00002563
2564 // If the only user of this instruction is a cast instruction, and all of the
2565 // incoming values are constants, change this PHI to merge together the casted
2566 // constants.
2567 if (PN.hasOneUse())
2568 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2569 if (CI->getType() != PN.getType()) { // noop casts will be folded
2570 bool AllConstant = true;
2571 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2572 if (!isa<Constant>(PN.getIncomingValue(i))) {
2573 AllConstant = false;
2574 break;
2575 }
2576 if (AllConstant) {
2577 // Make a new PHI with all casted values.
2578 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2579 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2580 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2581 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2582 PN.getIncomingBlock(i));
2583 }
2584
2585 // Update the cast instruction.
2586 CI->setOperand(0, New);
2587 WorkList.push_back(CI); // revisit the cast instruction to fold.
2588 WorkList.push_back(New); // Make sure to revisit the new Phi
2589 return &PN; // PN is now dead!
2590 }
2591 }
Chris Lattner91daeb52003-12-19 05:58:40 +00002592 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002593}
2594
Chris Lattner69193f92004-04-05 01:30:19 +00002595static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
2596 Instruction *InsertPoint,
2597 InstCombiner *IC) {
2598 unsigned PS = IC->getTargetData().getPointerSize();
2599 const Type *VTy = V->getType();
2600 Instruction *Cast;
2601 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
2602 // We must insert a cast to ensure we sign-extend.
2603 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
2604 V->getName()), *InsertPoint);
2605 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
2606 *InsertPoint);
2607}
2608
Chris Lattner48a44f72002-05-02 17:06:02 +00002609
Chris Lattner113f4f42002-06-25 16:13:24 +00002610Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002611 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00002612 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00002613 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002614 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00002615 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002616
2617 bool HasZeroPointerIndex = false;
2618 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2619 HasZeroPointerIndex = C->isNullValue();
2620
2621 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00002622 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00002623
Chris Lattner69193f92004-04-05 01:30:19 +00002624 // Eliminate unneeded casts for indices.
2625 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00002626 gep_type_iterator GTI = gep_type_begin(GEP);
2627 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
2628 if (isa<SequentialType>(*GTI)) {
2629 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
2630 Value *Src = CI->getOperand(0);
2631 const Type *SrcTy = Src->getType();
2632 const Type *DestTy = CI->getType();
2633 if (Src->getType()->isInteger()) {
2634 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
2635 // We can always eliminate a cast from ulong or long to the other.
2636 // We can always eliminate a cast from uint to int or the other on
2637 // 32-bit pointer platforms.
2638 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
2639 MadeChange = true;
2640 GEP.setOperand(i, Src);
2641 }
2642 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2643 SrcTy->getPrimitiveSize() == 4) {
2644 // We can always eliminate a cast from int to [u]long. We can
2645 // eliminate a cast from uint to [u]long iff the target is a 32-bit
2646 // pointer target.
2647 if (SrcTy->isSigned() ||
2648 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
2649 MadeChange = true;
2650 GEP.setOperand(i, Src);
2651 }
Chris Lattner69193f92004-04-05 01:30:19 +00002652 }
2653 }
2654 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00002655 // If we are using a wider index than needed for this platform, shrink it
2656 // to what we need. If the incoming value needs a cast instruction,
2657 // insert it. This explicit cast can make subsequent optimizations more
2658 // obvious.
2659 Value *Op = GEP.getOperand(i);
2660 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00002661 if (Constant *C = dyn_cast<Constant>(Op)) {
2662 GEP.setOperand(i, ConstantExpr::getCast(C, TD->getIntPtrType()));
2663 MadeChange = true;
2664 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00002665 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
2666 Op->getName()), GEP);
2667 GEP.setOperand(i, Op);
2668 MadeChange = true;
2669 }
Chris Lattner69193f92004-04-05 01:30:19 +00002670 }
2671 if (MadeChange) return &GEP;
2672
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002673 // Combine Indices - If the source pointer to this getelementptr instruction
2674 // is a getelementptr instruction, combine the indices of the two
2675 // getelementptr instructions into a single instruction.
2676 //
Chris Lattner57c67b02004-03-25 22:59:29 +00002677 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00002678 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002679 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00002680 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002681 if (CE->getOpcode() == Instruction::GetElementPtr)
2682 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
2683 }
2684
2685 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002686 // Note that if our source is a gep chain itself that we wait for that
2687 // chain to be resolved before we perform this transformation. This
2688 // avoids us creating a TON of code in some cases.
2689 //
2690 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
2691 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
2692 return 0; // Wait until our source is folded to completion.
2693
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002694 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00002695
2696 // Find out whether the last index in the source GEP is a sequential idx.
2697 bool EndsWithSequential = false;
2698 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
2699 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00002700 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00002701
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002702 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00002703 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00002704 // Replace: gep (gep %P, long B), long A, ...
2705 // With: T = long A+B; gep %P, T, ...
2706 //
Chris Lattner5f667a62004-05-07 22:09:22 +00002707 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00002708 if (SO1 == Constant::getNullValue(SO1->getType())) {
2709 Sum = GO1;
2710 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2711 Sum = SO1;
2712 } else {
2713 // If they aren't the same type, convert both to an integer of the
2714 // target's pointer size.
2715 if (SO1->getType() != GO1->getType()) {
2716 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
2717 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
2718 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
2719 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
2720 } else {
2721 unsigned PS = TD->getPointerSize();
2722 Instruction *Cast;
2723 if (SO1->getType()->getPrimitiveSize() == PS) {
2724 // Convert GO1 to SO1's type.
2725 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
2726
2727 } else if (GO1->getType()->getPrimitiveSize() == PS) {
2728 // Convert SO1 to GO1's type.
2729 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
2730 } else {
2731 const Type *PT = TD->getIntPtrType();
2732 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
2733 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
2734 }
2735 }
2736 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002737 if (isa<Constant>(SO1) && isa<Constant>(GO1))
2738 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
2739 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002740 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
2741 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00002742 }
Chris Lattner69193f92004-04-05 01:30:19 +00002743 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002744
2745 // Recycle the GEP we already have if possible.
2746 if (SrcGEPOperands.size() == 2) {
2747 GEP.setOperand(0, SrcGEPOperands[0]);
2748 GEP.setOperand(1, Sum);
2749 return &GEP;
2750 } else {
2751 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2752 SrcGEPOperands.end()-1);
2753 Indices.push_back(Sum);
2754 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
2755 }
Chris Lattner69193f92004-04-05 01:30:19 +00002756 } else if (isa<Constant>(*GEP.idx_begin()) &&
2757 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00002758 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002759 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00002760 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2761 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002762 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
2763 }
2764
2765 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00002766 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002767
Chris Lattner5f667a62004-05-07 22:09:22 +00002768 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002769 // GEP of global variable. If all of the indices for this GEP are
2770 // constants, we can promote this to a constexpr instead of an instruction.
2771
2772 // Scan for nonconstants...
2773 std::vector<Constant*> Indices;
2774 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2775 for (; I != E && isa<Constant>(*I); ++I)
2776 Indices.push_back(cast<Constant>(*I));
2777
2778 if (I == E) { // If they are all constants...
Chris Lattner46b3d302003-04-16 22:40:51 +00002779 Constant *CE =
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002780 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
2781
2782 // Replace all uses of the GEP with the new constexpr...
2783 return ReplaceInstUsesWith(GEP, CE);
2784 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002785 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002786 if (CE->getOpcode() == Instruction::Cast) {
2787 if (HasZeroPointerIndex) {
2788 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2789 // into : GEP [10 x ubyte]* X, long 0, ...
2790 //
2791 // This occurs when the program declares an array extern like "int X[];"
2792 //
2793 Constant *X = CE->getOperand(0);
2794 const PointerType *CPTy = cast<PointerType>(CE->getType());
2795 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2796 if (const ArrayType *XATy =
2797 dyn_cast<ArrayType>(XTy->getElementType()))
2798 if (const ArrayType *CATy =
2799 dyn_cast<ArrayType>(CPTy->getElementType()))
2800 if (CATy->getElementType() == XATy->getElementType()) {
2801 // At this point, we know that the cast source type is a pointer
2802 // to an array of the same type as the destination pointer
2803 // array. Because the array type is never stepped over (there
2804 // is a leading zero) we can fold the cast into this GEP.
2805 GEP.setOperand(0, X);
2806 return &GEP;
2807 }
2808 }
2809 }
Chris Lattnerca081252001-12-14 16:52:21 +00002810 }
2811
Chris Lattnerca081252001-12-14 16:52:21 +00002812 return 0;
2813}
2814
Chris Lattner1085bdf2002-11-04 16:18:53 +00002815Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2816 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
2817 if (AI.isArrayAllocation()) // Check C != 1
2818 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
2819 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002820 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00002821
2822 // Create and insert the replacement instruction...
2823 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00002824 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002825 else {
2826 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00002827 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00002828 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00002829
2830 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00002831
2832 // Scan to the end of the allocation instructions, to skip over a block of
2833 // allocas if possible...
2834 //
2835 BasicBlock::iterator It = New;
2836 while (isa<AllocationInst>(*It)) ++It;
2837
2838 // Now that I is pointing to the first non-allocation-inst in the block,
2839 // insert our getelementptr instruction...
2840 //
Chris Lattner69193f92004-04-05 01:30:19 +00002841 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00002842 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
2843
2844 // Now make everything use the getelementptr instead of the original
2845 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00002846 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00002847 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00002848
2849 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
2850 // Note that we only do this for alloca's, because malloc should allocate and
2851 // return a unique pointer, even for a zero byte allocation.
2852 if (isa<AllocaInst>(AI) && TD->getTypeSize(AI.getAllocatedType()) == 0)
2853 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
2854
Chris Lattner1085bdf2002-11-04 16:18:53 +00002855 return 0;
2856}
2857
Chris Lattner8427bff2003-12-07 01:24:23 +00002858Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
2859 Value *Op = FI.getOperand(0);
2860
2861 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
2862 if (CastInst *CI = dyn_cast<CastInst>(Op))
2863 if (isa<PointerType>(CI->getOperand(0)->getType())) {
2864 FI.setOperand(0, CI->getOperand(0));
2865 return &FI;
2866 }
2867
Chris Lattnerf3a36602004-02-28 04:57:37 +00002868 // If we have 'free null' delete the instruction. This can happen in stl code
2869 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00002870 if (isa<ConstantPointerNull>(Op))
2871 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00002872
Chris Lattner8427bff2003-12-07 01:24:23 +00002873 return 0;
2874}
2875
2876
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002877/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
2878/// constantexpr, return the constant value being addressed by the constant
2879/// expression, or null if something is funny.
2880///
2881static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00002882 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002883 return 0; // Do not allow stepping over the value!
2884
2885 // Loop over all of the operands, tracking down which value we are
2886 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00002887 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2888 for (++I; I != E; ++I)
2889 if (const StructType *STy = dyn_cast<StructType>(*I)) {
2890 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
2891 assert(CU->getValue() < STy->getNumElements() &&
2892 "Struct index out of range!");
2893 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
2894 C = cast<Constant>(CS->getValues()[CU->getValue()]);
2895 } else if (isa<ConstantAggregateZero>(C)) {
2896 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
2897 } else {
2898 return 0;
2899 }
2900 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
2901 const ArrayType *ATy = cast<ArrayType>(*I);
2902 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
2903 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
2904 C = cast<Constant>(CA->getValues()[CI->getRawValue()]);
2905 else if (isa<ConstantAggregateZero>(C))
2906 C = Constant::getNullValue(ATy->getElementType());
2907 else
2908 return 0;
2909 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002910 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00002911 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002912 return C;
2913}
2914
2915Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
2916 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00002917 if (LI.isVolatile()) return 0;
2918
Chris Lattner6679e462004-04-14 03:28:36 +00002919 if (Constant *C = dyn_cast<Constant>(Op))
2920 if (C->isNullValue()) // load null -> 0
2921 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
2922 else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C))
2923 Op = CPR->getValue();
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002924
2925 // Instcombine load (constant global) into the value loaded...
2926 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002927 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002928 return ReplaceInstUsesWith(LI, GV->getInitializer());
2929
2930 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
2931 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
2932 if (CE->getOpcode() == Instruction::GetElementPtr)
2933 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
2934 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00002935 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002936 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
2937 return ReplaceInstUsesWith(LI, V);
Chris Lattnere228ee52004-04-08 20:39:49 +00002938
2939 // load (cast X) --> cast (load X) iff safe
2940 if (CastInst *CI = dyn_cast<CastInst>(Op)) {
2941 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
2942 if (const PointerType *SrcTy =
2943 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
2944 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerd9e58132004-05-07 15:35:56 +00002945 if (SrcPTy->isSized() && DestPTy->isSized() &&
2946 TD->getTypeSize(SrcPTy) == TD->getTypeSize(DestPTy) &&
Chris Lattnere228ee52004-04-08 20:39:49 +00002947 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
2948 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
2949 // Okay, we are casting from one integer or pointer type to another of
2950 // the same size. Instead of casting the pointer before the load, cast
2951 // the result of the loaded value.
2952 Value *NewLoad = InsertNewInstBefore(new LoadInst(CI->getOperand(0),
2953 CI->getName()), LI);
2954 // Now cast the result of the load.
2955 return new CastInst(NewLoad, LI.getType());
2956 }
2957 }
2958 }
2959
Chris Lattner0f1d8a32003-06-26 05:06:25 +00002960 return 0;
2961}
2962
2963
Chris Lattner9eef8a72003-06-04 04:46:00 +00002964Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2965 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattner4f7acca2004-02-27 06:27:46 +00002966 if (BI.isConditional() && !isa<Constant>(BI.getCondition())) {
Chris Lattnere967b342003-06-04 05:10:11 +00002967 if (Value *V = dyn_castNotVal(BI.getCondition())) {
2968 BasicBlock *TrueDest = BI.getSuccessor(0);
2969 BasicBlock *FalseDest = BI.getSuccessor(1);
2970 // Swap Destinations and condition...
2971 BI.setCondition(V);
2972 BI.setSuccessor(0, FalseDest);
2973 BI.setSuccessor(1, TrueDest);
2974 return &BI;
Chris Lattner4f7acca2004-02-27 06:27:46 +00002975 } else if (SetCondInst *I = dyn_cast<SetCondInst>(BI.getCondition())) {
2976 // Cannonicalize setne -> seteq
2977 if ((I->getOpcode() == Instruction::SetNE ||
2978 I->getOpcode() == Instruction::SetLE ||
2979 I->getOpcode() == Instruction::SetGE) && I->hasOneUse()) {
2980 std::string Name = I->getName(); I->setName("");
2981 Instruction::BinaryOps NewOpcode =
2982 SetCondInst::getInverseCondition(I->getOpcode());
2983 Value *NewSCC = BinaryOperator::create(NewOpcode, I->getOperand(0),
2984 I->getOperand(1), Name, I);
2985 BasicBlock *TrueDest = BI.getSuccessor(0);
2986 BasicBlock *FalseDest = BI.getSuccessor(1);
2987 // Swap Destinations and condition...
2988 BI.setCondition(NewSCC);
2989 BI.setSuccessor(0, FalseDest);
2990 BI.setSuccessor(1, TrueDest);
2991 removeFromWorkList(I);
2992 I->getParent()->getInstList().erase(I);
2993 WorkList.push_back(cast<Instruction>(NewSCC));
2994 return &BI;
2995 }
Chris Lattnere967b342003-06-04 05:10:11 +00002996 }
Chris Lattner4f7acca2004-02-27 06:27:46 +00002997 }
Chris Lattner9eef8a72003-06-04 04:46:00 +00002998 return 0;
2999}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003000
Chris Lattnerca081252001-12-14 16:52:21 +00003001
Chris Lattner99f48c62002-09-02 04:59:56 +00003002void InstCombiner::removeFromWorkList(Instruction *I) {
3003 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3004 WorkList.end());
3005}
3006
Chris Lattner113f4f42002-06-25 16:13:24 +00003007bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003008 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003009 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003010
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003011 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3012 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003013
Chris Lattnerca081252001-12-14 16:52:21 +00003014
3015 while (!WorkList.empty()) {
3016 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3017 WorkList.pop_back();
3018
Misha Brukman632df282002-10-29 23:06:16 +00003019 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003020 // Check to see if we can DIE the instruction...
3021 if (isInstructionTriviallyDead(I)) {
3022 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003023 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003024 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003025 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003026
3027 I->getParent()->getInstList().erase(I);
3028 removeFromWorkList(I);
3029 continue;
3030 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003031
Misha Brukman632df282002-10-29 23:06:16 +00003032 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003033 if (Constant *C = ConstantFoldInstruction(I)) {
3034 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003035 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003036 ReplaceInstUsesWith(*I, C);
3037
Chris Lattner99f48c62002-09-02 04:59:56 +00003038 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003039 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003040 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003041 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003042 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003043
Chris Lattner57c67b02004-03-25 22:59:29 +00003044 // Check to see if any of the operands of this instruction are a
3045 // ConstantPointerRef. Since they sneak in all over the place and inhibit
3046 // optimization, we want to strip them out unconditionally!
3047 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3048 if (ConstantPointerRef *CPR =
3049 dyn_cast<ConstantPointerRef>(I->getOperand(i))) {
3050 I->setOperand(i, CPR->getValue());
3051 Changed = true;
3052 }
3053
Chris Lattnerca081252001-12-14 16:52:21 +00003054 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003055 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003056 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003057 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003058 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003059 DEBUG(std::cerr << "IC: Old = " << *I
3060 << " New = " << *Result);
3061
Chris Lattner396dbfe2004-06-09 05:08:07 +00003062 // Everything uses the new instruction now.
3063 I->replaceAllUsesWith(Result);
3064
3065 // Push the new instruction and any users onto the worklist.
3066 WorkList.push_back(Result);
3067 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003068
3069 // Move the name to the new instruction first...
3070 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003071 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003072
3073 // Insert the new instruction into the basic block...
3074 BasicBlock *InstParent = I->getParent();
3075 InstParent->getInstList().insert(I, Result);
3076
Chris Lattner63d75af2004-05-01 23:27:23 +00003077 // Make sure that we reprocess all operands now that we reduced their
3078 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003079 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3080 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3081 WorkList.push_back(OpI);
3082
Chris Lattner396dbfe2004-06-09 05:08:07 +00003083 // Instructions can end up on the worklist more than once. Make sure
3084 // we do not process an instruction that has been deleted.
3085 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003086
3087 // Erase the old instruction.
3088 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003089 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003090 DEBUG(std::cerr << "IC: MOD = " << *I);
3091
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003092 // If the instruction was modified, it's possible that it is now dead.
3093 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003094 if (isInstructionTriviallyDead(I)) {
3095 // Make sure we process all operands now that we are reducing their
3096 // use counts.
3097 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3098 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3099 WorkList.push_back(OpI);
3100
3101 // Instructions may end up in the worklist more than once. Erase all
3102 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003103 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003104 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003105 } else {
3106 WorkList.push_back(Result);
3107 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003108 }
Chris Lattner053c0932002-05-14 15:24:07 +00003109 }
Chris Lattner260ab202002-04-18 17:39:14 +00003110 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003111 }
3112 }
3113
Chris Lattner260ab202002-04-18 17:39:14 +00003114 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003115}
3116
Chris Lattner8427bff2003-12-07 01:24:23 +00003117Pass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003118 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003119}
Brian Gaeke960707c2003-11-11 22:41:34 +00003120