blob: 4f6724ff52f9d3d1c88bd6aff2319c53a9d646ee [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswellb576c942003-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 Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-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 Lattnerdf17af12003-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 Lattner2cd91962003-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 Lattnere92d2f42003-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 Lattner2cd91962003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattnerc54e2b82003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner7bcc0e72004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner2a9c8472003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-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 Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner221d6882002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattner0cea42a2004-03-13 23:54:27 +000051#include "Support/Debug.h"
Chris Lattnera92f6962002-10-01 22:38:41 +000052#include "Support/Statistic.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000054using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000055
Chris Lattnerdd841ae2002-04-18 17:39:14 +000056namespace {
Chris Lattnera92f6962002-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 Lattnerf57b8452002-04-27 06:56:12 +000061 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-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 Lattnerbc61e662003-11-02 05:57:39 +000065 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000066
Chris Lattner7bcc0e72004-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 Lattner7e708292002-06-25 16:13:24 +000072 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000073 UI != UE; ++UI)
74 WorkList.push_back(cast<Instruction>(*UI));
75 }
76
Chris Lattner7bcc0e72004-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 Lattner62b14df2002-09-02 04:59:56 +000086 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000088 public:
Chris Lattner7e708292002-06-25 16:13:24 +000089 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000090
Chris Lattner97e52e42002-04-28 21:27:06 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000092 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000093 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000094 }
95
Chris Lattner28977af2004-04-05 01:30:19 +000096 TargetData &getTargetData() const { return *TD; }
97
Chris Lattnerdd841ae2002-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 Lattner233f7dc2002-08-12 21:17:25 +0000102 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000103 // otherwise - Change was made, replace I with returned instruction
104 //
Chris Lattner7e708292002-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 Lattnerea340052003-03-10 19:16:08 +0000114 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000115 Instruction *visitCastInst(CastInst &CI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000116 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000121 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000122 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000123 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000124 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000125 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000126
127 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000128 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000129
Chris Lattner9fe38862003-06-19 17:00:31 +0000130 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000131 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000132 bool transformConstExprCastCall(CallSite CS);
133
Chris Lattner28977af2004-04-05 01:30:19 +0000134 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000135 // InsertNewInstBefore - insert an instruction New before instruction Old
136 // in the program. Add the new instruction to the worklist.
137 //
Chris Lattner4cb170c2004-02-23 06:38:22 +0000138 Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000139 assert(New && New->getParent() == 0 &&
140 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000141 BasicBlock *BB = Old.getParent();
142 BB->getInstList().insert(&Old, New); // Insert inst
143 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000144 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000145 }
146
147 // ReplaceInstUsesWith - This method is to be used when an instruction is
148 // found to be dead, replacable with another preexisting expression. Here
149 // we add all uses of I to the worklist, replace all uses of I with the new
150 // value, then return I, so that the inst combiner will know that I was
151 // modified.
152 //
153 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000154 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000155 if (&I != V) {
156 I.replaceAllUsesWith(V);
157 return &I;
158 } else {
159 // If we are replacing the instruction with itself, this must be in a
160 // segment of unreachable code, so just clobber the instruction.
161 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
162 return &I;
163 }
Chris Lattner8b170942002-08-09 23:47:40 +0000164 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000165
166 // EraseInstFromFunction - When dealing with an instruction that has side
167 // effects or produces a void value, we can't rely on DCE to delete the
168 // instruction. Instead, visit methods should return the value returned by
169 // this function.
170 Instruction *EraseInstFromFunction(Instruction &I) {
171 assert(I.use_empty() && "Cannot erase instruction that is used!");
172 AddUsesToWorkList(I);
173 removeFromWorkList(&I);
174 I.getParent()->getInstList().erase(&I);
175 return 0; // Don't do anything with FI
176 }
177
178
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000179 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000180 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
181 /// InsertBefore instruction. This is specialized a bit to avoid inserting
182 /// casts that are known to not do anything...
183 ///
184 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
185 Instruction *InsertBefore);
186
Chris Lattnerc8802d22003-03-11 00:12:48 +0000187 // SimplifyCommutative - This performs a few simplifications for commutative
188 // operators...
189 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000190
191 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
192 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000193 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000194
Chris Lattnera6275cc2002-07-26 21:12:46 +0000195 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000196}
197
Chris Lattner4f98c562003-03-10 21:43:22 +0000198// getComplexity: Assign a complexity or rank value to LLVM Values...
199// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
200static unsigned getComplexity(Value *V) {
201 if (isa<Instruction>(V)) {
202 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
203 return 2;
204 return 3;
205 }
206 if (isa<Argument>(V)) return 2;
207 return isa<Constant>(V) ? 0 : 1;
208}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000209
Chris Lattnerc8802d22003-03-11 00:12:48 +0000210// isOnlyUse - Return true if this instruction will be deleted if we stop using
211// it.
212static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000213 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000214}
215
Chris Lattner4cb170c2004-02-23 06:38:22 +0000216// getPromotedType - Return the specified type promoted as it would be to pass
217// though a va_arg area...
218static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000219 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000220 case Type::SByteTyID:
221 case Type::ShortTyID: return Type::IntTy;
222 case Type::UByteTyID:
223 case Type::UShortTyID: return Type::UIntTy;
224 case Type::FloatTyID: return Type::DoubleTy;
225 default: return Ty;
226 }
227}
228
Chris Lattner4f98c562003-03-10 21:43:22 +0000229// SimplifyCommutative - This performs a few simplifications for commutative
230// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000231//
Chris Lattner4f98c562003-03-10 21:43:22 +0000232// 1. Order operands such that they are listed from right (least complex) to
233// left (most complex). This puts constants before unary operators before
234// binary operators.
235//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000236// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
237// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000238//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000239bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000240 bool Changed = false;
241 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
242 Changed = !I.swapOperands();
243
244 if (!I.isAssociative()) return Changed;
245 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000246 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
247 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
248 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000249 Constant *Folded = ConstantExpr::get(I.getOpcode(),
250 cast<Constant>(I.getOperand(1)),
251 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000252 I.setOperand(0, Op->getOperand(0));
253 I.setOperand(1, Folded);
254 return true;
255 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
256 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
257 isOnlyUse(Op) && isOnlyUse(Op1)) {
258 Constant *C1 = cast<Constant>(Op->getOperand(1));
259 Constant *C2 = cast<Constant>(Op1->getOperand(1));
260
261 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000262 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000263 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
264 Op1->getOperand(0),
265 Op1->getName(), &I);
266 WorkList.push_back(New);
267 I.setOperand(0, New);
268 I.setOperand(1, Folded);
269 return true;
270 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000271 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000272 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000273}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000274
Chris Lattner8d969642003-03-10 23:06:50 +0000275// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
276// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000277//
Chris Lattner8d969642003-03-10 23:06:50 +0000278static inline Value *dyn_castNegVal(Value *V) {
279 if (BinaryOperator::isNeg(V))
280 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
281
Chris Lattnerfe32e0c2003-04-30 22:19:10 +0000282 // Constants can be considered to be negated values if they can be folded...
283 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000284 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000285 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000286}
287
Chris Lattner8d969642003-03-10 23:06:50 +0000288static inline Value *dyn_castNotVal(Value *V) {
289 if (BinaryOperator::isNot(V))
290 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
291
292 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000293 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000294 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000295 return 0;
296}
297
Chris Lattnerc8802d22003-03-11 00:12:48 +0000298// dyn_castFoldableMul - If this value is a multiply that can be folded into
299// other computations (because it has a constant operand), return the
300// non-constant operand of the multiply.
301//
302static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000303 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattnerc8802d22003-03-11 00:12:48 +0000304 if (Instruction *I = dyn_cast<Instruction>(V))
305 if (I->getOpcode() == Instruction::Mul)
306 if (isa<Constant>(I->getOperand(1)))
307 return I->getOperand(0);
308 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000309}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000310
Chris Lattnerc8802d22003-03-11 00:12:48 +0000311// dyn_castMaskingAnd - If this value is an And instruction masking a value with
312// a constant, return the constant being anded with.
313//
Chris Lattnere132d952003-08-12 19:17:27 +0000314template<class ValueType>
315static inline Constant *dyn_castMaskingAnd(ValueType *V) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000316 if (Instruction *I = dyn_cast<Instruction>(V))
317 if (I->getOpcode() == Instruction::And)
318 return dyn_cast<Constant>(I->getOperand(1));
319
320 // If this is a constant, it acts just like we were masking with it.
321 return dyn_cast<Constant>(V);
322}
Chris Lattnera2881962003-02-18 19:28:33 +0000323
324// Log2 - Calculate the log base 2 for the specified value if it is exactly a
325// power of 2.
326static unsigned Log2(uint64_t Val) {
327 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
328 unsigned Count = 0;
329 while (Val != 1) {
330 if (Val & 1) return 0; // Multiple bits set?
331 Val >>= 1;
332 ++Count;
333 }
334 return Count;
Chris Lattneraf2930e2002-08-14 17:51:49 +0000335}
336
Chris Lattner564a7272003-08-13 19:01:45 +0000337
338/// AssociativeOpt - Perform an optimization on an associative operator. This
339/// function is designed to check a chain of associative operators for a
340/// potential to apply a certain optimization. Since the optimization may be
341/// applicable if the expression was reassociated, this checks the chain, then
342/// reassociates the expression as necessary to expose the optimization
343/// opportunity. This makes use of a special Functor, which must define
344/// 'shouldApply' and 'apply' methods.
345///
346template<typename Functor>
347Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
348 unsigned Opcode = Root.getOpcode();
349 Value *LHS = Root.getOperand(0);
350
351 // Quick check, see if the immediate LHS matches...
352 if (F.shouldApply(LHS))
353 return F.apply(Root);
354
355 // Otherwise, if the LHS is not of the same opcode as the root, return.
356 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000357 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000358 // Should we apply this transform to the RHS?
359 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
360
361 // If not to the RHS, check to see if we should apply to the LHS...
362 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
363 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
364 ShouldApply = true;
365 }
366
367 // If the functor wants to apply the optimization to the RHS of LHSI,
368 // reassociate the expression from ((? op A) op B) to (? op (A op B))
369 if (ShouldApply) {
370 BasicBlock *BB = Root.getParent();
Chris Lattner564a7272003-08-13 19:01:45 +0000371
372 // Now all of the instructions are in the current basic block, go ahead
373 // and perform the reassociation.
374 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
375
376 // First move the selected RHS to the LHS of the root...
377 Root.setOperand(0, LHSI->getOperand(1));
378
379 // Make what used to be the LHS of the root be the user of the root...
380 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000381 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000382 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
383 return 0;
384 }
Chris Lattner65725312004-04-16 18:08:07 +0000385 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000386 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000387 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
388 BasicBlock::iterator ARI = &Root; ++ARI;
389 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
390 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000391
392 // Now propagate the ExtraOperand down the chain of instructions until we
393 // get to LHSI.
394 while (TmpLHSI != LHSI) {
395 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000396 // Move the instruction to immediately before the chain we are
397 // constructing to avoid breaking dominance properties.
398 NextLHSI->getParent()->getInstList().remove(NextLHSI);
399 BB->getInstList().insert(ARI, NextLHSI);
400 ARI = NextLHSI;
401
Chris Lattner564a7272003-08-13 19:01:45 +0000402 Value *NextOp = NextLHSI->getOperand(1);
403 NextLHSI->setOperand(1, ExtraOperand);
404 TmpLHSI = NextLHSI;
405 ExtraOperand = NextOp;
406 }
407
408 // Now that the instructions are reassociated, have the functor perform
409 // the transformation...
410 return F.apply(Root);
411 }
412
413 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
414 }
415 return 0;
416}
417
418
419// AddRHS - Implements: X + X --> X << 1
420struct AddRHS {
421 Value *RHS;
422 AddRHS(Value *rhs) : RHS(rhs) {}
423 bool shouldApply(Value *LHS) const { return LHS == RHS; }
424 Instruction *apply(BinaryOperator &Add) const {
425 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
426 ConstantInt::get(Type::UByteTy, 1));
427 }
428};
429
430// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
431// iff C1&C2 == 0
432struct AddMaskingAnd {
433 Constant *C2;
434 AddMaskingAnd(Constant *c) : C2(c) {}
435 bool shouldApply(Value *LHS) const {
436 if (Constant *C1 = dyn_castMaskingAnd(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000437 return ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000438 return false;
439 }
440 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000441 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000442 }
443};
444
Chris Lattner2eefe512004-04-09 19:05:30 +0000445static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
446 InstCombiner *IC) {
447 // Figure out if the constant is the left or the right argument.
448 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
449 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000450
Chris Lattner2eefe512004-04-09 19:05:30 +0000451 if (Constant *SOC = dyn_cast<Constant>(SO)) {
452 if (ConstIsRHS)
453 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
454 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
455 }
456
457 Value *Op0 = SO, *Op1 = ConstOperand;
458 if (!ConstIsRHS)
459 std::swap(Op0, Op1);
460 Instruction *New;
461 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
462 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
463 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
464 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattner326c0f32004-04-10 19:15:56 +0000465 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000466 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000467 abort();
468 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000469 return IC->InsertNewInstBefore(New, BI);
470}
471
472// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
473// constant as the other operand, try to fold the binary operator into the
474// select arguments.
475static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
476 InstCombiner *IC) {
477 // Don't modify shared select instructions
478 if (!SI->hasOneUse()) return 0;
479 Value *TV = SI->getOperand(1);
480 Value *FV = SI->getOperand(2);
481
482 if (isa<Constant>(TV) || isa<Constant>(FV)) {
483 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
484 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
485
486 return new SelectInst(SI->getCondition(), SelectTrueVal,
487 SelectFalseVal);
488 }
489 return 0;
490}
Chris Lattner564a7272003-08-13 19:01:45 +0000491
Chris Lattner7e708292002-06-25 16:13:24 +0000492Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000493 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000494 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000495
Chris Lattner66331a42004-04-10 22:01:55 +0000496 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
497 // X + 0 --> X
498 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
499 RHSC->isNullValue())
500 return ReplaceInstUsesWith(I, LHS);
501
502 // X + (signbit) --> X ^ signbit
503 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
504 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
505 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
506 if (Val == (1ULL << NumBits-1))
Chris Lattner48595f12004-06-10 02:07:29 +0000507 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000508 }
509 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000510
Chris Lattner564a7272003-08-13 19:01:45 +0000511 // X + X --> X << 1
512 if (I.getType()->isInteger())
513 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattnere92d2f42003-08-13 04:18:28 +0000514
Chris Lattner5c4afb92002-05-08 22:46:53 +0000515 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000516 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000517 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000518
519 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000520 if (!isa<Constant>(RHS))
521 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000522 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000523
Chris Lattnerad3448c2003-02-18 19:57:07 +0000524 // X*C + X --> X * (C+1)
525 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000526 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000527 ConstantExpr::getAdd(
Chris Lattner2a9c8472003-05-27 16:40:51 +0000528 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
529 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +0000530 return BinaryOperator::createMul(RHS, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000531 }
532
533 // X + X*C --> X * (C+1)
534 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000535 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000536 ConstantExpr::getAdd(
Chris Lattner2a9c8472003-05-27 16:40:51 +0000537 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
538 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +0000539 return BinaryOperator::createMul(LHS, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000540 }
541
Chris Lattner564a7272003-08-13 19:01:45 +0000542 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
543 if (Constant *C2 = dyn_castMaskingAnd(RHS))
544 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000545
Chris Lattner6b032052003-10-02 15:11:26 +0000546 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
547 if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
548 switch (ILHS->getOpcode()) {
549 case Instruction::Xor:
550 // ~X + C --> (C-1) - X
551 if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
552 if (XorRHS->isAllOnesValue())
Chris Lattner48595f12004-06-10 02:07:29 +0000553 return BinaryOperator::createSub(ConstantExpr::getSub(CRHS,
554 ConstantInt::get(I.getType(), 1)),
Chris Lattner6b032052003-10-02 15:11:26 +0000555 ILHS->getOperand(0));
556 break;
Chris Lattner2eefe512004-04-09 19:05:30 +0000557 case Instruction::Select:
558 // Try to fold constant add into select arguments.
559 if (Instruction *R = FoldBinOpIntoSelect(I,cast<SelectInst>(ILHS),this))
560 return R;
561
Chris Lattner6b032052003-10-02 15:11:26 +0000562 default: break;
563 }
564 }
565 }
566
Chris Lattner7e708292002-06-25 16:13:24 +0000567 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000568}
569
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000570// isSignBit - Return true if the value represented by the constant only has the
571// highest order bit set.
572static bool isSignBit(ConstantInt *CI) {
573 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
574 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
575}
576
Chris Lattner24c8e382003-07-24 17:35:25 +0000577static unsigned getTypeSizeInBits(const Type *Ty) {
578 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
579}
580
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000581/// RemoveNoopCast - Strip off nonconverting casts from the value.
582///
583static Value *RemoveNoopCast(Value *V) {
584 if (CastInst *CI = dyn_cast<CastInst>(V)) {
585 const Type *CTy = CI->getType();
586 const Type *OpTy = CI->getOperand(0)->getType();
587 if (CTy->isInteger() && OpTy->isInteger()) {
588 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
589 return RemoveNoopCast(CI->getOperand(0));
590 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
591 return RemoveNoopCast(CI->getOperand(0));
592 }
593 return V;
594}
595
Chris Lattner7e708292002-06-25 16:13:24 +0000596Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000597 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000598
Chris Lattner233f7dc2002-08-12 21:17:25 +0000599 if (Op0 == Op1) // sub X, X -> 0
600 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000601
Chris Lattner233f7dc2002-08-12 21:17:25 +0000602 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000603 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000604 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000605
Chris Lattnerd65460f2003-11-05 01:06:05 +0000606 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
607 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000608 if (C->isAllOnesValue())
609 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000610
Chris Lattnerd65460f2003-11-05 01:06:05 +0000611 // C - ~X == X + (1+C)
612 if (BinaryOperator::isNot(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000613 return BinaryOperator::createAdd(
614 BinaryOperator::getNotArgument(cast<BinaryOperator>(Op1)),
615 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000616 // -((uint)X >> 31) -> ((int)X >> 31)
617 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000618 if (C->isNullValue()) {
619 Value *NoopCastedRHS = RemoveNoopCast(Op1);
620 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +0000621 if (SI->getOpcode() == Instruction::Shr)
622 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
623 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000624 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000625 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000626 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000627 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000628 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000629 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner9c290672004-03-12 23:53:13 +0000630 // Ok, the transformation is safe. Insert a cast of the incoming
631 // value, then the new shift, then the new cast.
632 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
633 SI->getOperand(0)->getName());
634 Value *InV = InsertNewInstBefore(FirstCast, I);
635 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
636 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000637 if (NewShift->getType() == I.getType())
638 return NewShift;
639 else {
640 InV = InsertNewInstBefore(NewShift, I);
641 return new CastInst(NewShift, I.getType());
642 }
Chris Lattner9c290672004-03-12 23:53:13 +0000643 }
644 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000645 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000646
647 // Try to fold constant sub into select arguments.
648 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
649 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
650 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000651 }
652
Chris Lattnera2881962003-02-18 19:28:33 +0000653 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerfd059242003-10-15 16:48:29 +0000654 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000655 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
656 // is not used by anyone else...
657 //
Chris Lattner0517e722004-02-02 20:09:56 +0000658 if (Op1I->getOpcode() == Instruction::Sub &&
659 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000660 // Swap the two operands of the subexpr...
661 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
662 Op1I->setOperand(0, IIOp1);
663 Op1I->setOperand(1, IIOp0);
664
665 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +0000666 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000667 }
668
669 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
670 //
671 if (Op1I->getOpcode() == Instruction::And &&
672 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
673 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
674
Chris Lattnerf523d062004-06-09 05:08:07 +0000675 Value *NewNot =
676 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000677 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000678 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000679
680 // X - X*C --> X * (1-C)
681 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000682 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000683 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000684 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000685 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattner48595f12004-06-10 02:07:29 +0000686 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000687 }
Chris Lattner40371712002-05-09 01:29:19 +0000688 }
Chris Lattnera2881962003-02-18 19:28:33 +0000689
Chris Lattnerad3448c2003-02-18 19:57:07 +0000690 // X*C - X --> X * (C-1)
691 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000692 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000693 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000694 ConstantInt::get(I.getType(), 1));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000695 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattner48595f12004-06-10 02:07:29 +0000696 return BinaryOperator::createMul(Op1, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000697 }
698
Chris Lattner3f5b8772002-05-06 16:14:14 +0000699 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000700}
701
Chris Lattner4cb170c2004-02-23 06:38:22 +0000702/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
703/// really just returns true if the most significant (sign) bit is set.
704static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
705 if (RHS->getType()->isSigned()) {
706 // True if source is LHS < 0 or LHS <= -1
707 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
708 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
709 } else {
710 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
711 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
712 // the size of the integer type.
713 if (Opcode == Instruction::SetGE)
714 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
715 if (Opcode == Instruction::SetGT)
716 return RHSC->getValue() ==
717 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
718 }
719 return false;
720}
721
Chris Lattner7e708292002-06-25 16:13:24 +0000722Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000723 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +0000724 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000725
Chris Lattner233f7dc2002-08-12 21:17:25 +0000726 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +0000727 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
728 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +0000729
730 // ((X << C1)*C2) == (X * (C2 << C1))
731 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
732 if (SI->getOpcode() == Instruction::Shl)
733 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000734 return BinaryOperator::createMul(SI->getOperand(0),
735 ConstantExpr::getShl(CI, ShOp));
Chris Lattner7c4049c2004-01-12 19:35:11 +0000736
Chris Lattner515c97c2003-09-11 22:24:54 +0000737 if (CI->isNullValue())
738 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
739 if (CI->equalsInt(1)) // X * 1 == X
740 return ReplaceInstUsesWith(I, Op0);
741 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +0000742 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +0000743
Chris Lattner515c97c2003-09-11 22:24:54 +0000744 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnera2881962003-02-18 19:28:33 +0000745 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
746 return new ShiftInst(Instruction::Shl, Op0,
747 ConstantUInt::get(Type::UByteTy, C));
748 } else {
749 ConstantFP *Op1F = cast<ConstantFP>(Op1);
750 if (Op1F->isNullValue())
751 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +0000752
Chris Lattnera2881962003-02-18 19:28:33 +0000753 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
754 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
755 if (Op1F->getValue() == 1.0)
756 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
757 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000758
759 // Try to fold constant mul into select arguments.
760 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
761 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
762 return R;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000763 }
764
Chris Lattnera4f445b2003-03-10 23:23:04 +0000765 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
766 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000767 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +0000768
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000769 // If one of the operands of the multiply is a cast from a boolean value, then
770 // we know the bool is either zero or one, so this is a 'masking' multiply.
771 // See if we can simplify things based on how the boolean was originally
772 // formed.
773 CastInst *BoolCast = 0;
774 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
775 if (CI->getOperand(0)->getType() == Type::BoolTy)
776 BoolCast = CI;
777 if (!BoolCast)
778 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
779 if (CI->getOperand(0)->getType() == Type::BoolTy)
780 BoolCast = CI;
781 if (BoolCast) {
782 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
783 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
784 const Type *SCOpTy = SCIOp0->getType();
785
Chris Lattner4cb170c2004-02-23 06:38:22 +0000786 // If the setcc is true iff the sign bit of X is set, then convert this
787 // multiply into a shift/and combination.
788 if (isa<ConstantInt>(SCIOp1) &&
789 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000790 // Shift the X value right to turn it into "all signbits".
791 Constant *Amt = ConstantUInt::get(Type::UByteTy,
792 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000793 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000794 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +0000795 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
796 SCIOp0->getName()), I);
797 }
798
799 Value *V =
800 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
801 BoolCast->getOperand(0)->getName()+
802 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000803
804 // If the multiply type is not the same as the source type, sign extend
805 // or truncate to the multiply type.
806 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +0000807 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000808
809 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +0000810 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000811 }
812 }
813 }
814
Chris Lattner7e708292002-06-25 16:13:24 +0000815 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000816}
817
Chris Lattner7e708292002-06-25 16:13:24 +0000818Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnera2881962003-02-18 19:28:33 +0000819 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000820 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000821 if (RHS->equalsInt(1))
822 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnera2881962003-02-18 19:28:33 +0000823
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000824 // div X, -1 == -X
825 if (RHS->isAllOnesValue())
826 return BinaryOperator::createNeg(I.getOperand(0));
827
Chris Lattnera2881962003-02-18 19:28:33 +0000828 // Check to see if this is an unsigned division with an exact power of 2,
829 // if so, convert to a right shift.
830 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
831 if (uint64_t Val = C->getValue()) // Don't break X / 0
832 if (uint64_t C = Log2(Val))
833 return new ShiftInst(Instruction::Shr, I.getOperand(0),
834 ConstantUInt::get(Type::UByteTy, C));
835 }
836
837 // 0 / X == 0, we don't need to preserve faults!
838 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
839 if (LHS->equalsInt(0))
840 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
841
Chris Lattner3f5b8772002-05-06 16:14:14 +0000842 return 0;
843}
844
845
Chris Lattner7e708292002-06-25 16:13:24 +0000846Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000847 if (I.getType()->isSigned())
848 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner1e3564e2004-07-06 07:11:42 +0000849 if (!isa<ConstantSInt>(RHSNeg) ||
850 cast<ConstantSInt>(RHSNeg)->getValue() >= 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000851 // X % -Y -> X % Y
852 AddUsesToWorkList(I);
853 I.setOperand(1, RHSNeg);
854 return &I;
855 }
856
Chris Lattnera2881962003-02-18 19:28:33 +0000857 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
858 if (RHS->equalsInt(1)) // X % 1 == 0
859 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
860
861 // Check to see if this is an unsigned remainder with an exact power of 2,
862 // if so, convert to a bitwise and.
863 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
864 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +0000865 if (!(Val & (Val-1))) // Power of 2
Chris Lattner48595f12004-06-10 02:07:29 +0000866 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattnera2881962003-02-18 19:28:33 +0000867 ConstantUInt::get(I.getType(), Val-1));
868 }
869
870 // 0 % X == 0, we don't need to preserve faults!
871 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
872 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +0000873 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
874
Chris Lattner3f5b8772002-05-06 16:14:14 +0000875 return 0;
876}
877
Chris Lattner8b170942002-08-09 23:47:40 +0000878// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000879static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000880 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
881 // Calculate -1 casted to the right type...
882 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
883 uint64_t Val = ~0ULL; // All ones
884 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
885 return CU->getValue() == Val-1;
886 }
887
888 const ConstantSInt *CS = cast<ConstantSInt>(C);
889
890 // Calculate 0111111111..11111
891 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
892 int64_t Val = INT64_MAX; // All ones
893 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
894 return CS->getValue() == Val-1;
895}
896
897// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000898static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000899 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
900 return CU->getValue() == 1;
901
902 const ConstantSInt *CS = cast<ConstantSInt>(C);
903
904 // Calculate 1111111111000000000000
905 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
906 int64_t Val = -1; // All ones
907 Val <<= TypeBits-1; // Shift over to the right spot
908 return CS->getValue() == Val+1;
909}
910
Chris Lattner457dd822004-06-09 07:59:58 +0000911// isOneBitSet - Return true if there is exactly one bit set in the specified
912// constant.
913static bool isOneBitSet(const ConstantInt *CI) {
914 uint64_t V = CI->getRawValue();
915 return V && (V & (V-1)) == 0;
916}
917
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000918/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
919/// are carefully arranged to allow folding of expressions such as:
920///
921/// (A < B) | (A > B) --> (A != B)
922///
923/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
924/// represents that the comparison is true if A == B, and bit value '1' is true
925/// if A < B.
926///
927static unsigned getSetCondCode(const SetCondInst *SCI) {
928 switch (SCI->getOpcode()) {
929 // False -> 0
930 case Instruction::SetGT: return 1;
931 case Instruction::SetEQ: return 2;
932 case Instruction::SetGE: return 3;
933 case Instruction::SetLT: return 4;
934 case Instruction::SetNE: return 5;
935 case Instruction::SetLE: return 6;
936 // True -> 7
937 default:
938 assert(0 && "Invalid SetCC opcode!");
939 return 0;
940 }
941}
942
943/// getSetCCValue - This is the complement of getSetCondCode, which turns an
944/// opcode and two operands into either a constant true or false, or a brand new
945/// SetCC instruction.
946static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
947 switch (Opcode) {
948 case 0: return ConstantBool::False;
949 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
950 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
951 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
952 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
953 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
954 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
955 case 7: return ConstantBool::True;
956 default: assert(0 && "Illegal SetCCCode!"); return 0;
957 }
958}
959
960// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
961struct FoldSetCCLogical {
962 InstCombiner &IC;
963 Value *LHS, *RHS;
964 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
965 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
966 bool shouldApply(Value *V) const {
967 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
968 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
969 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
970 return false;
971 }
972 Instruction *apply(BinaryOperator &Log) const {
973 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
974 if (SCI->getOperand(0) != LHS) {
975 assert(SCI->getOperand(1) == LHS);
976 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
977 }
978
979 unsigned LHSCode = getSetCondCode(SCI);
980 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
981 unsigned Code;
982 switch (Log.getOpcode()) {
983 case Instruction::And: Code = LHSCode & RHSCode; break;
984 case Instruction::Or: Code = LHSCode | RHSCode; break;
985 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +0000986 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000987 }
988
989 Value *RV = getSetCCValue(Code, LHS, RHS);
990 if (Instruction *I = dyn_cast<Instruction>(RV))
991 return I;
992 // Otherwise, it's a constant boolean value...
993 return IC.ReplaceInstUsesWith(Log, RV);
994 }
995};
996
997
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000998// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
999// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1000// guaranteed to be either a shift instruction or a binary operator.
1001Instruction *InstCombiner::OptAndOp(Instruction *Op,
1002 ConstantIntegral *OpRHS,
1003 ConstantIntegral *AndRHS,
1004 BinaryOperator &TheAnd) {
1005 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001006 Constant *Together = 0;
1007 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001008 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001009
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001010 switch (Op->getOpcode()) {
1011 case Instruction::Xor:
Chris Lattner7c4049c2004-01-12 19:35:11 +00001012 if (Together->isNullValue()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001013 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001014 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001015 } else if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001016 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1017 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001018 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001019 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001020 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001021 }
1022 break;
1023 case Instruction::Or:
1024 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattner7c4049c2004-01-12 19:35:11 +00001025 if (Together->isNullValue())
Chris Lattner48595f12004-06-10 02:07:29 +00001026 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001027 else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001028 if (Together == AndRHS) // (X | C) & C --> C
1029 return ReplaceInstUsesWith(TheAnd, AndRHS);
1030
Chris Lattnerfd059242003-10-15 16:48:29 +00001031 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001032 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1033 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001034 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001035 InsertNewInstBefore(Or, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001036 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001037 }
1038 }
1039 break;
1040 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001041 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001042 // Adding a one to a single bit bit-field should be turned into an XOR
1043 // of the bit. First thing to check is to see if this AND is with a
1044 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001045 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001046
1047 // Clear bits that are not part of the constant.
1048 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1049
1050 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001051 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001052 // Ok, at this point, we know that we are masking the result of the
1053 // ADD down to exactly one bit. If the constant we are adding has
1054 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001055 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001056
1057 // Check to see if any bits below the one bit set in AndRHSV are set.
1058 if ((AddRHS & (AndRHSV-1)) == 0) {
1059 // If not, the only thing that can effect the output of the AND is
1060 // the bit specified by AndRHSV. If that bit is set, the effect of
1061 // the XOR is to toggle the bit. If it is clear, then the ADD has
1062 // no effect.
1063 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1064 TheAnd.setOperand(0, X);
1065 return &TheAnd;
1066 } else {
1067 std::string Name = Op->getName(); Op->setName("");
1068 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001069 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001070 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001071 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001072 }
1073 }
1074 }
1075 }
1076 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001077
1078 case Instruction::Shl: {
1079 // We know that the AND will not produce any of the bits shifted in, so if
1080 // the anded constant includes them, clear them now!
1081 //
1082 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner48595f12004-06-10 02:07:29 +00001083 Constant *CI = ConstantExpr::getAnd(AndRHS,
1084 ConstantExpr::getShl(AllOne, OpRHS));
Chris Lattner62a355c2003-09-19 19:05:02 +00001085 if (CI != AndRHS) {
1086 TheAnd.setOperand(1, CI);
1087 return &TheAnd;
1088 }
1089 break;
1090 }
1091 case Instruction::Shr:
1092 // We know that the AND will not produce any of the bits shifted in, so if
1093 // the anded constant includes them, clear them now! This only applies to
1094 // unsigned shifts, because a signed shr may bring in set bits!
1095 //
1096 if (AndRHS->getType()->isUnsigned()) {
1097 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner48595f12004-06-10 02:07:29 +00001098 Constant *CI = ConstantExpr::getAnd(AndRHS,
1099 ConstantExpr::getShr(AllOne, OpRHS));
Chris Lattner62a355c2003-09-19 19:05:02 +00001100 if (CI != AndRHS) {
1101 TheAnd.setOperand(1, CI);
1102 return &TheAnd;
1103 }
1104 }
1105 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001106 }
1107 return 0;
1108}
1109
Chris Lattner8b170942002-08-09 23:47:40 +00001110
Chris Lattner7e708292002-06-25 16:13:24 +00001111Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001112 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001113 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001114
1115 // and X, X = X and X, 0 == 0
Chris Lattner233f7dc2002-08-12 21:17:25 +00001116 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1117 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001118
1119 // and X, -1 == X
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001120 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001121 if (RHS->isAllOnesValue())
1122 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001123
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001124 // Optimize a variety of ((val OP C1) & C2) combinations...
1125 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1126 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner06782f82003-07-23 19:36:21 +00001127 Value *X = Op0I->getOperand(0);
Chris Lattner58403262003-07-23 19:25:52 +00001128 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001129 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1130 return Res;
Chris Lattner06782f82003-07-23 19:36:21 +00001131 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001132
1133 // Try to fold constant and into select arguments.
1134 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1135 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1136 return R;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001137 }
1138
Chris Lattner8d969642003-03-10 23:06:50 +00001139 Value *Op0NotVal = dyn_castNotVal(Op0);
1140 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001141
Chris Lattner5b62aa72004-06-18 06:07:51 +00001142 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1143 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1144
Chris Lattnera2881962003-02-18 19:28:33 +00001145 // (~A & ~B) == (~(A | B)) - Demorgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001146 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001147 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1148 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001149 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001150 return BinaryOperator::createNot(Or);
1151 }
1152
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001153 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1154 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1155 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1156 return R;
1157
Chris Lattner7e708292002-06-25 16:13:24 +00001158 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001159}
1160
1161
1162
Chris Lattner7e708292002-06-25 16:13:24 +00001163Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001164 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001165 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001166
1167 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001168 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1169 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001170
1171 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001172 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001173 if (RHS->isAllOnesValue())
1174 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001175
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001176 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1177 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1178 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
1179 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1180 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001181 Instruction *Or = BinaryOperator::createOr(Op0I->getOperand(0), RHS,
1182 Op0Name);
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001183 InsertNewInstBefore(Or, I);
Chris Lattner48595f12004-06-10 02:07:29 +00001184 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, Op0CI));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001185 }
1186
1187 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1188 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
1189 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
1190 std::string Op0Name = Op0I->getName(); Op0I->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001191 Instruction *Or = BinaryOperator::createOr(Op0I->getOperand(0), RHS,
1192 Op0Name);
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001193 InsertNewInstBefore(Or, I);
Chris Lattner48595f12004-06-10 02:07:29 +00001194 return BinaryOperator::createXor(Or,
Chris Lattner448c3232004-06-10 02:12:35 +00001195 ConstantExpr::getAnd(Op0CI,
1196 ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001197 }
1198 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001199
1200 // Try to fold constant and into select arguments.
1201 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1202 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1203 return R;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001204 }
1205
Chris Lattner67ca7682003-08-12 19:11:07 +00001206 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnere132d952003-08-12 19:17:27 +00001207 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
1208 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
1209 if (LHS->getOperand(0) == RHS->getOperand(0))
1210 if (Constant *C0 = dyn_castMaskingAnd(LHS))
1211 if (Constant *C1 = dyn_castMaskingAnd(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001212 return BinaryOperator::createAnd(LHS->getOperand(0),
1213 ConstantExpr::getOr(C0, C1));
Chris Lattner67ca7682003-08-12 19:11:07 +00001214
Chris Lattnera27231a2003-03-10 23:13:59 +00001215 Value *Op0NotVal = dyn_castNotVal(Op0);
1216 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001217
Chris Lattnera27231a2003-03-10 23:13:59 +00001218 if (Op1 == Op0NotVal) // ~A | A == -1
1219 return ReplaceInstUsesWith(I,
1220 ConstantIntegral::getAllOnesValue(I.getType()));
1221
1222 if (Op0 == Op1NotVal) // A | ~A == -1
1223 return ReplaceInstUsesWith(I,
1224 ConstantIntegral::getAllOnesValue(I.getType()));
1225
1226 // (~A | ~B) == (~(A & B)) - Demorgan's Law
1227 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerf523d062004-06-09 05:08:07 +00001228 Value *And = InsertNewInstBefore(
Chris Lattner48595f12004-06-10 02:07:29 +00001229 BinaryOperator::createAnd(Op0NotVal,
1230 Op1NotVal,I.getName()+".demorgan"),I);
Chris Lattnera27231a2003-03-10 23:13:59 +00001231 return BinaryOperator::createNot(And);
1232 }
Chris Lattnera2881962003-02-18 19:28:33 +00001233
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001234 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1235 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1236 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1237 return R;
1238
Chris Lattner7e708292002-06-25 16:13:24 +00001239 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001240}
1241
Chris Lattnerc317d392004-02-16 01:20:27 +00001242// XorSelf - Implements: X ^ X --> 0
1243struct XorSelf {
1244 Value *RHS;
1245 XorSelf(Value *rhs) : RHS(rhs) {}
1246 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1247 Instruction *apply(BinaryOperator &Xor) const {
1248 return &Xor;
1249 }
1250};
Chris Lattner3f5b8772002-05-06 16:14:14 +00001251
1252
Chris Lattner7e708292002-06-25 16:13:24 +00001253Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001254 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001255 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001256
Chris Lattnerc317d392004-02-16 01:20:27 +00001257 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1258 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1259 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00001260 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00001261 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001262
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001263 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00001264 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001265 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001266 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00001267
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001268 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00001269 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001270 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00001271 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00001272 return new SetCondInst(SCI->getInverseCondition(),
1273 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001274
Chris Lattnerd65460f2003-11-05 01:06:05 +00001275 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00001276 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1277 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00001278 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1279 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001280 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00001281 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001282 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00001283
1284 // ~(~X & Y) --> (X | ~Y)
1285 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1286 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1287 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1288 Instruction *NotY =
1289 BinaryOperator::createNot(Op0I->getOperand(1),
1290 Op0I->getOperand(1)->getName()+".not");
1291 InsertNewInstBefore(NotY, I);
1292 return BinaryOperator::createOr(Op0NotVal, NotY);
1293 }
1294 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001295
1296 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001297 switch (Op0I->getOpcode()) {
1298 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00001299 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00001300 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00001301 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1302 return BinaryOperator::createSub(
1303 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001304 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00001305 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00001306 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001307 break;
1308 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001309 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001310 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1311 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001312 break;
1313 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001314 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00001315 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00001316 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001317 break;
1318 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001319 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00001320 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001321
1322 // Try to fold constant and into select arguments.
1323 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1324 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1325 return R;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001326 }
1327
Chris Lattner8d969642003-03-10 23:06:50 +00001328 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001329 if (X == Op1)
1330 return ReplaceInstUsesWith(I,
1331 ConstantIntegral::getAllOnesValue(I.getType()));
1332
Chris Lattner8d969642003-03-10 23:06:50 +00001333 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001334 if (X == Op0)
1335 return ReplaceInstUsesWith(I,
1336 ConstantIntegral::getAllOnesValue(I.getType()));
1337
Chris Lattnercb40a372003-03-10 18:24:17 +00001338 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00001339 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001340 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1341 cast<BinaryOperator>(Op1I)->swapOperands();
1342 I.swapOperands();
1343 std::swap(Op0, Op1);
1344 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1345 I.swapOperands();
1346 std::swap(Op0, Op1);
Chris Lattner26ca7e12004-02-16 03:54:20 +00001347 }
1348 } else if (Op1I->getOpcode() == Instruction::Xor) {
1349 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1350 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1351 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1352 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1353 }
Chris Lattnercb40a372003-03-10 18:24:17 +00001354
1355 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00001356 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001357 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1358 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00001359 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00001360 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1361 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001362 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00001363 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00001364 } else if (Op0I->getOpcode() == Instruction::Xor) {
1365 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1366 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1367 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1368 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00001369 }
1370
Chris Lattnerc8802d22003-03-11 00:12:48 +00001371 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1372 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1373 if (Constant *C2 = dyn_castMaskingAnd(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001374 if (ConstantExpr::getAnd(C1, C2)->isNullValue())
1375 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00001376
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001377 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1378 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1379 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1380 return R;
1381
Chris Lattner7e708292002-06-25 16:13:24 +00001382 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001383}
1384
Chris Lattner8b170942002-08-09 23:47:40 +00001385// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1386static Constant *AddOne(ConstantInt *C) {
Chris Lattner48595f12004-06-10 02:07:29 +00001387 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner8b170942002-08-09 23:47:40 +00001388}
1389static Constant *SubOne(ConstantInt *C) {
Chris Lattner48595f12004-06-10 02:07:29 +00001390 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner8b170942002-08-09 23:47:40 +00001391}
1392
Chris Lattner53a5b572002-05-09 20:11:54 +00001393// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1394// true when both operands are equal...
1395//
Chris Lattner7e708292002-06-25 16:13:24 +00001396static bool isTrueWhenEqual(Instruction &I) {
1397 return I.getOpcode() == Instruction::SetEQ ||
1398 I.getOpcode() == Instruction::SetGE ||
1399 I.getOpcode() == Instruction::SetLE;
Chris Lattner53a5b572002-05-09 20:11:54 +00001400}
1401
Chris Lattner7e708292002-06-25 16:13:24 +00001402Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001403 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00001404 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1405 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00001406
1407 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00001408 if (Op0 == Op1)
1409 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00001410
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001411 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1412 if (isa<ConstantPointerNull>(Op1) &&
1413 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner8b170942002-08-09 23:47:40 +00001414 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1415
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001416
Chris Lattner8b170942002-08-09 23:47:40 +00001417 // setcc's with boolean values can always be turned into bitwise operations
1418 if (Ty == Type::BoolTy) {
1419 // If this is <, >, or !=, we can change this into a simple xor instruction
1420 if (!isTrueWhenEqual(I))
Chris Lattner48595f12004-06-10 02:07:29 +00001421 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001422
1423 // Otherwise we need to make a temporary intermediate instruction and insert
1424 // it into the instruction stream. This is what we are after:
1425 //
1426 // seteq bool %A, %B -> ~(A^B)
1427 // setle bool %A, %B -> ~A | B
1428 // setge bool %A, %B -> A | ~B
1429 //
1430 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
Chris Lattner48595f12004-06-10 02:07:29 +00001431 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00001432 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00001433 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00001434 }
1435
1436 // Handle the setXe cases...
1437 assert(I.getOpcode() == Instruction::SetGE ||
1438 I.getOpcode() == Instruction::SetLE);
1439
1440 if (I.getOpcode() == Instruction::SetGE)
1441 std::swap(Op0, Op1); // Change setge -> setle
1442
1443 // Now we just have the SetLE case.
Chris Lattneraf2930e2002-08-14 17:51:49 +00001444 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00001445 InsertNewInstBefore(Not, I);
Chris Lattner48595f12004-06-10 02:07:29 +00001446 return BinaryOperator::createOr(Not, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001447 }
1448
Chris Lattner2be51ae2004-06-09 04:24:29 +00001449 // See if we are doing a comparison between a constant and an instruction that
1450 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00001451 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3c6a0d42004-05-25 06:32:08 +00001452 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner2be51ae2004-06-09 04:24:29 +00001453 if (LHSI->hasOneUse())
Chris Lattner457dd822004-06-09 07:59:58 +00001454 switch (LHSI->getOpcode()) {
1455 case Instruction::And:
1456 if (isa<ConstantInt>(LHSI->getOperand(1))) {
1457
Chris Lattner3c6a0d42004-05-25 06:32:08 +00001458
Chris Lattner457dd822004-06-09 07:59:58 +00001459 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1460 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1461 // happens a LOT in code produced by the C front-end, for bitfield
1462 // access.
1463 if (LHSI->getOperand(0)->hasOneUse())
1464 if (ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0)))
1465 if (ConstantUInt *ShAmt =
1466 dyn_cast<ConstantUInt>(Shift->getOperand(1))) {
1467 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1468
1469 // We can fold this as long as we can't shift unknown bits
1470 // into the mask. This can only happen with signed shift
1471 // rights, as they sign-extend.
1472 const Type *Ty = Shift->getType();
1473 if (Shift->getOpcode() != Instruction::Shr ||
1474 Shift->getType()->isUnsigned() ||
1475 // To test for the bad case of the signed shr, see if any
1476 // of the bits shifted in could be tested after the mask.
1477 ConstantExpr::getAnd(ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), ConstantUInt::get(Type::UByteTy, Ty->getPrimitiveSize()*8-ShAmt->getValue())), AndCST)->isNullValue()) {
1478 unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
1479 ? Instruction::Shr : Instruction::Shl;
1480 I.setOperand(1, ConstantExpr::get(ShiftOp, CI, ShAmt));
1481 LHSI->setOperand(1,ConstantExpr::get(ShiftOp,AndCST,ShAmt));
1482 LHSI->setOperand(0, Shift->getOperand(0));
1483 WorkList.push_back(Shift); // Shift is probably dead.
1484 AddUsesToWorkList(I);
1485 return &I;
1486 }
Chris Lattner2be51ae2004-06-09 04:24:29 +00001487 }
Chris Lattner457dd822004-06-09 07:59:58 +00001488 }
1489 break;
Chris Lattner48595f12004-06-10 02:07:29 +00001490 case Instruction::Div:
1491 if (0 && isa<ConstantInt>(LHSI->getOperand(1))) {
1492 std::cerr << "COULD FOLD: " << *LHSI;
1493 std::cerr << "COULD FOLD: " << I << "\n";
1494 }
1495 break;
Chris Lattner457dd822004-06-09 07:59:58 +00001496 case Instruction::Select:
Chris Lattner2be51ae2004-06-09 04:24:29 +00001497 // If either operand of the select is a constant, we can fold the
1498 // comparison into the select arms, which will cause one to be
1499 // constant folded and the select turned into a bitwise or.
1500 Value *Op1 = 0, *Op2 = 0;
Chris Lattner457dd822004-06-09 07:59:58 +00001501 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00001502 // Fold the known value into the constant operand.
1503 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1504 // Insert a new SetCC of the other select operand.
1505 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00001506 LHSI->getOperand(2), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00001507 I.getName()), I);
Chris Lattner457dd822004-06-09 07:59:58 +00001508 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00001509 // Fold the known value into the constant operand.
1510 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1511 // Insert a new SetCC of the other select operand.
1512 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00001513 LHSI->getOperand(1), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00001514 I.getName()), I);
1515 }
1516
1517 if (Op1)
Chris Lattner457dd822004-06-09 07:59:58 +00001518 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1519 break;
Chris Lattner2be51ae2004-06-09 04:24:29 +00001520 }
Chris Lattner3c6a0d42004-05-25 06:32:08 +00001521
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001522 // Simplify seteq and setne instructions...
1523 if (I.getOpcode() == Instruction::SetEQ ||
1524 I.getOpcode() == Instruction::SetNE) {
1525 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1526
Chris Lattner00b1a7e2003-07-23 17:26:36 +00001527 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001528 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00001529 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1530 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00001531 case Instruction::Rem:
1532 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1533 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
1534 BO->hasOneUse() &&
1535 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
1536 if (unsigned L2 =
1537 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
1538 const Type *UTy = BO->getType()->getUnsignedVersion();
1539 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
1540 UTy, "tmp"), I);
1541 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
1542 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
1543 RHSCst, BO->getName()), I);
1544 return BinaryOperator::create(I.getOpcode(), NewRem,
1545 Constant::getNullValue(UTy));
1546 }
1547 break;
1548
Chris Lattner934754b2003-08-13 05:33:12 +00001549 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00001550 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1551 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1552 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1553 ConstantExpr::getSub(CI, BOp1C));
1554 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00001555 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1556 // efficiently invertible, or if the add has just this one use.
1557 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner15d58b62004-06-27 22:51:36 +00001558
Chris Lattner934754b2003-08-13 05:33:12 +00001559 if (Value *NegVal = dyn_castNegVal(BOp1))
1560 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1561 else if (Value *NegVal = dyn_castNegVal(BOp0))
1562 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00001563 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00001564 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1565 BO->setName("");
1566 InsertNewInstBefore(Neg, I);
1567 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1568 }
1569 }
1570 break;
1571 case Instruction::Xor:
1572 // For the xor case, we can xor two constants together, eliminating
1573 // the explicit xor.
1574 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1575 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00001576 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00001577
1578 // FALLTHROUGH
1579 case Instruction::Sub:
1580 // Replace (([sub|xor] A, B) != 0) with (A != B)
1581 if (CI->isNullValue())
1582 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1583 BO->getOperand(1));
1584 break;
1585
1586 case Instruction::Or:
1587 // If bits are being or'd in that are not present in the constant we
1588 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00001589 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00001590 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00001591 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001592 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00001593 }
Chris Lattner934754b2003-08-13 05:33:12 +00001594 break;
1595
1596 case Instruction::And:
1597 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001598 // If bits are being compared against that are and'd out, then the
1599 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00001600 if (!ConstantExpr::getAnd(CI,
1601 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001602 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00001603
Chris Lattner457dd822004-06-09 07:59:58 +00001604 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00001605 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00001606 return new SetCondInst(isSetNE ? Instruction::SetEQ :
1607 Instruction::SetNE, Op0,
1608 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00001609
Chris Lattner934754b2003-08-13 05:33:12 +00001610 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1611 // to be a signed value as appropriate.
1612 if (isSignBit(BOC)) {
1613 Value *X = BO->getOperand(0);
1614 // If 'X' is not signed, insert a cast now...
1615 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001616 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner934754b2003-08-13 05:33:12 +00001617 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1618 InsertNewInstBefore(NewCI, I);
1619 X = NewCI;
1620 }
1621 return new SetCondInst(isSetNE ? Instruction::SetLT :
1622 Instruction::SetGE, X,
1623 Constant::getNullValue(X->getType()));
1624 }
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001625 }
Chris Lattner934754b2003-08-13 05:33:12 +00001626 default: break;
1627 }
1628 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001629 } else { // Not a SetEQ/SetNE
1630 // If the LHS is a cast from an integral value of the same size,
1631 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1632 Value *CastOp = Cast->getOperand(0);
1633 const Type *SrcTy = CastOp->getType();
1634 unsigned SrcTySize = SrcTy->getPrimitiveSize();
1635 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1636 SrcTySize == Cast->getType()->getPrimitiveSize()) {
1637 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
1638 "Source and destination signednesses should differ!");
1639 if (Cast->getType()->isSigned()) {
1640 // If this is a signed comparison, check for comparisons in the
1641 // vicinity of zero.
1642 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1643 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00001644 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001645 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1646 else if (I.getOpcode() == Instruction::SetGT &&
1647 cast<ConstantSInt>(CI)->getValue() == -1)
1648 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00001649 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001650 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1651 } else {
1652 ConstantUInt *CUI = cast<ConstantUInt>(CI);
1653 if (I.getOpcode() == Instruction::SetLT &&
1654 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1655 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00001656 return BinaryOperator::createSetGT(CastOp,
1657 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001658 else if (I.getOpcode() == Instruction::SetGT &&
1659 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1660 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00001661 return BinaryOperator::createSetLT(CastOp,
1662 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001663 }
1664 }
1665 }
Chris Lattner40f5d702003-06-04 05:10:11 +00001666 }
Chris Lattner074d84c2003-06-01 03:35:25 +00001667
Chris Lattner8b170942002-08-09 23:47:40 +00001668 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattner233f7dc2002-08-12 21:17:25 +00001669 if (CI->isMinValue()) {
Chris Lattner8b170942002-08-09 23:47:40 +00001670 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1671 return ReplaceInstUsesWith(I, ConstantBool::False);
1672 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1673 return ReplaceInstUsesWith(I, ConstantBool::True);
1674 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001675 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001676 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001677 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001678
Chris Lattner233f7dc2002-08-12 21:17:25 +00001679 } else if (CI->isMaxValue()) {
Chris Lattner8b170942002-08-09 23:47:40 +00001680 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1681 return ReplaceInstUsesWith(I, ConstantBool::False);
1682 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1683 return ReplaceInstUsesWith(I, ConstantBool::True);
1684 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001685 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001686 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001687 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001688
1689 // Comparing against a value really close to min or max?
1690 } else if (isMinValuePlusOne(CI)) {
1691 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001692 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001693 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001694 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001695
1696 } else if (isMaxValueMinusOne(CI)) {
1697 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001698 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001699 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001700 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001701 }
Chris Lattner45aaafe2004-02-23 05:47:48 +00001702
1703 // If we still have a setle or setge instruction, turn it into the
1704 // appropriate setlt or setgt instruction. Since the border cases have
1705 // already been handled above, this requires little checking.
1706 //
1707 if (I.getOpcode() == Instruction::SetLE)
Chris Lattner48595f12004-06-10 02:07:29 +00001708 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner45aaafe2004-02-23 05:47:48 +00001709 if (I.getOpcode() == Instruction::SetGE)
Chris Lattner48595f12004-06-10 02:07:29 +00001710 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattner3f5b8772002-05-06 16:14:14 +00001711 }
1712
Chris Lattnerde90b762003-11-03 04:25:02 +00001713 // Test to see if the operands of the setcc are casted versions of other
1714 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00001715 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1716 Value *CastOp0 = CI->getOperand(0);
1717 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00001718 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00001719 (I.getOpcode() == Instruction::SetEQ ||
1720 I.getOpcode() == Instruction::SetNE)) {
1721 // We keep moving the cast from the left operand over to the right
1722 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00001723 Op0 = CastOp0;
Chris Lattnerde90b762003-11-03 04:25:02 +00001724
1725 // If operand #1 is a cast instruction, see if we can eliminate it as
1726 // well.
Chris Lattner68708052003-11-03 05:17:03 +00001727 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1728 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00001729 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00001730 Op1 = CI2->getOperand(0);
Chris Lattnerde90b762003-11-03 04:25:02 +00001731
1732 // If Op1 is a constant, we can fold the cast into the constant.
1733 if (Op1->getType() != Op0->getType())
1734 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1735 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1736 } else {
1737 // Otherwise, cast the RHS right before the setcc
1738 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1739 InsertNewInstBefore(cast<Instruction>(Op1), I);
1740 }
1741 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1742 }
1743
Chris Lattner68708052003-11-03 05:17:03 +00001744 // Handle the special case of: setcc (cast bool to X), <cst>
1745 // This comes up when you have code like
1746 // int X = A < B;
1747 // if (X) ...
1748 // For generality, we handle any zero-extension of any operand comparison
1749 // with a constant.
1750 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1751 const Type *SrcTy = CastOp0->getType();
1752 const Type *DestTy = Op0->getType();
1753 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1754 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1755 // Ok, we have an expansion of operand 0 into a new type. Get the
1756 // constant value, masink off bits which are not set in the RHS. These
1757 // could be set if the destination value is signed.
1758 uint64_t ConstVal = ConstantRHS->getRawValue();
1759 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1760
1761 // If the constant we are comparing it with has high bits set, which
1762 // don't exist in the original value, the values could never be equal,
1763 // because the source would be zero extended.
1764 unsigned SrcBits =
1765 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner1bcc70d2003-11-05 17:31:36 +00001766 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1767 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner68708052003-11-03 05:17:03 +00001768 switch (I.getOpcode()) {
1769 default: assert(0 && "Unknown comparison type!");
1770 case Instruction::SetEQ:
1771 return ReplaceInstUsesWith(I, ConstantBool::False);
1772 case Instruction::SetNE:
1773 return ReplaceInstUsesWith(I, ConstantBool::True);
1774 case Instruction::SetLT:
1775 case Instruction::SetLE:
1776 if (DestTy->isSigned() && HasSignBit)
1777 return ReplaceInstUsesWith(I, ConstantBool::False);
1778 return ReplaceInstUsesWith(I, ConstantBool::True);
1779 case Instruction::SetGT:
1780 case Instruction::SetGE:
1781 if (DestTy->isSigned() && HasSignBit)
1782 return ReplaceInstUsesWith(I, ConstantBool::True);
1783 return ReplaceInstUsesWith(I, ConstantBool::False);
1784 }
1785 }
1786
1787 // Otherwise, we can replace the setcc with a setcc of the smaller
1788 // operand value.
1789 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1790 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1791 }
1792 }
1793 }
Chris Lattner7e708292002-06-25 16:13:24 +00001794 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001795}
1796
1797
1798
Chris Lattnerea340052003-03-10 19:16:08 +00001799Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001800 assert(I.getOperand(1)->getType() == Type::UByteTy);
1801 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00001802 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001803
1804 // shl X, 0 == X and shr X, 0 == X
1805 // shl 0, X == 0 and shr 0, X == 0
1806 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00001807 Op0 == Constant::getNullValue(Op0->getType()))
1808 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001809
Chris Lattnerdf17af12003-08-12 21:53:41 +00001810 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1811 if (!isLeftShift)
1812 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1813 if (CSI->isAllOnesValue())
1814 return ReplaceInstUsesWith(I, CSI);
1815
Chris Lattner2eefe512004-04-09 19:05:30 +00001816 // Try to fold constant and into select arguments.
1817 if (isa<Constant>(Op0))
1818 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1819 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1820 return R;
1821
Chris Lattner3f5b8772002-05-06 16:14:14 +00001822 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001823 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1824 // of a signed value.
1825 //
Chris Lattnerea340052003-03-10 19:16:08 +00001826 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner8adac752004-02-23 20:30:06 +00001827 if (CUI->getValue() >= TypeBits) {
1828 if (!Op0->getType()->isSigned() || isLeftShift)
1829 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1830 else {
1831 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1832 return &I;
1833 }
1834 }
Chris Lattnerf2836082002-09-10 23:04:09 +00001835
Chris Lattnere92d2f42003-08-13 04:18:28 +00001836 // ((X*C1) << C2) == (X * (C1 << C2))
1837 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1838 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1839 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001840 return BinaryOperator::createMul(BO->getOperand(0),
1841 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnere92d2f42003-08-13 04:18:28 +00001842
Chris Lattner2eefe512004-04-09 19:05:30 +00001843 // Try to fold constant and into select arguments.
1844 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1845 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1846 return R;
Chris Lattnere92d2f42003-08-13 04:18:28 +00001847
Chris Lattnerdf17af12003-08-12 21:53:41 +00001848 // If the operand is an bitwise operator with a constant RHS, and the
1849 // shift is the only use, we can pull it out of the shift.
Chris Lattnerfd059242003-10-15 16:48:29 +00001850 if (Op0->hasOneUse())
Chris Lattnerdf17af12003-08-12 21:53:41 +00001851 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1852 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1853 bool isValid = true; // Valid only for And, Or, Xor
1854 bool highBitSet = false; // Transform if high bit of constant set?
1855
1856 switch (Op0BO->getOpcode()) {
1857 default: isValid = false; break; // Do not perform transform!
1858 case Instruction::Or:
1859 case Instruction::Xor:
1860 highBitSet = false;
1861 break;
1862 case Instruction::And:
1863 highBitSet = true;
1864 break;
1865 }
1866
1867 // If this is a signed shift right, and the high bit is modified
1868 // by the logical operation, do not perform the transformation.
1869 // The highBitSet boolean indicates the value of the high bit of
1870 // the constant which would cause it to be modified for this
1871 // operation.
1872 //
1873 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1874 uint64_t Val = Op0C->getRawValue();
1875 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1876 }
1877
1878 if (isValid) {
Chris Lattner7c4049c2004-01-12 19:35:11 +00001879 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdf17af12003-08-12 21:53:41 +00001880
1881 Instruction *NewShift =
1882 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1883 Op0BO->getName());
1884 Op0BO->setName("");
1885 InsertNewInstBefore(NewShift, I);
1886
1887 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1888 NewRHS);
1889 }
1890 }
1891
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001892 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00001893 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00001894 if (ConstantUInt *ShiftAmt1C =
1895 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001896 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1897 unsigned ShiftAmt2 = CUI->getValue();
1898
1899 // Check for (A << c1) << c2 and (A >> c1) >> c2
1900 if (I.getOpcode() == Op0SI->getOpcode()) {
1901 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattner8adac752004-02-23 20:30:06 +00001902 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
1903 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001904 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1905 ConstantUInt::get(Type::UByteTy, Amt));
1906 }
1907
Chris Lattner943c7132003-07-24 18:38:56 +00001908 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1909 // signed types, we can only support the (A >> c1) << c2 configuration,
1910 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00001911 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001912 // Calculate bitmask for what gets shifted off the edge...
1913 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00001914 if (isLeftShift)
Chris Lattner48595f12004-06-10 02:07:29 +00001915 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00001916 else
Chris Lattner48595f12004-06-10 02:07:29 +00001917 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001918
1919 Instruction *Mask =
Chris Lattner48595f12004-06-10 02:07:29 +00001920 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
1921 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001922 InsertNewInstBefore(Mask, I);
1923
1924 // Figure out what flavor of shift we should use...
1925 if (ShiftAmt1 == ShiftAmt2)
1926 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1927 else if (ShiftAmt1 < ShiftAmt2) {
1928 return new ShiftInst(I.getOpcode(), Mask,
1929 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1930 } else {
1931 return new ShiftInst(Op0SI->getOpcode(), Mask,
1932 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1933 }
1934 }
1935 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001936 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00001937
Chris Lattner3f5b8772002-05-06 16:14:14 +00001938 return 0;
1939}
1940
1941
Chris Lattnera1be5662002-05-02 17:06:02 +00001942// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1943// instruction.
1944//
Chris Lattner24c8e382003-07-24 17:35:25 +00001945static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1946 const Type *DstTy) {
Chris Lattnera1be5662002-05-02 17:06:02 +00001947
Chris Lattner8fd217c2002-08-02 20:00:25 +00001948 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1949 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5cf6f112002-08-14 23:21:10 +00001950 // int->float->int would not be allowed)
Misha Brukmanf117cc92003-05-20 18:45:36 +00001951 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00001952 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00001953
1954 // Allow free casting and conversion of sizes as long as the sign doesn't
1955 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00001956 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00001957 unsigned SrcSize = SrcTy->getPrimitiveSize();
1958 unsigned MidSize = MidTy->getPrimitiveSize();
1959 unsigned DstSize = DstTy->getPrimitiveSize();
Chris Lattner8fd217c2002-08-02 20:00:25 +00001960
Chris Lattner3ecce662002-08-15 16:15:25 +00001961 // Cases where we are monotonically decreasing the size of the type are
1962 // always ok, regardless of what sign changes are going on.
1963 //
Chris Lattner5cf6f112002-08-14 23:21:10 +00001964 if (SrcSize >= MidSize && MidSize >= DstSize)
Chris Lattner8fd217c2002-08-02 20:00:25 +00001965 return true;
Chris Lattner3ecce662002-08-15 16:15:25 +00001966
Chris Lattnerd06451f2002-09-23 23:39:43 +00001967 // Cases where the source and destination type are the same, but the middle
1968 // type is bigger are noops.
1969 //
1970 if (SrcSize == DstSize && MidSize > SrcSize)
1971 return true;
1972
Chris Lattner3ecce662002-08-15 16:15:25 +00001973 // If we are monotonically growing, things are more complex.
1974 //
1975 if (SrcSize <= MidSize && MidSize <= DstSize) {
1976 // We have eight combinations of signedness to worry about. Here's the
1977 // table:
1978 static const int SignTable[8] = {
1979 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1980 1, // U U U Always ok
1981 1, // U U S Always ok
1982 3, // U S U Ok iff SrcSize != MidSize
1983 3, // U S S Ok iff SrcSize != MidSize
1984 0, // S U U Never ok
1985 2, // S U S Ok iff MidSize == DstSize
1986 1, // S S U Always ok
1987 1, // S S S Always ok
1988 };
1989
1990 // Choose an action based on the current entry of the signtable that this
1991 // cast of cast refers to...
1992 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1993 switch (SignTable[Row]) {
1994 case 0: return false; // Never ok
1995 case 1: return true; // Always ok
1996 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1997 case 3: // Ok iff SrcSize != MidSize
1998 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1999 default: assert(0 && "Bad entry in sign table!");
2000 }
Chris Lattner3ecce662002-08-15 16:15:25 +00002001 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00002002 }
Chris Lattnera1be5662002-05-02 17:06:02 +00002003
2004 // Otherwise, we cannot succeed. Specifically we do not want to allow things
2005 // like: short -> ushort -> uint, because this can create wrong results if
2006 // the input short is negative!
2007 //
2008 return false;
2009}
2010
Chris Lattner24c8e382003-07-24 17:35:25 +00002011static bool ValueRequiresCast(const Value *V, const Type *Ty) {
2012 if (V->getType() == Ty || isa<Constant>(V)) return false;
2013 if (const CastInst *CI = dyn_cast<CastInst>(V))
2014 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
2015 return false;
2016 return true;
2017}
2018
2019/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2020/// InsertBefore instruction. This is specialized a bit to avoid inserting
2021/// casts that are known to not do anything...
2022///
2023Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2024 Instruction *InsertBefore) {
2025 if (V->getType() == DestTy) return V;
2026 if (Constant *C = dyn_cast<Constant>(V))
2027 return ConstantExpr::getCast(C, DestTy);
2028
2029 CastInst *CI = new CastInst(V, DestTy, V->getName());
2030 InsertNewInstBefore(CI, *InsertBefore);
2031 return CI;
2032}
Chris Lattnera1be5662002-05-02 17:06:02 +00002033
2034// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002035//
Chris Lattner7e708292002-06-25 16:13:24 +00002036Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00002037 Value *Src = CI.getOperand(0);
2038
Chris Lattnera1be5662002-05-02 17:06:02 +00002039 // If the user is casting a value to the same type, eliminate this cast
2040 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00002041 if (CI.getType() == Src->getType())
2042 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00002043
Chris Lattnera1be5662002-05-02 17:06:02 +00002044 // If casting the result of another cast instruction, try to eliminate this
2045 // one!
2046 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002047 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002048 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
2049 CSrc->getType(), CI.getType())) {
Chris Lattnera1be5662002-05-02 17:06:02 +00002050 // This instruction now refers directly to the cast's src operand. This
2051 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00002052 CI.setOperand(0, CSrc->getOperand(0));
2053 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00002054 }
2055
Chris Lattner8fd217c2002-08-02 20:00:25 +00002056 // If this is an A->B->A cast, and we are dealing with integral types, try
2057 // to convert this into a logical 'and' instruction.
2058 //
2059 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00002060 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner8fd217c2002-08-02 20:00:25 +00002061 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2062 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2063 assert(CSrc->getType() != Type::ULongTy &&
2064 "Cannot have type bigger than ulong!");
Chris Lattnerbd4ecf72003-05-26 23:41:32 +00002065 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner8fd217c2002-08-02 20:00:25 +00002066 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattner48595f12004-06-10 02:07:29 +00002067 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner8fd217c2002-08-02 20:00:25 +00002068 }
2069 }
2070
Chris Lattnera710ddc2004-05-25 04:29:21 +00002071 // If this is a cast to bool, turn it into the appropriate setne instruction.
2072 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00002073 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00002074 Constant::getNullValue(CI.getOperand(0)->getType()));
2075
Chris Lattner797249b2003-06-21 23:12:02 +00002076 // If casting the result of a getelementptr instruction with no offset, turn
2077 // this into a cast of the original pointer!
2078 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002079 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00002080 bool AllZeroOperands = true;
2081 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2082 if (!isa<Constant>(GEP->getOperand(i)) ||
2083 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2084 AllZeroOperands = false;
2085 break;
2086 }
2087 if (AllZeroOperands) {
2088 CI.setOperand(0, GEP->getOperand(0));
2089 return &CI;
2090 }
2091 }
2092
Chris Lattnerbc61e662003-11-02 05:57:39 +00002093 // If we are casting a malloc or alloca to a pointer to a type of the same
2094 // size, rewrite the allocation instruction to allocate the "right" type.
2095 //
2096 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerfc07a342003-11-02 06:54:48 +00002097 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerbc61e662003-11-02 05:57:39 +00002098 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2099 // Get the type really allocated and the type casted to...
2100 const Type *AllocElTy = AI->getAllocatedType();
2101 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2102 const Type *CastElTy = PTy->getElementType();
2103 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner1bcc70d2003-11-05 17:31:36 +00002104
Chris Lattnerbc61e662003-11-02 05:57:39 +00002105 // If the allocation is for an even multiple of the cast type size
Chris Lattner8ee92042003-11-03 01:29:41 +00002106 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Chris Lattnerbc61e662003-11-02 05:57:39 +00002107 Value *Amt = ConstantUInt::get(Type::UIntTy,
2108 AllocElTySize/CastElTySize);
2109 std::string Name = AI->getName(); AI->setName("");
2110 AllocationInst *New;
2111 if (isa<MallocInst>(AI))
2112 New = new MallocInst(CastElTy, Amt, Name);
2113 else
2114 New = new AllocaInst(CastElTy, Amt, Name);
Chris Lattnerc1526a92004-04-30 04:37:52 +00002115 InsertNewInstBefore(New, *AI);
Chris Lattnerbc61e662003-11-02 05:57:39 +00002116 return ReplaceInstUsesWith(CI, New);
2117 }
2118 }
2119
Chris Lattner24c8e382003-07-24 17:35:25 +00002120 // If the source value is an instruction with only this use, we can attempt to
2121 // propagate the cast into the instruction. Also, only handle integral types
2122 // for now.
2123 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00002124 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00002125 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2126 const Type *DestTy = CI.getType();
2127 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2128 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2129
2130 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2131 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2132
2133 switch (SrcI->getOpcode()) {
2134 case Instruction::Add:
2135 case Instruction::Mul:
2136 case Instruction::And:
2137 case Instruction::Or:
2138 case Instruction::Xor:
2139 // If we are discarding information, or just changing the sign, rewrite.
2140 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2141 // Don't insert two casts if they cannot be eliminated. We allow two
2142 // casts to be inserted if the sizes are the same. This could only be
2143 // converting signedness, which is a noop.
2144 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
2145 !ValueRequiresCast(Op0, DestTy)) {
2146 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2147 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2148 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2149 ->getOpcode(), Op0c, Op1c);
2150 }
2151 }
2152 break;
2153 case Instruction::Shl:
2154 // Allow changing the sign of the source operand. Do not allow changing
2155 // the size of the shift, UNLESS the shift amount is a constant. We
2156 // mush not change variable sized shifts to a smaller size, because it
2157 // is undefined to shift more bits out than exist in the value.
2158 if (DestBitSize == SrcBitSize ||
2159 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2160 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2161 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2162 }
2163 break;
2164 }
2165 }
2166
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002167 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00002168}
2169
Chris Lattnere576b912004-04-09 23:46:01 +00002170/// GetSelectFoldableOperands - We want to turn code that looks like this:
2171/// %C = or %A, %B
2172/// %D = select %cond, %C, %A
2173/// into:
2174/// %C = select %cond, %B, 0
2175/// %D = or %A, %C
2176///
2177/// Assuming that the specified instruction is an operand to the select, return
2178/// a bitmask indicating which operands of this instruction are foldable if they
2179/// equal the other incoming value of the select.
2180///
2181static unsigned GetSelectFoldableOperands(Instruction *I) {
2182 switch (I->getOpcode()) {
2183 case Instruction::Add:
2184 case Instruction::Mul:
2185 case Instruction::And:
2186 case Instruction::Or:
2187 case Instruction::Xor:
2188 return 3; // Can fold through either operand.
2189 case Instruction::Sub: // Can only fold on the amount subtracted.
2190 case Instruction::Shl: // Can only fold on the shift amount.
2191 case Instruction::Shr:
2192 return 1;
2193 default:
2194 return 0; // Cannot fold
2195 }
2196}
2197
2198/// GetSelectFoldableConstant - For the same transformation as the previous
2199/// function, return the identity constant that goes into the select.
2200static Constant *GetSelectFoldableConstant(Instruction *I) {
2201 switch (I->getOpcode()) {
2202 default: assert(0 && "This cannot happen!"); abort();
2203 case Instruction::Add:
2204 case Instruction::Sub:
2205 case Instruction::Or:
2206 case Instruction::Xor:
2207 return Constant::getNullValue(I->getType());
2208 case Instruction::Shl:
2209 case Instruction::Shr:
2210 return Constant::getNullValue(Type::UByteTy);
2211 case Instruction::And:
2212 return ConstantInt::getAllOnesValue(I->getType());
2213 case Instruction::Mul:
2214 return ConstantInt::get(I->getType(), 1);
2215 }
2216}
2217
Chris Lattner3d69f462004-03-12 05:52:32 +00002218Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002219 Value *CondVal = SI.getCondition();
2220 Value *TrueVal = SI.getTrueValue();
2221 Value *FalseVal = SI.getFalseValue();
2222
2223 // select true, X, Y -> X
2224 // select false, X, Y -> Y
2225 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00002226 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002227 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00002228 else {
2229 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002230 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00002231 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002232
2233 // select C, X, X -> X
2234 if (TrueVal == FalseVal)
2235 return ReplaceInstUsesWith(SI, TrueVal);
2236
Chris Lattner0c199a72004-04-08 04:43:23 +00002237 if (SI.getType() == Type::BoolTy)
2238 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2239 if (C == ConstantBool::True) {
2240 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00002241 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002242 } else {
2243 // Change: A = select B, false, C --> A = and !B, C
2244 Value *NotCond =
2245 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2246 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00002247 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002248 }
2249 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2250 if (C == ConstantBool::False) {
2251 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00002252 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002253 } else {
2254 // Change: A = select B, C, true --> A = or !B, C
2255 Value *NotCond =
2256 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2257 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00002258 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002259 }
2260 }
2261
Chris Lattner2eefe512004-04-09 19:05:30 +00002262 // Selecting between two integer constants?
2263 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2264 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2265 // select C, 1, 0 -> cast C to int
2266 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2267 return new CastInst(CondVal, SI.getType());
2268 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2269 // select C, 0, 1 -> cast !C to int
2270 Value *NotCond =
2271 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00002272 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00002273 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00002274 }
Chris Lattner457dd822004-06-09 07:59:58 +00002275
2276 // If one of the constants is zero (we know they can't both be) and we
2277 // have a setcc instruction with zero, and we have an 'and' with the
2278 // non-constant value, eliminate this whole mess. This corresponds to
2279 // cases like this: ((X & 27) ? 27 : 0)
2280 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2281 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2282 if ((IC->getOpcode() == Instruction::SetEQ ||
2283 IC->getOpcode() == Instruction::SetNE) &&
2284 isa<ConstantInt>(IC->getOperand(1)) &&
2285 cast<Constant>(IC->getOperand(1))->isNullValue())
2286 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2287 if (ICA->getOpcode() == Instruction::And &&
2288 isa<ConstantInt>(ICA->getOperand(1)) &&
2289 (ICA->getOperand(1) == TrueValC ||
2290 ICA->getOperand(1) == FalseValC) &&
2291 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2292 // Okay, now we know that everything is set up, we just don't
2293 // know whether we have a setne or seteq and whether the true or
2294 // false val is the zero.
2295 bool ShouldNotVal = !TrueValC->isNullValue();
2296 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2297 Value *V = ICA;
2298 if (ShouldNotVal)
2299 V = InsertNewInstBefore(BinaryOperator::create(
2300 Instruction::Xor, V, ICA->getOperand(1)), SI);
2301 return ReplaceInstUsesWith(SI, V);
2302 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002303 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00002304
2305 // See if we are selecting two values based on a comparison of the two values.
2306 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2307 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2308 // Transform (X == Y) ? X : Y -> Y
2309 if (SCI->getOpcode() == Instruction::SetEQ)
2310 return ReplaceInstUsesWith(SI, FalseVal);
2311 // Transform (X != Y) ? X : Y -> X
2312 if (SCI->getOpcode() == Instruction::SetNE)
2313 return ReplaceInstUsesWith(SI, TrueVal);
2314 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2315
2316 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2317 // Transform (X == Y) ? Y : X -> X
2318 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00002319 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00002320 // Transform (X != Y) ? Y : X -> Y
2321 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00002322 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00002323 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2324 }
2325 }
Chris Lattner0c199a72004-04-08 04:43:23 +00002326
Chris Lattnere576b912004-04-09 23:46:01 +00002327 // See if we can fold the select into one of our operands.
2328 if (SI.getType()->isInteger()) {
2329 // See the comment above GetSelectFoldableOperands for a description of the
2330 // transformation we are doing here.
2331 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2332 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2333 !isa<Constant>(FalseVal))
2334 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2335 unsigned OpToFold = 0;
2336 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2337 OpToFold = 1;
2338 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2339 OpToFold = 2;
2340 }
2341
2342 if (OpToFold) {
2343 Constant *C = GetSelectFoldableConstant(TVI);
2344 std::string Name = TVI->getName(); TVI->setName("");
2345 Instruction *NewSel =
2346 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2347 Name);
2348 InsertNewInstBefore(NewSel, SI);
2349 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2350 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2351 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2352 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2353 else {
2354 assert(0 && "Unknown instruction!!");
2355 }
2356 }
2357 }
2358
2359 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2360 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2361 !isa<Constant>(TrueVal))
2362 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2363 unsigned OpToFold = 0;
2364 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2365 OpToFold = 1;
2366 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2367 OpToFold = 2;
2368 }
2369
2370 if (OpToFold) {
2371 Constant *C = GetSelectFoldableConstant(FVI);
2372 std::string Name = FVI->getName(); FVI->setName("");
2373 Instruction *NewSel =
2374 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2375 Name);
2376 InsertNewInstBefore(NewSel, SI);
2377 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2378 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2379 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2380 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2381 else {
2382 assert(0 && "Unknown instruction!!");
2383 }
2384 }
2385 }
2386 }
Chris Lattner3d69f462004-03-12 05:52:32 +00002387 return 0;
2388}
2389
2390
Chris Lattner9fe38862003-06-19 17:00:31 +00002391// CallInst simplification
2392//
2393Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +00002394 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2395 // visitCallSite.
2396 if (Function *F = CI.getCalledFunction())
2397 switch (F->getIntrinsicID()) {
2398 case Intrinsic::memmove:
2399 case Intrinsic::memcpy:
2400 case Intrinsic::memset:
2401 // memmove/cpy/set of zero bytes is a noop.
2402 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2403 if (NumBytes->isNullValue())
2404 return EraseInstFromFunction(CI);
2405 }
2406 break;
2407 default:
2408 break;
2409 }
2410
Chris Lattnera44d8a22003-10-07 22:32:43 +00002411 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00002412}
2413
2414// InvokeInst simplification
2415//
2416Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00002417 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00002418}
2419
Chris Lattnera44d8a22003-10-07 22:32:43 +00002420// visitCallSite - Improvements for call and invoke instructions.
2421//
2422Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00002423 bool Changed = false;
2424
2425 // If the callee is a constexpr cast of a function, attempt to move the cast
2426 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00002427 if (transformConstExprCastCall(CS)) return 0;
2428
Chris Lattner6c266db2003-10-07 22:54:13 +00002429 Value *Callee = CS.getCalledValue();
2430 const PointerType *PTy = cast<PointerType>(Callee->getType());
2431 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2432 if (FTy->isVarArg()) {
2433 // See if we can optimize any arguments passed through the varargs area of
2434 // the call.
2435 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2436 E = CS.arg_end(); I != E; ++I)
2437 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2438 // If this cast does not effect the value passed through the varargs
2439 // area, we can eliminate the use of the cast.
2440 Value *Op = CI->getOperand(0);
2441 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2442 *I = Op;
2443 Changed = true;
2444 }
2445 }
2446 }
Chris Lattnera44d8a22003-10-07 22:32:43 +00002447
Chris Lattner6c266db2003-10-07 22:54:13 +00002448 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00002449}
2450
Chris Lattner9fe38862003-06-19 17:00:31 +00002451// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2452// attempt to move the cast to the arguments of the call/invoke.
2453//
2454bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2455 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2456 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
2457 if (CE->getOpcode() != Instruction::Cast ||
2458 !isa<ConstantPointerRef>(CE->getOperand(0)))
2459 return false;
2460 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
2461 if (!isa<Function>(CPR->getValue())) return false;
2462 Function *Callee = cast<Function>(CPR->getValue());
2463 Instruction *Caller = CS.getInstruction();
2464
2465 // Okay, this is a cast from a function to a different type. Unless doing so
2466 // would cause a type conversion of one of our arguments, change this call to
2467 // be a direct call with arguments casted to the appropriate types.
2468 //
2469 const FunctionType *FT = Callee->getFunctionType();
2470 const Type *OldRetTy = Caller->getType();
2471
Chris Lattnerf78616b2004-01-14 06:06:08 +00002472 // Check to see if we are changing the return type...
2473 if (OldRetTy != FT->getReturnType()) {
2474 if (Callee->isExternal() &&
2475 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2476 !Caller->use_empty())
2477 return false; // Cannot transform this return value...
2478
2479 // If the callsite is an invoke instruction, and the return value is used by
2480 // a PHI node in a successor, we cannot change the return type of the call
2481 // because there is no place to put the cast instruction (without breaking
2482 // the critical edge). Bail out in this case.
2483 if (!Caller->use_empty())
2484 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2485 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2486 UI != E; ++UI)
2487 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2488 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00002489 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00002490 return false;
2491 }
Chris Lattner9fe38862003-06-19 17:00:31 +00002492
2493 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2494 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2495
2496 CallSite::arg_iterator AI = CS.arg_begin();
2497 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2498 const Type *ParamTy = FT->getParamType(i);
2499 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2500 if (Callee->isExternal() && !isConvertible) return false;
2501 }
2502
2503 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2504 Callee->isExternal())
2505 return false; // Do not delete arguments unless we have a function body...
2506
2507 // Okay, we decided that this is a safe thing to do: go ahead and start
2508 // inserting cast instructions as necessary...
2509 std::vector<Value*> Args;
2510 Args.reserve(NumActualArgs);
2511
2512 AI = CS.arg_begin();
2513 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2514 const Type *ParamTy = FT->getParamType(i);
2515 if ((*AI)->getType() == ParamTy) {
2516 Args.push_back(*AI);
2517 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00002518 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2519 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00002520 }
2521 }
2522
2523 // If the function takes more arguments than the call was taking, add them
2524 // now...
2525 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2526 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2527
2528 // If we are removing arguments to the function, emit an obnoxious warning...
2529 if (FT->getNumParams() < NumActualArgs)
2530 if (!FT->isVarArg()) {
2531 std::cerr << "WARNING: While resolving call to function '"
2532 << Callee->getName() << "' arguments were dropped!\n";
2533 } else {
2534 // Add all of the arguments in their promoted form to the arg list...
2535 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2536 const Type *PTy = getPromotedType((*AI)->getType());
2537 if (PTy != (*AI)->getType()) {
2538 // Must promote to pass through va_arg area!
2539 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2540 InsertNewInstBefore(Cast, *Caller);
2541 Args.push_back(Cast);
2542 } else {
2543 Args.push_back(*AI);
2544 }
2545 }
2546 }
2547
2548 if (FT->getReturnType() == Type::VoidTy)
2549 Caller->setName(""); // Void type should not have a name...
2550
2551 Instruction *NC;
2552 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00002553 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00002554 Args, Caller->getName(), Caller);
2555 } else {
2556 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2557 }
2558
2559 // Insert a cast of the return type as necessary...
2560 Value *NV = NC;
2561 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2562 if (NV->getType() != Type::VoidTy) {
2563 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00002564
2565 // If this is an invoke instruction, we should insert it after the first
2566 // non-phi, instruction in the normal successor block.
2567 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2568 BasicBlock::iterator I = II->getNormalDest()->begin();
2569 while (isa<PHINode>(I)) ++I;
2570 InsertNewInstBefore(NC, *I);
2571 } else {
2572 // Otherwise, it's a call, just insert cast right after the call instr
2573 InsertNewInstBefore(NC, *Caller);
2574 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00002575 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00002576 } else {
2577 NV = Constant::getNullValue(Caller->getType());
2578 }
2579 }
2580
2581 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2582 Caller->replaceAllUsesWith(NV);
2583 Caller->getParent()->getInstList().erase(Caller);
2584 removeFromWorkList(Caller);
2585 return true;
2586}
2587
2588
Chris Lattnera1be5662002-05-02 17:06:02 +00002589
Chris Lattner473945d2002-05-06 18:06:38 +00002590// PHINode simplification
2591//
Chris Lattner7e708292002-06-25 16:13:24 +00002592Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner60921c92003-12-19 05:58:40 +00002593 if (Value *V = hasConstantValue(&PN))
2594 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00002595
2596 // If the only user of this instruction is a cast instruction, and all of the
2597 // incoming values are constants, change this PHI to merge together the casted
2598 // constants.
2599 if (PN.hasOneUse())
2600 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2601 if (CI->getType() != PN.getType()) { // noop casts will be folded
2602 bool AllConstant = true;
2603 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2604 if (!isa<Constant>(PN.getIncomingValue(i))) {
2605 AllConstant = false;
2606 break;
2607 }
2608 if (AllConstant) {
2609 // Make a new PHI with all casted values.
2610 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2611 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2612 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2613 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2614 PN.getIncomingBlock(i));
2615 }
2616
2617 // Update the cast instruction.
2618 CI->setOperand(0, New);
2619 WorkList.push_back(CI); // revisit the cast instruction to fold.
2620 WorkList.push_back(New); // Make sure to revisit the new Phi
2621 return &PN; // PN is now dead!
2622 }
2623 }
Chris Lattner60921c92003-12-19 05:58:40 +00002624 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00002625}
2626
Chris Lattner28977af2004-04-05 01:30:19 +00002627static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
2628 Instruction *InsertPoint,
2629 InstCombiner *IC) {
2630 unsigned PS = IC->getTargetData().getPointerSize();
2631 const Type *VTy = V->getType();
2632 Instruction *Cast;
2633 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
2634 // We must insert a cast to ensure we sign-extend.
2635 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
2636 V->getName()), *InsertPoint);
2637 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
2638 *InsertPoint);
2639}
2640
Chris Lattnera1be5662002-05-02 17:06:02 +00002641
Chris Lattner7e708292002-06-25 16:13:24 +00002642Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00002643 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00002644 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00002645 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002646 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00002647 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002648
2649 bool HasZeroPointerIndex = false;
2650 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2651 HasZeroPointerIndex = C->isNullValue();
2652
2653 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00002654 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00002655
Chris Lattner28977af2004-04-05 01:30:19 +00002656 // Eliminate unneeded casts for indices.
2657 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002658 gep_type_iterator GTI = gep_type_begin(GEP);
2659 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
2660 if (isa<SequentialType>(*GTI)) {
2661 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
2662 Value *Src = CI->getOperand(0);
2663 const Type *SrcTy = Src->getType();
2664 const Type *DestTy = CI->getType();
2665 if (Src->getType()->isInteger()) {
2666 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
2667 // We can always eliminate a cast from ulong or long to the other.
2668 // We can always eliminate a cast from uint to int or the other on
2669 // 32-bit pointer platforms.
2670 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
2671 MadeChange = true;
2672 GEP.setOperand(i, Src);
2673 }
2674 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2675 SrcTy->getPrimitiveSize() == 4) {
2676 // We can always eliminate a cast from int to [u]long. We can
2677 // eliminate a cast from uint to [u]long iff the target is a 32-bit
2678 // pointer target.
2679 if (SrcTy->isSigned() ||
2680 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
2681 MadeChange = true;
2682 GEP.setOperand(i, Src);
2683 }
Chris Lattner28977af2004-04-05 01:30:19 +00002684 }
2685 }
2686 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002687 // If we are using a wider index than needed for this platform, shrink it
2688 // to what we need. If the incoming value needs a cast instruction,
2689 // insert it. This explicit cast can make subsequent optimizations more
2690 // obvious.
2691 Value *Op = GEP.getOperand(i);
2692 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00002693 if (Constant *C = dyn_cast<Constant>(Op)) {
2694 GEP.setOperand(i, ConstantExpr::getCast(C, TD->getIntPtrType()));
2695 MadeChange = true;
2696 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002697 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
2698 Op->getName()), GEP);
2699 GEP.setOperand(i, Op);
2700 MadeChange = true;
2701 }
Chris Lattner28977af2004-04-05 01:30:19 +00002702 }
2703 if (MadeChange) return &GEP;
2704
Chris Lattner90ac28c2002-08-02 19:29:35 +00002705 // Combine Indices - If the source pointer to this getelementptr instruction
2706 // is a getelementptr instruction, combine the indices of the two
2707 // getelementptr instructions into a single instruction.
2708 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00002709 std::vector<Value*> SrcGEPOperands;
Chris Lattner620ce142004-05-07 22:09:22 +00002710 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00002711 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner620ce142004-05-07 22:09:22 +00002712 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00002713 if (CE->getOpcode() == Instruction::GetElementPtr)
2714 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
2715 }
2716
2717 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00002718 // Note that if our source is a gep chain itself that we wait for that
2719 // chain to be resolved before we perform this transformation. This
2720 // avoids us creating a TON of code in some cases.
2721 //
2722 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
2723 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
2724 return 0; // Wait until our source is folded to completion.
2725
Chris Lattner90ac28c2002-08-02 19:29:35 +00002726 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00002727
2728 // Find out whether the last index in the source GEP is a sequential idx.
2729 bool EndsWithSequential = false;
2730 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
2731 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00002732 EndsWithSequential = !isa<StructType>(*I);
Chris Lattner8a2a3112001-12-14 16:52:21 +00002733
Chris Lattner90ac28c2002-08-02 19:29:35 +00002734 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00002735 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00002736 // Replace: gep (gep %P, long B), long A, ...
2737 // With: T = long A+B; gep %P, T, ...
2738 //
Chris Lattner620ce142004-05-07 22:09:22 +00002739 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00002740 if (SO1 == Constant::getNullValue(SO1->getType())) {
2741 Sum = GO1;
2742 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2743 Sum = SO1;
2744 } else {
2745 // If they aren't the same type, convert both to an integer of the
2746 // target's pointer size.
2747 if (SO1->getType() != GO1->getType()) {
2748 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
2749 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
2750 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
2751 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
2752 } else {
2753 unsigned PS = TD->getPointerSize();
2754 Instruction *Cast;
2755 if (SO1->getType()->getPrimitiveSize() == PS) {
2756 // Convert GO1 to SO1's type.
2757 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
2758
2759 } else if (GO1->getType()->getPrimitiveSize() == PS) {
2760 // Convert SO1 to GO1's type.
2761 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
2762 } else {
2763 const Type *PT = TD->getIntPtrType();
2764 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
2765 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
2766 }
2767 }
2768 }
Chris Lattner620ce142004-05-07 22:09:22 +00002769 if (isa<Constant>(SO1) && isa<Constant>(GO1))
2770 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
2771 else {
Chris Lattner48595f12004-06-10 02:07:29 +00002772 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
2773 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00002774 }
Chris Lattner28977af2004-04-05 01:30:19 +00002775 }
Chris Lattner620ce142004-05-07 22:09:22 +00002776
2777 // Recycle the GEP we already have if possible.
2778 if (SrcGEPOperands.size() == 2) {
2779 GEP.setOperand(0, SrcGEPOperands[0]);
2780 GEP.setOperand(1, Sum);
2781 return &GEP;
2782 } else {
2783 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2784 SrcGEPOperands.end()-1);
2785 Indices.push_back(Sum);
2786 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
2787 }
Chris Lattner28977af2004-04-05 01:30:19 +00002788 } else if (isa<Constant>(*GEP.idx_begin()) &&
2789 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerebd985c2004-03-25 22:59:29 +00002790 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00002791 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00002792 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2793 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00002794 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
2795 }
2796
2797 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00002798 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00002799
Chris Lattner620ce142004-05-07 22:09:22 +00002800 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00002801 // GEP of global variable. If all of the indices for this GEP are
2802 // constants, we can promote this to a constexpr instead of an instruction.
2803
2804 // Scan for nonconstants...
2805 std::vector<Constant*> Indices;
2806 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2807 for (; I != E && isa<Constant>(*I); ++I)
2808 Indices.push_back(cast<Constant>(*I));
2809
2810 if (I == E) { // If they are all constants...
Chris Lattnerfb242b62003-04-16 22:40:51 +00002811 Constant *CE =
Chris Lattner9b761232002-08-17 22:21:59 +00002812 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
2813
2814 // Replace all uses of the GEP with the new constexpr...
2815 return ReplaceInstUsesWith(GEP, CE);
2816 }
Chris Lattner620ce142004-05-07 22:09:22 +00002817 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002818 if (CE->getOpcode() == Instruction::Cast) {
2819 if (HasZeroPointerIndex) {
2820 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2821 // into : GEP [10 x ubyte]* X, long 0, ...
2822 //
2823 // This occurs when the program declares an array extern like "int X[];"
2824 //
2825 Constant *X = CE->getOperand(0);
2826 const PointerType *CPTy = cast<PointerType>(CE->getType());
2827 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2828 if (const ArrayType *XATy =
2829 dyn_cast<ArrayType>(XTy->getElementType()))
2830 if (const ArrayType *CATy =
2831 dyn_cast<ArrayType>(CPTy->getElementType()))
2832 if (CATy->getElementType() == XATy->getElementType()) {
2833 // At this point, we know that the cast source type is a pointer
2834 // to an array of the same type as the destination pointer
2835 // array. Because the array type is never stepped over (there
2836 // is a leading zero) we can fold the cast into this GEP.
2837 GEP.setOperand(0, X);
2838 return &GEP;
2839 }
2840 }
2841 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00002842 }
2843
Chris Lattner8a2a3112001-12-14 16:52:21 +00002844 return 0;
2845}
2846
Chris Lattner0864acf2002-11-04 16:18:53 +00002847Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2848 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
2849 if (AI.isArrayAllocation()) // Check C != 1
2850 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
2851 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00002852 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00002853
2854 // Create and insert the replacement instruction...
2855 if (isa<MallocInst>(AI))
Chris Lattner7c881df2004-03-19 06:08:10 +00002856 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00002857 else {
2858 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner7c881df2004-03-19 06:08:10 +00002859 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00002860 }
Chris Lattner7c881df2004-03-19 06:08:10 +00002861
2862 InsertNewInstBefore(New, AI);
Chris Lattner0864acf2002-11-04 16:18:53 +00002863
2864 // Scan to the end of the allocation instructions, to skip over a block of
2865 // allocas if possible...
2866 //
2867 BasicBlock::iterator It = New;
2868 while (isa<AllocationInst>(*It)) ++It;
2869
2870 // Now that I is pointing to the first non-allocation-inst in the block,
2871 // insert our getelementptr instruction...
2872 //
Chris Lattner28977af2004-04-05 01:30:19 +00002873 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner0864acf2002-11-04 16:18:53 +00002874 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
2875
2876 // Now make everything use the getelementptr instead of the original
2877 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00002878 return ReplaceInstUsesWith(AI, V);
Chris Lattner0864acf2002-11-04 16:18:53 +00002879 }
Chris Lattner7c881df2004-03-19 06:08:10 +00002880
2881 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
2882 // Note that we only do this for alloca's, because malloc should allocate and
2883 // return a unique pointer, even for a zero byte allocation.
Chris Lattnercf27afb2004-07-02 22:55:47 +00002884 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
2885 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00002886 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
2887
Chris Lattner0864acf2002-11-04 16:18:53 +00002888 return 0;
2889}
2890
Chris Lattner67b1e1b2003-12-07 01:24:23 +00002891Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
2892 Value *Op = FI.getOperand(0);
2893
2894 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
2895 if (CastInst *CI = dyn_cast<CastInst>(Op))
2896 if (isa<PointerType>(CI->getOperand(0)->getType())) {
2897 FI.setOperand(0, CI->getOperand(0));
2898 return &FI;
2899 }
2900
Chris Lattner6160e852004-02-28 04:57:37 +00002901 // If we have 'free null' delete the instruction. This can happen in stl code
2902 // when lots of inlining happens.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00002903 if (isa<ConstantPointerNull>(Op))
2904 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00002905
Chris Lattner67b1e1b2003-12-07 01:24:23 +00002906 return 0;
2907}
2908
2909
Chris Lattner833b8a42003-06-26 05:06:25 +00002910/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
2911/// constantexpr, return the constant value being addressed by the constant
2912/// expression, or null if something is funny.
2913///
2914static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner28977af2004-04-05 01:30:19 +00002915 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner833b8a42003-06-26 05:06:25 +00002916 return 0; // Do not allow stepping over the value!
2917
2918 // Loop over all of the operands, tracking down which value we are
2919 // addressing...
Chris Lattnere1368ae2004-05-27 17:30:27 +00002920 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
2921 for (++I; I != E; ++I)
2922 if (const StructType *STy = dyn_cast<StructType>(*I)) {
2923 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
2924 assert(CU->getValue() < STy->getNumElements() &&
2925 "Struct index out of range!");
2926 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
2927 C = cast<Constant>(CS->getValues()[CU->getValue()]);
2928 } else if (isa<ConstantAggregateZero>(C)) {
2929 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
2930 } else {
2931 return 0;
2932 }
2933 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
2934 const ArrayType *ATy = cast<ArrayType>(*I);
2935 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
2936 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
2937 C = cast<Constant>(CA->getValues()[CI->getRawValue()]);
2938 else if (isa<ConstantAggregateZero>(C))
2939 C = Constant::getNullValue(ATy->getElementType());
2940 else
2941 return 0;
2942 } else {
Chris Lattner833b8a42003-06-26 05:06:25 +00002943 return 0;
Chris Lattnere1368ae2004-05-27 17:30:27 +00002944 }
Chris Lattner833b8a42003-06-26 05:06:25 +00002945 return C;
2946}
2947
2948Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
2949 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00002950 if (LI.isVolatile()) return 0;
2951
Chris Lattnerd9955aa2004-04-14 03:28:36 +00002952 if (Constant *C = dyn_cast<Constant>(Op))
2953 if (C->isNullValue()) // load null -> 0
2954 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
2955 else if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(C))
2956 Op = CPR->getValue();
Chris Lattner833b8a42003-06-26 05:06:25 +00002957
2958 // Instcombine load (constant global) into the value loaded...
2959 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002960 if (GV->isConstant() && !GV->isExternal())
Chris Lattner833b8a42003-06-26 05:06:25 +00002961 return ReplaceInstUsesWith(LI, GV->getInitializer());
2962
2963 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
2964 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
2965 if (CE->getOpcode() == Instruction::GetElementPtr)
2966 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
2967 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002968 if (GV->isConstant() && !GV->isExternal())
Chris Lattner833b8a42003-06-26 05:06:25 +00002969 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
2970 return ReplaceInstUsesWith(LI, V);
Chris Lattnerf499eac2004-04-08 20:39:49 +00002971
2972 // load (cast X) --> cast (load X) iff safe
2973 if (CastInst *CI = dyn_cast<CastInst>(Op)) {
2974 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
2975 if (const PointerType *SrcTy =
2976 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
2977 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattner546516c2004-05-07 15:35:56 +00002978 if (SrcPTy->isSized() && DestPTy->isSized() &&
2979 TD->getTypeSize(SrcPTy) == TD->getTypeSize(DestPTy) &&
Chris Lattnerf499eac2004-04-08 20:39:49 +00002980 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
2981 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
2982 // Okay, we are casting from one integer or pointer type to another of
2983 // the same size. Instead of casting the pointer before the load, cast
2984 // the result of the loaded value.
2985 Value *NewLoad = InsertNewInstBefore(new LoadInst(CI->getOperand(0),
2986 CI->getName()), LI);
2987 // Now cast the result of the load.
2988 return new CastInst(NewLoad, LI.getType());
2989 }
2990 }
2991 }
2992
Chris Lattner833b8a42003-06-26 05:06:25 +00002993 return 0;
2994}
2995
2996
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00002997Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
2998 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnera0ebceb2004-02-27 06:27:46 +00002999 if (BI.isConditional() && !isa<Constant>(BI.getCondition())) {
Chris Lattner40f5d702003-06-04 05:10:11 +00003000 if (Value *V = dyn_castNotVal(BI.getCondition())) {
3001 BasicBlock *TrueDest = BI.getSuccessor(0);
3002 BasicBlock *FalseDest = BI.getSuccessor(1);
3003 // Swap Destinations and condition...
3004 BI.setCondition(V);
3005 BI.setSuccessor(0, FalseDest);
3006 BI.setSuccessor(1, TrueDest);
3007 return &BI;
Chris Lattnera0ebceb2004-02-27 06:27:46 +00003008 } else if (SetCondInst *I = dyn_cast<SetCondInst>(BI.getCondition())) {
3009 // Cannonicalize setne -> seteq
3010 if ((I->getOpcode() == Instruction::SetNE ||
3011 I->getOpcode() == Instruction::SetLE ||
3012 I->getOpcode() == Instruction::SetGE) && I->hasOneUse()) {
3013 std::string Name = I->getName(); I->setName("");
3014 Instruction::BinaryOps NewOpcode =
3015 SetCondInst::getInverseCondition(I->getOpcode());
3016 Value *NewSCC = BinaryOperator::create(NewOpcode, I->getOperand(0),
3017 I->getOperand(1), Name, I);
3018 BasicBlock *TrueDest = BI.getSuccessor(0);
3019 BasicBlock *FalseDest = BI.getSuccessor(1);
3020 // Swap Destinations and condition...
3021 BI.setCondition(NewSCC);
3022 BI.setSuccessor(0, FalseDest);
3023 BI.setSuccessor(1, TrueDest);
3024 removeFromWorkList(I);
3025 I->getParent()->getInstList().erase(I);
3026 WorkList.push_back(cast<Instruction>(NewSCC));
3027 return &BI;
3028 }
Chris Lattner40f5d702003-06-04 05:10:11 +00003029 }
Chris Lattnera0ebceb2004-02-27 06:27:46 +00003030 }
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003031 return 0;
3032}
Chris Lattner0864acf2002-11-04 16:18:53 +00003033
Chris Lattner46238a62004-07-03 00:26:11 +00003034Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3035 Value *Cond = SI.getCondition();
3036 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3037 if (I->getOpcode() == Instruction::Add)
3038 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3039 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3040 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3041 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3042 AddRHS));
3043 SI.setOperand(0, I->getOperand(0));
3044 WorkList.push_back(I);
3045 return &SI;
3046 }
3047 }
3048 return 0;
3049}
3050
Chris Lattner8a2a3112001-12-14 16:52:21 +00003051
Chris Lattner62b14df2002-09-02 04:59:56 +00003052void InstCombiner::removeFromWorkList(Instruction *I) {
3053 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3054 WorkList.end());
3055}
3056
Chris Lattner7e708292002-06-25 16:13:24 +00003057bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003058 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00003059 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00003060
Chris Lattner216d4d82004-05-01 23:19:52 +00003061 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3062 WorkList.push_back(&*i);
Chris Lattner6ffe5512004-04-27 15:13:33 +00003063
Chris Lattner8a2a3112001-12-14 16:52:21 +00003064
3065 while (!WorkList.empty()) {
3066 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3067 WorkList.pop_back();
3068
Misha Brukmana3bbcb52002-10-29 23:06:16 +00003069 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00003070 // Check to see if we can DIE the instruction...
3071 if (isInstructionTriviallyDead(I)) {
3072 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00003073 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003074 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00003075 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00003076
3077 I->getParent()->getInstList().erase(I);
3078 removeFromWorkList(I);
3079 continue;
3080 }
Chris Lattner62b14df2002-09-02 04:59:56 +00003081
Misha Brukmana3bbcb52002-10-29 23:06:16 +00003082 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00003083 if (Constant *C = ConstantFoldInstruction(I)) {
3084 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003085 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00003086 ReplaceInstUsesWith(*I, C);
3087
Chris Lattner62b14df2002-09-02 04:59:56 +00003088 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00003089 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00003090 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003091 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00003092 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00003093
Chris Lattnerebd985c2004-03-25 22:59:29 +00003094 // Check to see if any of the operands of this instruction are a
3095 // ConstantPointerRef. Since they sneak in all over the place and inhibit
3096 // optimization, we want to strip them out unconditionally!
3097 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3098 if (ConstantPointerRef *CPR =
3099 dyn_cast<ConstantPointerRef>(I->getOperand(i))) {
3100 I->setOperand(i, CPR->getValue());
3101 Changed = true;
3102 }
3103
Chris Lattner8a2a3112001-12-14 16:52:21 +00003104 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00003105 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00003106 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003107 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003108 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00003109 DEBUG(std::cerr << "IC: Old = " << *I
3110 << " New = " << *Result);
3111
Chris Lattnerf523d062004-06-09 05:08:07 +00003112 // Everything uses the new instruction now.
3113 I->replaceAllUsesWith(Result);
3114
3115 // Push the new instruction and any users onto the worklist.
3116 WorkList.push_back(Result);
3117 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003118
3119 // Move the name to the new instruction first...
3120 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00003121 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003122
3123 // Insert the new instruction into the basic block...
3124 BasicBlock *InstParent = I->getParent();
3125 InstParent->getInstList().insert(I, Result);
3126
Chris Lattner00d51312004-05-01 23:27:23 +00003127 // Make sure that we reprocess all operands now that we reduced their
3128 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00003129 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3130 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3131 WorkList.push_back(OpI);
3132
Chris Lattnerf523d062004-06-09 05:08:07 +00003133 // Instructions can end up on the worklist more than once. Make sure
3134 // we do not process an instruction that has been deleted.
3135 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003136
3137 // Erase the old instruction.
3138 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003139 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00003140 DEBUG(std::cerr << "IC: MOD = " << *I);
3141
Chris Lattner90ac28c2002-08-02 19:29:35 +00003142 // If the instruction was modified, it's possible that it is now dead.
3143 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00003144 if (isInstructionTriviallyDead(I)) {
3145 // Make sure we process all operands now that we are reducing their
3146 // use counts.
3147 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3148 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3149 WorkList.push_back(OpI);
3150
3151 // Instructions may end up in the worklist more than once. Erase all
3152 // occurrances of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00003153 removeFromWorkList(I);
Chris Lattner00d51312004-05-01 23:27:23 +00003154 I->getParent()->getInstList().erase(I);
Chris Lattnerf523d062004-06-09 05:08:07 +00003155 } else {
3156 WorkList.push_back(Result);
3157 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00003158 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003159 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003160 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00003161 }
3162 }
3163
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003164 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003165}
3166
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003167Pass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003168 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003169}
Brian Gaeked0fde302003-11-11 22:41:34 +00003170