blob: 1e0e77dde7fa63b70ecebeef1b1157c2760216ab [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 Lattneracd1f0f2004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000057
Chris Lattnerdd841ae2002-04-18 17:39:14 +000058namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
Chris Lattnerf57b8452002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000068
Chris Lattner7bcc0e72004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner7bcc0e72004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner62b14df2002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000090 public:
Chris Lattner7e708292002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000092
Chris Lattner97e52e42002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000096 }
97
Chris Lattner28977af2004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner7e708292002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000116 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000117 Instruction *visitCastInst(CastInst &CI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000118 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000123 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000124 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000125 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000126 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000127 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000128
129 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000130 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000131
Chris Lattner9fe38862003-06-19 17:00:31 +0000132 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000133 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000134 bool transformConstExprCastCall(CallSite CS);
135
Chris Lattner28977af2004-04-05 01:30:19 +0000136 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
139 //
Chris Lattner4cb170c2004-02-23 06:38:22 +0000140 Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000146 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000147 }
148
Chris Lattner0c967662004-09-24 15:21:34 +0000149 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150 /// This also adds the cast to the worklist. Finally, this returns the
151 /// cast.
152 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153 if (V->getType() == Ty) return V;
154
155 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156 WorkList.push_back(C);
157 return C;
158 }
159
Chris Lattner8b170942002-08-09 23:47:40 +0000160 // ReplaceInstUsesWith - This method is to be used when an instruction is
161 // found to be dead, replacable with another preexisting expression. Here
162 // we add all uses of I to the worklist, replace all uses of I with the new
163 // value, then return I, so that the inst combiner will know that I was
164 // modified.
165 //
166 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000167 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000168 if (&I != V) {
169 I.replaceAllUsesWith(V);
170 return &I;
171 } else {
172 // If we are replacing the instruction with itself, this must be in a
173 // segment of unreachable code, so just clobber the instruction.
174 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
175 return &I;
176 }
Chris Lattner8b170942002-08-09 23:47:40 +0000177 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000178
179 // EraseInstFromFunction - When dealing with an instruction that has side
180 // effects or produces a void value, we can't rely on DCE to delete the
181 // instruction. Instead, visit methods should return the value returned by
182 // this function.
183 Instruction *EraseInstFromFunction(Instruction &I) {
184 assert(I.use_empty() && "Cannot erase instruction that is used!");
185 AddUsesToWorkList(I);
186 removeFromWorkList(&I);
187 I.getParent()->getInstList().erase(&I);
188 return 0; // Don't do anything with FI
189 }
190
191
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000192 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000193 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194 /// InsertBefore instruction. This is specialized a bit to avoid inserting
195 /// casts that are known to not do anything...
196 ///
197 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198 Instruction *InsertBefore);
199
Chris Lattnerc8802d22003-03-11 00:12:48 +0000200 // SimplifyCommutative - This performs a few simplifications for commutative
201 // operators...
202 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000203
204 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
205 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000206 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000207
Chris Lattnera6275cc2002-07-26 21:12:46 +0000208 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000209}
210
Chris Lattner4f98c562003-03-10 21:43:22 +0000211// getComplexity: Assign a complexity or rank value to LLVM Values...
212// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
213static unsigned getComplexity(Value *V) {
214 if (isa<Instruction>(V)) {
215 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
216 return 2;
217 return 3;
218 }
219 if (isa<Argument>(V)) return 2;
220 return isa<Constant>(V) ? 0 : 1;
221}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000222
Chris Lattnerc8802d22003-03-11 00:12:48 +0000223// isOnlyUse - Return true if this instruction will be deleted if we stop using
224// it.
225static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000226 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000227}
228
Chris Lattner4cb170c2004-02-23 06:38:22 +0000229// getPromotedType - Return the specified type promoted as it would be to pass
230// though a va_arg area...
231static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000232 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000233 case Type::SByteTyID:
234 case Type::ShortTyID: return Type::IntTy;
235 case Type::UByteTyID:
236 case Type::UShortTyID: return Type::UIntTy;
237 case Type::FloatTyID: return Type::DoubleTy;
238 default: return Ty;
239 }
240}
241
Chris Lattner4f98c562003-03-10 21:43:22 +0000242// SimplifyCommutative - This performs a few simplifications for commutative
243// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000244//
Chris Lattner4f98c562003-03-10 21:43:22 +0000245// 1. Order operands such that they are listed from right (least complex) to
246// left (most complex). This puts constants before unary operators before
247// binary operators.
248//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000249// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
250// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000251//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000252bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000253 bool Changed = false;
254 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
255 Changed = !I.swapOperands();
256
257 if (!I.isAssociative()) return Changed;
258 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000259 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
260 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
261 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000262 Constant *Folded = ConstantExpr::get(I.getOpcode(),
263 cast<Constant>(I.getOperand(1)),
264 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000265 I.setOperand(0, Op->getOperand(0));
266 I.setOperand(1, Folded);
267 return true;
268 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
269 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
270 isOnlyUse(Op) && isOnlyUse(Op1)) {
271 Constant *C1 = cast<Constant>(Op->getOperand(1));
272 Constant *C2 = cast<Constant>(Op1->getOperand(1));
273
274 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000275 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000276 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
277 Op1->getOperand(0),
278 Op1->getName(), &I);
279 WorkList.push_back(New);
280 I.setOperand(0, New);
281 I.setOperand(1, Folded);
282 return true;
283 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000284 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000285 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000286}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000287
Chris Lattner8d969642003-03-10 23:06:50 +0000288// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
289// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000290//
Chris Lattner8d969642003-03-10 23:06:50 +0000291static inline Value *dyn_castNegVal(Value *V) {
292 if (BinaryOperator::isNeg(V))
293 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
294
Chris Lattnerfe32e0c2003-04-30 22:19:10 +0000295 // Constants can be considered to be negated values if they can be folded...
296 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000297 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000298 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000299}
300
Chris Lattner8d969642003-03-10 23:06:50 +0000301static inline Value *dyn_castNotVal(Value *V) {
302 if (BinaryOperator::isNot(V))
303 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
304
305 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000306 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000307 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000308 return 0;
309}
310
Chris Lattnerc8802d22003-03-11 00:12:48 +0000311// dyn_castFoldableMul - If this value is a multiply that can be folded into
312// other computations (because it has a constant operand), return the
313// non-constant operand of the multiply.
314//
315static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000316 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattnerc8802d22003-03-11 00:12:48 +0000317 if (Instruction *I = dyn_cast<Instruction>(V))
318 if (I->getOpcode() == Instruction::Mul)
319 if (isa<Constant>(I->getOperand(1)))
320 return I->getOperand(0);
321 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000322}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000323
Chris Lattnera2881962003-02-18 19:28:33 +0000324// Log2 - Calculate the log base 2 for the specified value if it is exactly a
325// power of 2.
326static unsigned Log2(uint64_t Val) {
327 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
328 unsigned Count = 0;
329 while (Val != 1) {
330 if (Val & 1) return 0; // Multiple bits set?
331 Val >>= 1;
332 ++Count;
333 }
334 return Count;
Chris 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 {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000436 ConstantInt *C1;
437 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
438 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000439 }
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
Robert Bocchino71698282004-07-27 21:02:21 +0000512 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000513 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino71698282004-07-27 21:02:21 +0000514 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000515
Chris Lattner5c4afb92002-05-08 22:46:53 +0000516 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000517 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000518 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000519
520 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000521 if (!isa<Constant>(RHS))
522 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000523 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000524
Chris Lattnerad3448c2003-02-18 19:57:07 +0000525 // X*C + X --> X * (C+1)
526 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000527 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000528 ConstantExpr::getAdd(
Chris Lattner2a9c8472003-05-27 16:40:51 +0000529 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
530 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +0000531 return BinaryOperator::createMul(RHS, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000532 }
533
534 // X + X*C --> X * (C+1)
535 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000536 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000537 ConstantExpr::getAdd(
Chris Lattner2a9c8472003-05-27 16:40:51 +0000538 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
539 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +0000540 return BinaryOperator::createMul(LHS, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000541 }
542
Chris Lattner564a7272003-08-13 19:01:45 +0000543 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000544 ConstantInt *C2;
545 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000546 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000547
Chris Lattner6b032052003-10-02 15:11:26 +0000548 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000549 Value *X;
550 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
551 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
552 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000553 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000554
555 // Try to fold constant add into select arguments.
556 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
557 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
558 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000559 }
560
Chris Lattner7e708292002-06-25 16:13:24 +0000561 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000562}
563
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000564// isSignBit - Return true if the value represented by the constant only has the
565// highest order bit set.
566static bool isSignBit(ConstantInt *CI) {
567 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
568 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
569}
570
Chris Lattner24c8e382003-07-24 17:35:25 +0000571static unsigned getTypeSizeInBits(const Type *Ty) {
572 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
573}
574
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000575/// RemoveNoopCast - Strip off nonconverting casts from the value.
576///
577static Value *RemoveNoopCast(Value *V) {
578 if (CastInst *CI = dyn_cast<CastInst>(V)) {
579 const Type *CTy = CI->getType();
580 const Type *OpTy = CI->getOperand(0)->getType();
581 if (CTy->isInteger() && OpTy->isInteger()) {
582 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
583 return RemoveNoopCast(CI->getOperand(0));
584 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
585 return RemoveNoopCast(CI->getOperand(0));
586 }
587 return V;
588}
589
Chris Lattner7e708292002-06-25 16:13:24 +0000590Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000591 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000592
Chris Lattner233f7dc2002-08-12 21:17:25 +0000593 if (Op0 == Op1) // sub X, X -> 0
594 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000595
Chris Lattner233f7dc2002-08-12 21:17:25 +0000596 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000597 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000598 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000599
Chris Lattnerd65460f2003-11-05 01:06:05 +0000600 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
601 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000602 if (C->isAllOnesValue())
603 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000604
Chris Lattnerd65460f2003-11-05 01:06:05 +0000605 // C - ~X == X + (1+C)
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000606 Value *X;
607 if (match(Op1, m_Not(m_Value(X))))
608 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +0000609 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000610 // -((uint)X >> 31) -> ((int)X >> 31)
611 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000612 if (C->isNullValue()) {
613 Value *NoopCastedRHS = RemoveNoopCast(Op1);
614 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +0000615 if (SI->getOpcode() == Instruction::Shr)
616 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
617 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000618 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000619 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000620 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000621 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000622 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000623 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner9c290672004-03-12 23:53:13 +0000624 // Ok, the transformation is safe. Insert a cast of the incoming
625 // value, then the new shift, then the new cast.
626 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
627 SI->getOperand(0)->getName());
628 Value *InV = InsertNewInstBefore(FirstCast, I);
629 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
630 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000631 if (NewShift->getType() == I.getType())
632 return NewShift;
633 else {
634 InV = InsertNewInstBefore(NewShift, I);
635 return new CastInst(NewShift, I.getType());
636 }
Chris Lattner9c290672004-03-12 23:53:13 +0000637 }
638 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000639 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000640
641 // Try to fold constant sub into select arguments.
642 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
643 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
644 return R;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000645 }
646
Chris Lattnera2881962003-02-18 19:28:33 +0000647 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerfd059242003-10-15 16:48:29 +0000648 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000649 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
650 // is not used by anyone else...
651 //
Chris Lattner0517e722004-02-02 20:09:56 +0000652 if (Op1I->getOpcode() == Instruction::Sub &&
653 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000654 // Swap the two operands of the subexpr...
655 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
656 Op1I->setOperand(0, IIOp1);
657 Op1I->setOperand(1, IIOp0);
658
659 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +0000660 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000661 }
662
663 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
664 //
665 if (Op1I->getOpcode() == Instruction::And &&
666 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
667 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
668
Chris Lattnerf523d062004-06-09 05:08:07 +0000669 Value *NewNot =
670 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000671 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000672 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000673
674 // X - X*C --> X * (1-C)
675 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000676 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000677 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000678 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000679 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattner48595f12004-06-10 02:07:29 +0000680 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000681 }
Chris Lattner40371712002-05-09 01:29:19 +0000682 }
Chris Lattnera2881962003-02-18 19:28:33 +0000683
Chris Lattnerad3448c2003-02-18 19:57:07 +0000684 // X*C - X --> X * (C-1)
685 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000686 Constant *CP1 =
Chris Lattner48595f12004-06-10 02:07:29 +0000687 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000688 ConstantInt::get(I.getType(), 1));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000689 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattner48595f12004-06-10 02:07:29 +0000690 return BinaryOperator::createMul(Op1, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000691 }
692
Chris Lattner3f5b8772002-05-06 16:14:14 +0000693 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000694}
695
Chris Lattner4cb170c2004-02-23 06:38:22 +0000696/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
697/// really just returns true if the most significant (sign) bit is set.
698static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
699 if (RHS->getType()->isSigned()) {
700 // True if source is LHS < 0 or LHS <= -1
701 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
702 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
703 } else {
704 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
705 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
706 // the size of the integer type.
707 if (Opcode == Instruction::SetGE)
708 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
709 if (Opcode == Instruction::SetGT)
710 return RHSC->getValue() ==
711 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
712 }
713 return false;
714}
715
Chris Lattner7e708292002-06-25 16:13:24 +0000716Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000717 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +0000718 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000719
Chris Lattner233f7dc2002-08-12 21:17:25 +0000720 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +0000721 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
722 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +0000723
724 // ((X << C1)*C2) == (X * (C2 << C1))
725 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
726 if (SI->getOpcode() == Instruction::Shl)
727 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000728 return BinaryOperator::createMul(SI->getOperand(0),
729 ConstantExpr::getShl(CI, ShOp));
Chris Lattner7c4049c2004-01-12 19:35:11 +0000730
Chris Lattner515c97c2003-09-11 22:24:54 +0000731 if (CI->isNullValue())
732 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
733 if (CI->equalsInt(1)) // X * 1 == X
734 return ReplaceInstUsesWith(I, Op0);
735 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +0000736 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +0000737
Chris Lattner515c97c2003-09-11 22:24:54 +0000738 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnera2881962003-02-18 19:28:33 +0000739 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
740 return new ShiftInst(Instruction::Shl, Op0,
741 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino71698282004-07-27 21:02:21 +0000742 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +0000743 if (Op1F->isNullValue())
744 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +0000745
Chris Lattnera2881962003-02-18 19:28:33 +0000746 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
747 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
748 if (Op1F->getValue() == 1.0)
749 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
750 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000751
752 // Try to fold constant mul into select arguments.
753 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
754 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
755 return R;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000756 }
757
Chris Lattnera4f445b2003-03-10 23:23:04 +0000758 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
759 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000760 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +0000761
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000762 // If one of the operands of the multiply is a cast from a boolean value, then
763 // we know the bool is either zero or one, so this is a 'masking' multiply.
764 // See if we can simplify things based on how the boolean was originally
765 // formed.
766 CastInst *BoolCast = 0;
767 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
768 if (CI->getOperand(0)->getType() == Type::BoolTy)
769 BoolCast = CI;
770 if (!BoolCast)
771 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
772 if (CI->getOperand(0)->getType() == Type::BoolTy)
773 BoolCast = CI;
774 if (BoolCast) {
775 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
776 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
777 const Type *SCOpTy = SCIOp0->getType();
778
Chris Lattner4cb170c2004-02-23 06:38:22 +0000779 // If the setcc is true iff the sign bit of X is set, then convert this
780 // multiply into a shift/and combination.
781 if (isa<ConstantInt>(SCIOp1) &&
782 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000783 // Shift the X value right to turn it into "all signbits".
784 Constant *Amt = ConstantUInt::get(Type::UByteTy,
785 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000786 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000787 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +0000788 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
789 SCIOp0->getName()), I);
790 }
791
792 Value *V =
793 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
794 BoolCast->getOperand(0)->getName()+
795 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000796
797 // If the multiply type is not the same as the source type, sign extend
798 // or truncate to the multiply type.
799 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +0000800 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000801
802 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +0000803 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +0000804 }
805 }
806 }
807
Chris Lattner7e708292002-06-25 16:13:24 +0000808 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000809}
810
Chris Lattner7e708292002-06-25 16:13:24 +0000811Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnera2881962003-02-18 19:28:33 +0000812 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000813 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +0000814 if (RHS->equalsInt(1))
815 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattnera2881962003-02-18 19:28:33 +0000816
Chris Lattner83a2e6e2004-04-26 14:01:59 +0000817 // div X, -1 == -X
818 if (RHS->isAllOnesValue())
819 return BinaryOperator::createNeg(I.getOperand(0));
820
Chris Lattnera2881962003-02-18 19:28:33 +0000821 // Check to see if this is an unsigned division with an exact power of 2,
822 // if so, convert to a right shift.
823 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
824 if (uint64_t Val = C->getValue()) // Don't break X / 0
825 if (uint64_t C = Log2(Val))
826 return new ShiftInst(Instruction::Shr, I.getOperand(0),
827 ConstantUInt::get(Type::UByteTy, C));
828 }
829
830 // 0 / X == 0, we don't need to preserve faults!
831 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
832 if (LHS->equalsInt(0))
833 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
834
Chris Lattner3f5b8772002-05-06 16:14:14 +0000835 return 0;
836}
837
838
Chris Lattner7e708292002-06-25 16:13:24 +0000839Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000840 if (I.getType()->isSigned())
841 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner1e3564e2004-07-06 07:11:42 +0000842 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +0000843 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +0000844 // X % -Y -> X % Y
845 AddUsesToWorkList(I);
846 I.setOperand(1, RHSNeg);
847 return &I;
848 }
849
Chris Lattnera2881962003-02-18 19:28:33 +0000850 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
851 if (RHS->equalsInt(1)) // X % 1 == 0
852 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
853
854 // Check to see if this is an unsigned remainder with an exact power of 2,
855 // if so, convert to a bitwise and.
856 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
857 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +0000858 if (!(Val & (Val-1))) // Power of 2
Chris Lattner48595f12004-06-10 02:07:29 +0000859 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattnera2881962003-02-18 19:28:33 +0000860 ConstantUInt::get(I.getType(), Val-1));
861 }
862
863 // 0 % X == 0, we don't need to preserve faults!
864 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
865 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +0000866 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
867
Chris Lattner3f5b8772002-05-06 16:14:14 +0000868 return 0;
869}
870
Chris Lattner8b170942002-08-09 23:47:40 +0000871// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000872static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000873 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
874 // Calculate -1 casted to the right type...
875 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
876 uint64_t Val = ~0ULL; // All ones
877 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
878 return CU->getValue() == Val-1;
879 }
880
881 const ConstantSInt *CS = cast<ConstantSInt>(C);
882
883 // Calculate 0111111111..11111
884 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
885 int64_t Val = INT64_MAX; // All ones
886 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
887 return CS->getValue() == Val-1;
888}
889
890// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +0000891static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +0000892 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
893 return CU->getValue() == 1;
894
895 const ConstantSInt *CS = cast<ConstantSInt>(C);
896
897 // Calculate 1111111111000000000000
898 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
899 int64_t Val = -1; // All ones
900 Val <<= TypeBits-1; // Shift over to the right spot
901 return CS->getValue() == Val+1;
902}
903
Chris Lattner457dd822004-06-09 07:59:58 +0000904// isOneBitSet - Return true if there is exactly one bit set in the specified
905// constant.
906static bool isOneBitSet(const ConstantInt *CI) {
907 uint64_t V = CI->getRawValue();
908 return V && (V & (V-1)) == 0;
909}
910
Chris Lattnerb20ba0a2004-09-23 21:46:38 +0000911#if 0 // Currently unused
912// isLowOnes - Return true if the constant is of the form 0+1+.
913static bool isLowOnes(const ConstantInt *CI) {
914 uint64_t V = CI->getRawValue();
915
916 // There won't be bits set in parts that the type doesn't contain.
917 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
918
919 uint64_t U = V+1; // If it is low ones, this should be a power of two.
920 return U && V && (U & V) == 0;
921}
922#endif
923
924// isHighOnes - Return true if the constant is of the form 1+0+.
925// This is the same as lowones(~X).
926static bool isHighOnes(const ConstantInt *CI) {
927 uint64_t V = ~CI->getRawValue();
928
929 // There won't be bits set in parts that the type doesn't contain.
930 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
931
932 uint64_t U = V+1; // If it is low ones, this should be a power of two.
933 return U && V && (U & V) == 0;
934}
935
936
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000937/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
938/// are carefully arranged to allow folding of expressions such as:
939///
940/// (A < B) | (A > B) --> (A != B)
941///
942/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
943/// represents that the comparison is true if A == B, and bit value '1' is true
944/// if A < B.
945///
946static unsigned getSetCondCode(const SetCondInst *SCI) {
947 switch (SCI->getOpcode()) {
948 // False -> 0
949 case Instruction::SetGT: return 1;
950 case Instruction::SetEQ: return 2;
951 case Instruction::SetGE: return 3;
952 case Instruction::SetLT: return 4;
953 case Instruction::SetNE: return 5;
954 case Instruction::SetLE: return 6;
955 // True -> 7
956 default:
957 assert(0 && "Invalid SetCC opcode!");
958 return 0;
959 }
960}
961
962/// getSetCCValue - This is the complement of getSetCondCode, which turns an
963/// opcode and two operands into either a constant true or false, or a brand new
964/// SetCC instruction.
965static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
966 switch (Opcode) {
967 case 0: return ConstantBool::False;
968 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
969 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
970 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
971 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
972 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
973 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
974 case 7: return ConstantBool::True;
975 default: assert(0 && "Illegal SetCCCode!"); return 0;
976 }
977}
978
979// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
980struct FoldSetCCLogical {
981 InstCombiner &IC;
982 Value *LHS, *RHS;
983 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
984 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
985 bool shouldApply(Value *V) const {
986 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
987 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
988 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
989 return false;
990 }
991 Instruction *apply(BinaryOperator &Log) const {
992 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
993 if (SCI->getOperand(0) != LHS) {
994 assert(SCI->getOperand(1) == LHS);
995 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
996 }
997
998 unsigned LHSCode = getSetCondCode(SCI);
999 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1000 unsigned Code;
1001 switch (Log.getOpcode()) {
1002 case Instruction::And: Code = LHSCode & RHSCode; break;
1003 case Instruction::Or: Code = LHSCode | RHSCode; break;
1004 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00001005 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001006 }
1007
1008 Value *RV = getSetCCValue(Code, LHS, RHS);
1009 if (Instruction *I = dyn_cast<Instruction>(RV))
1010 return I;
1011 // Otherwise, it's a constant boolean value...
1012 return IC.ReplaceInstUsesWith(Log, RV);
1013 }
1014};
1015
1016
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001017// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1018// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1019// guaranteed to be either a shift instruction or a binary operator.
1020Instruction *InstCombiner::OptAndOp(Instruction *Op,
1021 ConstantIntegral *OpRHS,
1022 ConstantIntegral *AndRHS,
1023 BinaryOperator &TheAnd) {
1024 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001025 Constant *Together = 0;
1026 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001027 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001028
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001029 switch (Op->getOpcode()) {
1030 case Instruction::Xor:
Chris Lattner7c4049c2004-01-12 19:35:11 +00001031 if (Together->isNullValue()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001032 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001033 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001034 } else if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001035 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1036 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001037 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001038 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001039 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001040 }
1041 break;
1042 case Instruction::Or:
1043 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattner7c4049c2004-01-12 19:35:11 +00001044 if (Together->isNullValue())
Chris Lattner48595f12004-06-10 02:07:29 +00001045 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001046 else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001047 if (Together == AndRHS) // (X | C) & C --> C
1048 return ReplaceInstUsesWith(TheAnd, AndRHS);
1049
Chris Lattnerfd059242003-10-15 16:48:29 +00001050 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001051 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1052 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001053 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001054 InsertNewInstBefore(Or, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001055 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001056 }
1057 }
1058 break;
1059 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001060 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001061 // Adding a one to a single bit bit-field should be turned into an XOR
1062 // of the bit. First thing to check is to see if this AND is with a
1063 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001064 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001065
1066 // Clear bits that are not part of the constant.
1067 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1068
1069 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001070 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001071 // Ok, at this point, we know that we are masking the result of the
1072 // ADD down to exactly one bit. If the constant we are adding has
1073 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001074 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001075
1076 // Check to see if any bits below the one bit set in AndRHSV are set.
1077 if ((AddRHS & (AndRHSV-1)) == 0) {
1078 // If not, the only thing that can effect the output of the AND is
1079 // the bit specified by AndRHSV. If that bit is set, the effect of
1080 // the XOR is to toggle the bit. If it is clear, then the ADD has
1081 // no effect.
1082 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1083 TheAnd.setOperand(0, X);
1084 return &TheAnd;
1085 } else {
1086 std::string Name = Op->getName(); Op->setName("");
1087 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001088 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001089 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001090 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001091 }
1092 }
1093 }
1094 }
1095 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001096
1097 case Instruction::Shl: {
1098 // We know that the AND will not produce any of the bits shifted in, so if
1099 // the anded constant includes them, clear them now!
1100 //
1101 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001102 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1103 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1104
1105 if (CI == ShlMask) { // Masking out bits that the shift already masks
1106 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1107 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001108 TheAnd.setOperand(1, CI);
1109 return &TheAnd;
1110 }
1111 break;
1112 }
1113 case Instruction::Shr:
1114 // We know that the AND will not produce any of the bits shifted in, so if
1115 // the anded constant includes them, clear them now! This only applies to
1116 // unsigned shifts, because a signed shr may bring in set bits!
1117 //
1118 if (AndRHS->getType()->isUnsigned()) {
1119 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001120 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1121 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1122
1123 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1124 return ReplaceInstUsesWith(TheAnd, Op);
1125 } else if (CI != AndRHS) {
1126 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00001127 return &TheAnd;
1128 }
Chris Lattner0c967662004-09-24 15:21:34 +00001129 } else { // Signed shr.
1130 // See if this is shifting in some sign extension, then masking it out
1131 // with an and.
1132 if (Op->hasOneUse()) {
1133 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1134 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1135 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1136 if (CI == ShrMask) { // Masking out bits shifted in.
1137 // Make the argument unsigned.
1138 Value *ShVal = Op->getOperand(0);
1139 ShVal = InsertCastBefore(ShVal,
1140 ShVal->getType()->getUnsignedVersion(),
1141 TheAnd);
1142 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1143 OpRHS, Op->getName()),
1144 TheAnd);
1145 return new CastInst(ShVal, Op->getType());
1146 }
1147 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001148 }
1149 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001150 }
1151 return 0;
1152}
1153
Chris Lattner8b170942002-08-09 23:47:40 +00001154
Chris Lattner7e708292002-06-25 16:13:24 +00001155Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001156 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001157 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001158
1159 // and X, X = X and X, 0 == 0
Chris Lattner233f7dc2002-08-12 21:17:25 +00001160 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1161 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001162
1163 // and X, -1 == X
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001164 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001165 if (RHS->isAllOnesValue())
1166 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001167
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001168 // Optimize a variety of ((val OP C1) & C2) combinations...
1169 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1170 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner06782f82003-07-23 19:36:21 +00001171 Value *X = Op0I->getOperand(0);
Chris Lattner58403262003-07-23 19:25:52 +00001172 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001173 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1174 return Res;
Chris Lattner06782f82003-07-23 19:36:21 +00001175 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001176
1177 // Try to fold constant and into select arguments.
1178 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1179 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1180 return R;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001181 }
1182
Chris Lattner8d969642003-03-10 23:06:50 +00001183 Value *Op0NotVal = dyn_castNotVal(Op0);
1184 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001185
Chris Lattner5b62aa72004-06-18 06:07:51 +00001186 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1187 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1188
Misha Brukmancb6267b2004-07-30 12:50:08 +00001189 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001190 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001191 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1192 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001193 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001194 return BinaryOperator::createNot(Or);
1195 }
1196
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001197 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1198 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1199 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1200 return R;
1201
Chris Lattner7e708292002-06-25 16:13:24 +00001202 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001203}
1204
1205
1206
Chris Lattner7e708292002-06-25 16:13:24 +00001207Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001208 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001210
1211 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001212 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1213 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001214
1215 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001216 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner233f7dc2002-08-12 21:17:25 +00001217 if (RHS->isAllOnesValue())
1218 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001219
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001220 ConstantInt *C1; Value *X;
1221 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1222 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1223 std::string Op0Name = Op0->getName(); Op0->setName("");
1224 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1225 InsertNewInstBefore(Or, I);
1226 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1227 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001228
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001229 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1230 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1231 std::string Op0Name = Op0->getName(); Op0->setName("");
1232 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1233 InsertNewInstBefore(Or, I);
1234 return BinaryOperator::createXor(Or,
1235 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001236 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001237
1238 // Try to fold constant and into select arguments.
1239 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1240 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1241 return R;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00001242 }
1243
Chris Lattner67ca7682003-08-12 19:11:07 +00001244 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001245 Value *A, *B; ConstantInt *C1, *C2;
1246 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1247 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1248 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner67ca7682003-08-12 19:11:07 +00001249
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001250 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1251 if (A == Op1) // ~A | A == -1
1252 return ReplaceInstUsesWith(I,
1253 ConstantIntegral::getAllOnesValue(I.getType()));
1254 } else {
1255 A = 0;
1256 }
Chris Lattnera2881962003-02-18 19:28:33 +00001257
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001258 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1259 if (Op0 == B)
1260 return ReplaceInstUsesWith(I,
1261 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00001262
Misha Brukmancb6267b2004-07-30 12:50:08 +00001263 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001264 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1265 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1266 I.getName()+".demorgan"), I);
1267 return BinaryOperator::createNot(And);
1268 }
Chris Lattnera27231a2003-03-10 23:13:59 +00001269 }
Chris Lattnera2881962003-02-18 19:28:33 +00001270
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001271 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1272 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1273 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1274 return R;
1275
Chris Lattner7e708292002-06-25 16:13:24 +00001276 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001277}
1278
Chris Lattnerc317d392004-02-16 01:20:27 +00001279// XorSelf - Implements: X ^ X --> 0
1280struct XorSelf {
1281 Value *RHS;
1282 XorSelf(Value *rhs) : RHS(rhs) {}
1283 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1284 Instruction *apply(BinaryOperator &Xor) const {
1285 return &Xor;
1286 }
1287};
Chris Lattner3f5b8772002-05-06 16:14:14 +00001288
1289
Chris Lattner7e708292002-06-25 16:13:24 +00001290Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001291 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001292 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001293
Chris Lattnerc317d392004-02-16 01:20:27 +00001294 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1295 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1296 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00001297 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00001298 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001299
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001300 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00001301 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001302 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001303 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00001304
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001305 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00001306 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001307 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00001308 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00001309 return new SetCondInst(SCI->getInverseCondition(),
1310 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001311
Chris Lattnerd65460f2003-11-05 01:06:05 +00001312 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00001313 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1314 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00001315 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1316 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001317 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00001318 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001319 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00001320
1321 // ~(~X & Y) --> (X | ~Y)
1322 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1323 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1324 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1325 Instruction *NotY =
1326 BinaryOperator::createNot(Op0I->getOperand(1),
1327 Op0I->getOperand(1)->getName()+".not");
1328 InsertNewInstBefore(NotY, I);
1329 return BinaryOperator::createOr(Op0NotVal, NotY);
1330 }
1331 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001332
1333 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001334 switch (Op0I->getOpcode()) {
1335 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00001336 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00001337 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00001338 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1339 return BinaryOperator::createSub(
1340 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00001341 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00001342 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00001343 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001344 break;
1345 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001346 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00001347 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1348 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001349 break;
1350 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001351 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00001352 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00001353 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00001354 break;
1355 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00001356 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00001357 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001358
1359 // Try to fold constant and into select arguments.
1360 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1361 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1362 return R;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001363 }
1364
Chris Lattner8d969642003-03-10 23:06:50 +00001365 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001366 if (X == Op1)
1367 return ReplaceInstUsesWith(I,
1368 ConstantIntegral::getAllOnesValue(I.getType()));
1369
Chris Lattner8d969642003-03-10 23:06:50 +00001370 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00001371 if (X == Op0)
1372 return ReplaceInstUsesWith(I,
1373 ConstantIntegral::getAllOnesValue(I.getType()));
1374
Chris Lattnercb40a372003-03-10 18:24:17 +00001375 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00001376 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001377 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1378 cast<BinaryOperator>(Op1I)->swapOperands();
1379 I.swapOperands();
1380 std::swap(Op0, Op1);
1381 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1382 I.swapOperands();
1383 std::swap(Op0, Op1);
Chris Lattner26ca7e12004-02-16 03:54:20 +00001384 }
1385 } else if (Op1I->getOpcode() == Instruction::Xor) {
1386 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1387 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1388 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1389 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1390 }
Chris Lattnercb40a372003-03-10 18:24:17 +00001391
1392 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00001393 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00001394 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1395 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00001396 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00001397 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1398 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001399 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00001400 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00001401 } else if (Op0I->getOpcode() == Instruction::Xor) {
1402 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1403 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1404 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1405 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00001406 }
1407
Chris Lattner14840892004-08-01 19:42:59 +00001408 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001409 Value *A, *B; ConstantInt *C1, *C2;
1410 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1411 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00001412 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001413 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00001414
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001415 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1416 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1417 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1418 return R;
1419
Chris Lattner7e708292002-06-25 16:13:24 +00001420 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001421}
1422
Chris Lattner8b170942002-08-09 23:47:40 +00001423// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1424static Constant *AddOne(ConstantInt *C) {
Chris Lattner48595f12004-06-10 02:07:29 +00001425 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner8b170942002-08-09 23:47:40 +00001426}
1427static Constant *SubOne(ConstantInt *C) {
Chris Lattner48595f12004-06-10 02:07:29 +00001428 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner8b170942002-08-09 23:47:40 +00001429}
1430
Chris Lattner53a5b572002-05-09 20:11:54 +00001431// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1432// true when both operands are equal...
1433//
Chris Lattner7e708292002-06-25 16:13:24 +00001434static bool isTrueWhenEqual(Instruction &I) {
1435 return I.getOpcode() == Instruction::SetEQ ||
1436 I.getOpcode() == Instruction::SetGE ||
1437 I.getOpcode() == Instruction::SetLE;
Chris Lattner53a5b572002-05-09 20:11:54 +00001438}
1439
Chris Lattner7e708292002-06-25 16:13:24 +00001440Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001441 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00001442 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1443 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00001444
1445 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00001446 if (Op0 == Op1)
1447 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00001448
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001449 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1450 if (isa<ConstantPointerNull>(Op1) &&
1451 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner8b170942002-08-09 23:47:40 +00001452 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1453
Chris Lattner3ccd17e2003-08-13 05:38:46 +00001454
Chris Lattner8b170942002-08-09 23:47:40 +00001455 // setcc's with boolean values can always be turned into bitwise operations
1456 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00001457 switch (I.getOpcode()) {
1458 default: assert(0 && "Invalid setcc instruction!");
1459 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00001460 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00001461 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00001462 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00001463 }
Chris Lattner5dbef222004-08-11 00:50:51 +00001464 case Instruction::SetNE:
1465 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001466
Chris Lattner5dbef222004-08-11 00:50:51 +00001467 case Instruction::SetGT:
1468 std::swap(Op0, Op1); // Change setgt -> setlt
1469 // FALL THROUGH
1470 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1471 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1472 InsertNewInstBefore(Not, I);
1473 return BinaryOperator::createAnd(Not, Op1);
1474 }
1475 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00001476 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00001477 // FALL THROUGH
1478 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1479 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1480 InsertNewInstBefore(Not, I);
1481 return BinaryOperator::createOr(Not, Op1);
1482 }
1483 }
Chris Lattner8b170942002-08-09 23:47:40 +00001484 }
1485
Chris Lattner2be51ae2004-06-09 04:24:29 +00001486 // See if we are doing a comparison between a constant and an instruction that
1487 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00001488 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3c6a0d42004-05-25 06:32:08 +00001489 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00001490 switch (LHSI->getOpcode()) {
1491 case Instruction::And:
1492 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1493 LHSI->getOperand(0)->hasOneUse()) {
1494 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1495 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1496 // happens a LOT in code produced by the C front-end, for bitfield
1497 // access.
1498 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1499 ConstantUInt *ShAmt;
1500 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1501 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1502 const Type *Ty = LHSI->getType();
1503
1504 // We can fold this as long as we can't shift unknown bits
1505 // into the mask. This can only happen with signed shift
1506 // rights, as they sign-extend.
1507 if (ShAmt) {
1508 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1509 Shift->getType()->isUnsigned();
1510 if (!CanFold) {
1511 // To test for the bad case of the signed shr, see if any
1512 // of the bits shifted in could be tested after the mask.
1513 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerf0cacc02004-07-21 20:14:10 +00001514 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00001515 Constant *ShVal =
1516 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1517 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1518 CanFold = true;
1519 }
1520
1521 if (CanFold) {
1522 unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
1523 ? Instruction::Shr : Instruction::Shl;
1524 Constant *NewCst = ConstantExpr::get(ShiftOp, CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00001525
Chris Lattner648e3bc2004-09-23 21:52:49 +00001526 // Check to see if we are shifting out any of the bits being
1527 // compared.
1528 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1529 // If we shifted bits out, the fold is not going to work out.
1530 // As a special case, check to see if this means that the
1531 // result is always true or false now.
1532 if (I.getOpcode() == Instruction::SetEQ)
1533 return ReplaceInstUsesWith(I, ConstantBool::False);
1534 if (I.getOpcode() == Instruction::SetNE)
1535 return ReplaceInstUsesWith(I, ConstantBool::True);
1536 } else {
1537 I.setOperand(1, NewCst);
1538 LHSI->setOperand(1, ConstantExpr::get(ShiftOp, AndCST,ShAmt));
1539 LHSI->setOperand(0, Shift->getOperand(0));
1540 WorkList.push_back(Shift); // Shift is dead.
1541 AddUsesToWorkList(I);
1542 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00001543 }
1544 }
Chris Lattner457dd822004-06-09 07:59:58 +00001545 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00001546 }
1547 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00001548
1549 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00001550 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
1551 unsigned ShAmtVal = ShAmt->getValue();
1552
1553 switch (I.getOpcode()) {
1554 default: break;
1555 case Instruction::SetEQ:
1556 case Instruction::SetNE: {
1557 // If we are comparing against bits always shifted out, the
1558 // comparison cannot succeed.
1559 Constant *Comp =
1560 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
1561
1562 if (Comp != CI) {// Comparing against a bit that we know is zero.
1563 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
1564 Constant *Cst = ConstantBool::get(IsSetNE);
1565 return ReplaceInstUsesWith(I, Cst);
1566 }
1567
1568 if (LHSI->hasOneUse() || CI->isNullValue()) {
1569 // Otherwise strength reduce the shift into an and.
1570 uint64_t Val = ~0ULL; // All ones.
1571 Val <<= ShAmtVal; // Shift over to the right spot.
1572
1573 Constant *Mask;
1574 if (CI->getType()->isUnsigned()) {
1575 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
1576 Val &= (1ULL << TypeBits)-1;
1577 Mask = ConstantUInt::get(CI->getType(), Val);
1578 } else {
1579 Mask = ConstantSInt::get(CI->getType(), Val);
1580 }
1581
1582 Instruction *AndI =
1583 BinaryOperator::createAnd(LHSI->getOperand(0),
1584 Mask, LHSI->getName()+".mask");
1585 Value *And = InsertNewInstBefore(AndI, I);
1586 return new SetCondInst(I.getOpcode(), And,
1587 ConstantExpr::getShl(CI, ShAmt));
1588 }
1589 break;
1590 }
1591 }
1592 }
1593 break;
Chris Lattner0c967662004-09-24 15:21:34 +00001594
Chris Lattner648e3bc2004-09-23 21:52:49 +00001595 case Instruction::Div:
1596 if (0 && isa<ConstantInt>(LHSI->getOperand(1))) {
1597 std::cerr << "COULD FOLD: " << *LHSI;
1598 std::cerr << "COULD FOLD: " << I << "\n";
1599 }
1600 break;
1601 case Instruction::Select:
1602 // If either operand of the select is a constant, we can fold the
1603 // comparison into the select arms, which will cause one to be
1604 // constant folded and the select turned into a bitwise or.
1605 Value *Op1 = 0, *Op2 = 0;
1606 if (LHSI->hasOneUse()) {
Chris Lattner457dd822004-06-09 07:59:58 +00001607 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00001608 // Fold the known value into the constant operand.
1609 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1610 // Insert a new SetCC of the other select operand.
1611 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00001612 LHSI->getOperand(2), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00001613 I.getName()), I);
Chris Lattner457dd822004-06-09 07:59:58 +00001614 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2be51ae2004-06-09 04:24:29 +00001615 // Fold the known value into the constant operand.
1616 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1617 // Insert a new SetCC of the other select operand.
1618 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner457dd822004-06-09 07:59:58 +00001619 LHSI->getOperand(1), CI,
Chris Lattner2be51ae2004-06-09 04:24:29 +00001620 I.getName()), I);
1621 }
Chris Lattner2be51ae2004-06-09 04:24:29 +00001622 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00001623
1624 if (Op1)
1625 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1626 break;
1627 }
1628
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001629 // Simplify seteq and setne instructions...
1630 if (I.getOpcode() == Instruction::SetEQ ||
1631 I.getOpcode() == Instruction::SetNE) {
1632 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1633
Chris Lattner00b1a7e2003-07-23 17:26:36 +00001634 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001635 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00001636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1637 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00001638 case Instruction::Rem:
1639 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1640 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
1641 BO->hasOneUse() &&
1642 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
1643 if (unsigned L2 =
1644 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
1645 const Type *UTy = BO->getType()->getUnsignedVersion();
1646 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
1647 UTy, "tmp"), I);
1648 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
1649 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
1650 RHSCst, BO->getName()), I);
1651 return BinaryOperator::create(I.getOpcode(), NewRem,
1652 Constant::getNullValue(UTy));
1653 }
1654 break;
1655
Chris Lattner934754b2003-08-13 05:33:12 +00001656 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00001657 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1658 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00001659 if (BO->hasOneUse())
1660 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1661 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00001662 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00001663 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1664 // efficiently invertible, or if the add has just this one use.
1665 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner15d58b62004-06-27 22:51:36 +00001666
Chris Lattner934754b2003-08-13 05:33:12 +00001667 if (Value *NegVal = dyn_castNegVal(BOp1))
1668 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1669 else if (Value *NegVal = dyn_castNegVal(BOp0))
1670 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00001671 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00001672 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1673 BO->setName("");
1674 InsertNewInstBefore(Neg, I);
1675 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1676 }
1677 }
1678 break;
1679 case Instruction::Xor:
1680 // For the xor case, we can xor two constants together, eliminating
1681 // the explicit xor.
1682 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1683 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00001684 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00001685
1686 // FALLTHROUGH
1687 case Instruction::Sub:
1688 // Replace (([sub|xor] A, B) != 0) with (A != B)
1689 if (CI->isNullValue())
1690 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1691 BO->getOperand(1));
1692 break;
1693
1694 case Instruction::Or:
1695 // If bits are being or'd in that are not present in the constant we
1696 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00001697 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00001698 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00001699 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001700 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00001701 }
Chris Lattner934754b2003-08-13 05:33:12 +00001702 break;
1703
1704 case Instruction::And:
1705 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001706 // If bits are being compared against that are and'd out, then the
1707 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00001708 if (!ConstantExpr::getAnd(CI,
1709 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001710 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00001711
Chris Lattner457dd822004-06-09 07:59:58 +00001712 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00001713 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00001714 return new SetCondInst(isSetNE ? Instruction::SetEQ :
1715 Instruction::SetNE, Op0,
1716 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00001717
Chris Lattner934754b2003-08-13 05:33:12 +00001718 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1719 // to be a signed value as appropriate.
1720 if (isSignBit(BOC)) {
1721 Value *X = BO->getOperand(0);
1722 // If 'X' is not signed, insert a cast now...
1723 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001724 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00001725 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00001726 }
1727 return new SetCondInst(isSetNE ? Instruction::SetLT :
1728 Instruction::SetGE, X,
1729 Constant::getNullValue(X->getType()));
1730 }
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001731
Chris Lattner83c4ec02004-09-27 19:29:18 +00001732 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001733 if (CI->isNullValue() && isHighOnes(BOC)) {
1734 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00001735 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001736
1737 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00001738 if (NegX->getType()->isSigned()) {
1739 const Type *DestTy = NegX->getType()->getUnsignedVersion();
1740 X = InsertCastBefore(X, DestTy, I);
1741 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001742 }
1743
1744 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00001745 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001746 }
1747
Chris Lattnerbc5d4142003-07-23 17:02:11 +00001748 }
Chris Lattner934754b2003-08-13 05:33:12 +00001749 default: break;
1750 }
1751 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001752 } else { // Not a SetEQ/SetNE
1753 // If the LHS is a cast from an integral value of the same size,
1754 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1755 Value *CastOp = Cast->getOperand(0);
1756 const Type *SrcTy = CastOp->getType();
1757 unsigned SrcTySize = SrcTy->getPrimitiveSize();
1758 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1759 SrcTySize == Cast->getType()->getPrimitiveSize()) {
1760 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
1761 "Source and destination signednesses should differ!");
1762 if (Cast->getType()->isSigned()) {
1763 // If this is a signed comparison, check for comparisons in the
1764 // vicinity of zero.
1765 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1766 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00001767 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001768 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1769 else if (I.getOpcode() == Instruction::SetGT &&
1770 cast<ConstantSInt>(CI)->getValue() == -1)
1771 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00001772 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001773 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1774 } else {
1775 ConstantUInt *CUI = cast<ConstantUInt>(CI);
1776 if (I.getOpcode() == Instruction::SetLT &&
1777 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1778 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00001779 return BinaryOperator::createSetGT(CastOp,
1780 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001781 else if (I.getOpcode() == Instruction::SetGT &&
1782 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1783 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00001784 return BinaryOperator::createSetLT(CastOp,
1785 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00001786 }
1787 }
1788 }
Chris Lattner40f5d702003-06-04 05:10:11 +00001789 }
Chris Lattner074d84c2003-06-01 03:35:25 +00001790
Chris Lattner8b170942002-08-09 23:47:40 +00001791 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattner233f7dc2002-08-12 21:17:25 +00001792 if (CI->isMinValue()) {
Chris Lattner8b170942002-08-09 23:47:40 +00001793 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1794 return ReplaceInstUsesWith(I, ConstantBool::False);
1795 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1796 return ReplaceInstUsesWith(I, ConstantBool::True);
1797 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001798 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001799 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001800 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001801
Chris Lattner233f7dc2002-08-12 21:17:25 +00001802 } else if (CI->isMaxValue()) {
Chris Lattner8b170942002-08-09 23:47:40 +00001803 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1804 return ReplaceInstUsesWith(I, ConstantBool::False);
1805 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1806 return ReplaceInstUsesWith(I, ConstantBool::True);
1807 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001808 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001809 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001810 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00001811
1812 // Comparing against a value really close to min or max?
1813 } else if (isMinValuePlusOne(CI)) {
1814 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001815 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001816 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattner48595f12004-06-10 02:07:29 +00001817 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001818
1819 } else if (isMaxValueMinusOne(CI)) {
1820 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001821 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001822 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattner48595f12004-06-10 02:07:29 +00001823 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner8b170942002-08-09 23:47:40 +00001824 }
Chris Lattner45aaafe2004-02-23 05:47:48 +00001825
1826 // If we still have a setle or setge instruction, turn it into the
1827 // appropriate setlt or setgt instruction. Since the border cases have
1828 // already been handled above, this requires little checking.
1829 //
1830 if (I.getOpcode() == Instruction::SetLE)
Chris Lattner48595f12004-06-10 02:07:29 +00001831 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner45aaafe2004-02-23 05:47:48 +00001832 if (I.getOpcode() == Instruction::SetGE)
Chris Lattner48595f12004-06-10 02:07:29 +00001833 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattner3f5b8772002-05-06 16:14:14 +00001834 }
1835
Chris Lattnerde90b762003-11-03 04:25:02 +00001836 // Test to see if the operands of the setcc are casted versions of other
1837 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00001838 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1839 Value *CastOp0 = CI->getOperand(0);
1840 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00001841 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00001842 (I.getOpcode() == Instruction::SetEQ ||
1843 I.getOpcode() == Instruction::SetNE)) {
1844 // We keep moving the cast from the left operand over to the right
1845 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00001846 Op0 = CastOp0;
Chris Lattnerde90b762003-11-03 04:25:02 +00001847
1848 // If operand #1 is a cast instruction, see if we can eliminate it as
1849 // well.
Chris Lattner68708052003-11-03 05:17:03 +00001850 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1851 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00001852 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00001853 Op1 = CI2->getOperand(0);
Chris Lattnerde90b762003-11-03 04:25:02 +00001854
1855 // If Op1 is a constant, we can fold the cast into the constant.
1856 if (Op1->getType() != Op0->getType())
1857 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1858 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1859 } else {
1860 // Otherwise, cast the RHS right before the setcc
1861 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1862 InsertNewInstBefore(cast<Instruction>(Op1), I);
1863 }
1864 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1865 }
1866
Chris Lattner68708052003-11-03 05:17:03 +00001867 // Handle the special case of: setcc (cast bool to X), <cst>
1868 // This comes up when you have code like
1869 // int X = A < B;
1870 // if (X) ...
1871 // For generality, we handle any zero-extension of any operand comparison
1872 // with a constant.
1873 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1874 const Type *SrcTy = CastOp0->getType();
1875 const Type *DestTy = Op0->getType();
1876 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1877 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1878 // Ok, we have an expansion of operand 0 into a new type. Get the
1879 // constant value, masink off bits which are not set in the RHS. These
1880 // could be set if the destination value is signed.
1881 uint64_t ConstVal = ConstantRHS->getRawValue();
1882 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1883
1884 // If the constant we are comparing it with has high bits set, which
1885 // don't exist in the original value, the values could never be equal,
1886 // because the source would be zero extended.
1887 unsigned SrcBits =
1888 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner1bcc70d2003-11-05 17:31:36 +00001889 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1890 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner68708052003-11-03 05:17:03 +00001891 switch (I.getOpcode()) {
1892 default: assert(0 && "Unknown comparison type!");
1893 case Instruction::SetEQ:
1894 return ReplaceInstUsesWith(I, ConstantBool::False);
1895 case Instruction::SetNE:
1896 return ReplaceInstUsesWith(I, ConstantBool::True);
1897 case Instruction::SetLT:
1898 case Instruction::SetLE:
1899 if (DestTy->isSigned() && HasSignBit)
1900 return ReplaceInstUsesWith(I, ConstantBool::False);
1901 return ReplaceInstUsesWith(I, ConstantBool::True);
1902 case Instruction::SetGT:
1903 case Instruction::SetGE:
1904 if (DestTy->isSigned() && HasSignBit)
1905 return ReplaceInstUsesWith(I, ConstantBool::True);
1906 return ReplaceInstUsesWith(I, ConstantBool::False);
1907 }
1908 }
1909
1910 // Otherwise, we can replace the setcc with a setcc of the smaller
1911 // operand value.
1912 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1913 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1914 }
1915 }
1916 }
Chris Lattner7e708292002-06-25 16:13:24 +00001917 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001918}
1919
1920
1921
Chris Lattnerea340052003-03-10 19:16:08 +00001922Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001923 assert(I.getOperand(1)->getType() == Type::UByteTy);
1924 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00001925 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001926
1927 // shl X, 0 == X and shr X, 0 == X
1928 // shl 0, X == 0 and shr 0, X == 0
1929 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00001930 Op0 == Constant::getNullValue(Op0->getType()))
1931 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001932
Chris Lattnerdf17af12003-08-12 21:53:41 +00001933 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1934 if (!isLeftShift)
1935 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1936 if (CSI->isAllOnesValue())
1937 return ReplaceInstUsesWith(I, CSI);
1938
Chris Lattner2eefe512004-04-09 19:05:30 +00001939 // Try to fold constant and into select arguments.
1940 if (isa<Constant>(Op0))
1941 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1942 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1943 return R;
1944
Chris Lattner3f5b8772002-05-06 16:14:14 +00001945 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00001946 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1947 // of a signed value.
1948 //
Chris Lattnerea340052003-03-10 19:16:08 +00001949 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner8adac752004-02-23 20:30:06 +00001950 if (CUI->getValue() >= TypeBits) {
1951 if (!Op0->getType()->isSigned() || isLeftShift)
1952 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1953 else {
1954 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1955 return &I;
1956 }
1957 }
Chris Lattnerf2836082002-09-10 23:04:09 +00001958
Chris Lattnere92d2f42003-08-13 04:18:28 +00001959 // ((X*C1) << C2) == (X * (C1 << C2))
1960 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1961 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1962 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001963 return BinaryOperator::createMul(BO->getOperand(0),
1964 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnere92d2f42003-08-13 04:18:28 +00001965
Chris Lattner2eefe512004-04-09 19:05:30 +00001966 // Try to fold constant and into select arguments.
1967 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1968 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1969 return R;
Chris Lattnere92d2f42003-08-13 04:18:28 +00001970
Chris Lattnerdf17af12003-08-12 21:53:41 +00001971 // If the operand is an bitwise operator with a constant RHS, and the
1972 // shift is the only use, we can pull it out of the shift.
Chris Lattnerfd059242003-10-15 16:48:29 +00001973 if (Op0->hasOneUse())
Chris Lattnerdf17af12003-08-12 21:53:41 +00001974 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1975 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1976 bool isValid = true; // Valid only for And, Or, Xor
1977 bool highBitSet = false; // Transform if high bit of constant set?
1978
1979 switch (Op0BO->getOpcode()) {
1980 default: isValid = false; break; // Do not perform transform!
1981 case Instruction::Or:
1982 case Instruction::Xor:
1983 highBitSet = false;
1984 break;
1985 case Instruction::And:
1986 highBitSet = true;
1987 break;
1988 }
1989
1990 // If this is a signed shift right, and the high bit is modified
1991 // by the logical operation, do not perform the transformation.
1992 // The highBitSet boolean indicates the value of the high bit of
1993 // the constant which would cause it to be modified for this
1994 // operation.
1995 //
1996 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1997 uint64_t Val = Op0C->getRawValue();
1998 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1999 }
2000
2001 if (isValid) {
Chris Lattner7c4049c2004-01-12 19:35:11 +00002002 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002003
2004 Instruction *NewShift =
2005 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2006 Op0BO->getName());
2007 Op0BO->setName("");
2008 InsertNewInstBefore(NewShift, I);
2009
2010 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2011 NewRHS);
2012 }
2013 }
2014
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002015 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00002016 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00002017 if (ConstantUInt *ShiftAmt1C =
2018 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002019 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2020 unsigned ShiftAmt2 = CUI->getValue();
2021
2022 // Check for (A << c1) << c2 and (A >> c1) >> c2
2023 if (I.getOpcode() == Op0SI->getOpcode()) {
2024 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattner8adac752004-02-23 20:30:06 +00002025 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2026 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002027 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2028 ConstantUInt::get(Type::UByteTy, Amt));
2029 }
2030
Chris Lattner943c7132003-07-24 18:38:56 +00002031 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2032 // signed types, we can only support the (A >> c1) << c2 configuration,
2033 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00002034 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002035 // Calculate bitmask for what gets shifted off the edge...
2036 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00002037 if (isLeftShift)
Chris Lattner48595f12004-06-10 02:07:29 +00002038 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00002039 else
Chris Lattner48595f12004-06-10 02:07:29 +00002040 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002041
2042 Instruction *Mask =
Chris Lattner48595f12004-06-10 02:07:29 +00002043 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2044 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner08fd7ab2003-07-24 17:52:58 +00002045 InsertNewInstBefore(Mask, I);
2046
2047 // Figure out what flavor of shift we should use...
2048 if (ShiftAmt1 == ShiftAmt2)
2049 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2050 else if (ShiftAmt1 < ShiftAmt2) {
2051 return new ShiftInst(I.getOpcode(), Mask,
2052 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2053 } else {
2054 return new ShiftInst(Op0SI->getOpcode(), Mask,
2055 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2056 }
2057 }
2058 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002059 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00002060
Chris Lattner3f5b8772002-05-06 16:14:14 +00002061 return 0;
2062}
2063
Chris Lattnerbee7e762004-07-20 00:59:32 +00002064enum CastType {
2065 Noop = 0,
2066 Truncate = 1,
2067 Signext = 2,
2068 Zeroext = 3
2069};
2070
2071/// getCastType - In the future, we will split the cast instruction into these
2072/// various types. Until then, we have to do the analysis here.
2073static CastType getCastType(const Type *Src, const Type *Dest) {
2074 assert(Src->isIntegral() && Dest->isIntegral() &&
2075 "Only works on integral types!");
2076 unsigned SrcSize = Src->getPrimitiveSize()*8;
2077 if (Src == Type::BoolTy) SrcSize = 1;
2078 unsigned DestSize = Dest->getPrimitiveSize()*8;
2079 if (Dest == Type::BoolTy) DestSize = 1;
2080
2081 if (SrcSize == DestSize) return Noop;
2082 if (SrcSize > DestSize) return Truncate;
2083 if (Src->isSigned()) return Signext;
2084 return Zeroext;
2085}
2086
Chris Lattner3f5b8772002-05-06 16:14:14 +00002087
Chris Lattnera1be5662002-05-02 17:06:02 +00002088// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2089// instruction.
2090//
Chris Lattner24c8e382003-07-24 17:35:25 +00002091static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner59a20772004-07-20 05:21:00 +00002092 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00002093
Chris Lattner8fd217c2002-08-02 20:00:25 +00002094 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2095 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00002096 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00002097 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00002098 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00002099
Chris Lattnere8a7e592004-07-21 04:27:24 +00002100 // If we are casting between pointer and integer types, treat pointers as
2101 // integers of the appropriate size for the code below.
2102 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2103 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2104 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00002105
Chris Lattnera1be5662002-05-02 17:06:02 +00002106 // Allow free casting and conversion of sizes as long as the sign doesn't
2107 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00002108 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00002109 CastType FirstCast = getCastType(SrcTy, MidTy);
2110 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00002111
Chris Lattnerbee7e762004-07-20 00:59:32 +00002112 // Capture the effect of these two casts. If the result is a legal cast,
2113 // the CastType is stored here, otherwise a special code is used.
2114 static const unsigned CastResult[] = {
2115 // First cast is noop
2116 0, 1, 2, 3,
2117 // First cast is a truncate
2118 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2119 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00002120 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00002121 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00002122 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00002123 };
2124
2125 unsigned Result = CastResult[FirstCast*4+SecondCast];
2126 switch (Result) {
2127 default: assert(0 && "Illegal table value!");
2128 case 0:
2129 case 1:
2130 case 2:
2131 case 3:
2132 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2133 // truncates, we could eliminate more casts.
2134 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2135 case 4:
2136 return false; // Not possible to eliminate this here.
2137 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00002138 // Sign or zero extend followed by truncate is always ok if the result
2139 // is a truncate or noop.
2140 CastType ResultCast = getCastType(SrcTy, DstTy);
2141 if (ResultCast == Noop || ResultCast == Truncate)
2142 return true;
2143 // Otherwise we are still growing the value, we are only safe if the
2144 // result will match the sign/zeroextendness of the result.
2145 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00002146 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00002147 }
Chris Lattnera1be5662002-05-02 17:06:02 +00002148 return false;
2149}
2150
Chris Lattner59a20772004-07-20 05:21:00 +00002151static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002152 if (V->getType() == Ty || isa<Constant>(V)) return false;
2153 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00002154 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2155 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00002156 return false;
2157 return true;
2158}
2159
2160/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2161/// InsertBefore instruction. This is specialized a bit to avoid inserting
2162/// casts that are known to not do anything...
2163///
2164Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2165 Instruction *InsertBefore) {
2166 if (V->getType() == DestTy) return V;
2167 if (Constant *C = dyn_cast<Constant>(V))
2168 return ConstantExpr::getCast(C, DestTy);
2169
2170 CastInst *CI = new CastInst(V, DestTy, V->getName());
2171 InsertNewInstBefore(CI, *InsertBefore);
2172 return CI;
2173}
Chris Lattnera1be5662002-05-02 17:06:02 +00002174
2175// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002176//
Chris Lattner7e708292002-06-25 16:13:24 +00002177Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00002178 Value *Src = CI.getOperand(0);
2179
Chris Lattnera1be5662002-05-02 17:06:02 +00002180 // If the user is casting a value to the same type, eliminate this cast
2181 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00002182 if (CI.getType() == Src->getType())
2183 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00002184
Chris Lattnera1be5662002-05-02 17:06:02 +00002185 // If casting the result of another cast instruction, try to eliminate this
2186 // one!
2187 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002188 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002189 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner59a20772004-07-20 05:21:00 +00002190 CSrc->getType(), CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00002191 // This instruction now refers directly to the cast's src operand. This
2192 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00002193 CI.setOperand(0, CSrc->getOperand(0));
2194 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00002195 }
2196
Chris Lattner8fd217c2002-08-02 20:00:25 +00002197 // If this is an A->B->A cast, and we are dealing with integral types, try
2198 // to convert this into a logical 'and' instruction.
2199 //
2200 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00002201 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner8fd217c2002-08-02 20:00:25 +00002202 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2203 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2204 assert(CSrc->getType() != Type::ULongTy &&
2205 "Cannot have type bigger than ulong!");
Chris Lattnerbd4ecf72003-05-26 23:41:32 +00002206 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner8fd217c2002-08-02 20:00:25 +00002207 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattner48595f12004-06-10 02:07:29 +00002208 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner8fd217c2002-08-02 20:00:25 +00002209 }
2210 }
2211
Chris Lattnera710ddc2004-05-25 04:29:21 +00002212 // If this is a cast to bool, turn it into the appropriate setne instruction.
2213 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00002214 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00002215 Constant::getNullValue(CI.getOperand(0)->getType()));
2216
Chris Lattner797249b2003-06-21 23:12:02 +00002217 // If casting the result of a getelementptr instruction with no offset, turn
2218 // this into a cast of the original pointer!
2219 //
Chris Lattner79d35b32003-06-23 21:59:52 +00002220 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00002221 bool AllZeroOperands = true;
2222 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2223 if (!isa<Constant>(GEP->getOperand(i)) ||
2224 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2225 AllZeroOperands = false;
2226 break;
2227 }
2228 if (AllZeroOperands) {
2229 CI.setOperand(0, GEP->getOperand(0));
2230 return &CI;
2231 }
2232 }
2233
Chris Lattnerbc61e662003-11-02 05:57:39 +00002234 // If we are casting a malloc or alloca to a pointer to a type of the same
2235 // size, rewrite the allocation instruction to allocate the "right" type.
2236 //
2237 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerfc07a342003-11-02 06:54:48 +00002238 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerbc61e662003-11-02 05:57:39 +00002239 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2240 // Get the type really allocated and the type casted to...
2241 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerbc61e662003-11-02 05:57:39 +00002242 const Type *CastElTy = PTy->getElementType();
Chris Lattnerfae10102004-07-06 19:28:42 +00002243 if (AllocElTy->isSized() && CastElTy->isSized()) {
2244 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2245 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner1bcc70d2003-11-05 17:31:36 +00002246
Chris Lattnerfae10102004-07-06 19:28:42 +00002247 // If the allocation is for an even multiple of the cast type size
2248 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2249 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerbc61e662003-11-02 05:57:39 +00002250 AllocElTySize/CastElTySize);
Chris Lattnerfae10102004-07-06 19:28:42 +00002251 std::string Name = AI->getName(); AI->setName("");
2252 AllocationInst *New;
2253 if (isa<MallocInst>(AI))
2254 New = new MallocInst(CastElTy, Amt, Name);
2255 else
2256 New = new AllocaInst(CastElTy, Amt, Name);
2257 InsertNewInstBefore(New, *AI);
2258 return ReplaceInstUsesWith(CI, New);
2259 }
Chris Lattnerbc61e662003-11-02 05:57:39 +00002260 }
2261 }
2262
Chris Lattner24c8e382003-07-24 17:35:25 +00002263 // If the source value is an instruction with only this use, we can attempt to
2264 // propagate the cast into the instruction. Also, only handle integral types
2265 // for now.
2266 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00002267 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00002268 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2269 const Type *DestTy = CI.getType();
2270 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2271 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2272
2273 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2274 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2275
2276 switch (SrcI->getOpcode()) {
2277 case Instruction::Add:
2278 case Instruction::Mul:
2279 case Instruction::And:
2280 case Instruction::Or:
2281 case Instruction::Xor:
2282 // If we are discarding information, or just changing the sign, rewrite.
2283 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2284 // Don't insert two casts if they cannot be eliminated. We allow two
2285 // casts to be inserted if the sizes are the same. This could only be
2286 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00002287 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2288 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00002289 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2290 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2291 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2292 ->getOpcode(), Op0c, Op1c);
2293 }
2294 }
2295 break;
2296 case Instruction::Shl:
2297 // Allow changing the sign of the source operand. Do not allow changing
2298 // the size of the shift, UNLESS the shift amount is a constant. We
2299 // mush not change variable sized shifts to a smaller size, because it
2300 // is undefined to shift more bits out than exist in the value.
2301 if (DestBitSize == SrcBitSize ||
2302 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2303 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2304 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2305 }
2306 break;
2307 }
2308 }
2309
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002310 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00002311}
2312
Chris Lattnere576b912004-04-09 23:46:01 +00002313/// GetSelectFoldableOperands - We want to turn code that looks like this:
2314/// %C = or %A, %B
2315/// %D = select %cond, %C, %A
2316/// into:
2317/// %C = select %cond, %B, 0
2318/// %D = or %A, %C
2319///
2320/// Assuming that the specified instruction is an operand to the select, return
2321/// a bitmask indicating which operands of this instruction are foldable if they
2322/// equal the other incoming value of the select.
2323///
2324static unsigned GetSelectFoldableOperands(Instruction *I) {
2325 switch (I->getOpcode()) {
2326 case Instruction::Add:
2327 case Instruction::Mul:
2328 case Instruction::And:
2329 case Instruction::Or:
2330 case Instruction::Xor:
2331 return 3; // Can fold through either operand.
2332 case Instruction::Sub: // Can only fold on the amount subtracted.
2333 case Instruction::Shl: // Can only fold on the shift amount.
2334 case Instruction::Shr:
2335 return 1;
2336 default:
2337 return 0; // Cannot fold
2338 }
2339}
2340
2341/// GetSelectFoldableConstant - For the same transformation as the previous
2342/// function, return the identity constant that goes into the select.
2343static Constant *GetSelectFoldableConstant(Instruction *I) {
2344 switch (I->getOpcode()) {
2345 default: assert(0 && "This cannot happen!"); abort();
2346 case Instruction::Add:
2347 case Instruction::Sub:
2348 case Instruction::Or:
2349 case Instruction::Xor:
2350 return Constant::getNullValue(I->getType());
2351 case Instruction::Shl:
2352 case Instruction::Shr:
2353 return Constant::getNullValue(Type::UByteTy);
2354 case Instruction::And:
2355 return ConstantInt::getAllOnesValue(I->getType());
2356 case Instruction::Mul:
2357 return ConstantInt::get(I->getType(), 1);
2358 }
2359}
2360
Chris Lattner3d69f462004-03-12 05:52:32 +00002361Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002362 Value *CondVal = SI.getCondition();
2363 Value *TrueVal = SI.getTrueValue();
2364 Value *FalseVal = SI.getFalseValue();
2365
2366 // select true, X, Y -> X
2367 // select false, X, Y -> Y
2368 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00002369 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002370 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00002371 else {
2372 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002373 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00002374 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002375
2376 // select C, X, X -> X
2377 if (TrueVal == FalseVal)
2378 return ReplaceInstUsesWith(SI, TrueVal);
2379
Chris Lattner0c199a72004-04-08 04:43:23 +00002380 if (SI.getType() == Type::BoolTy)
2381 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2382 if (C == ConstantBool::True) {
2383 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00002384 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002385 } else {
2386 // Change: A = select B, false, C --> A = and !B, C
2387 Value *NotCond =
2388 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2389 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00002390 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002391 }
2392 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2393 if (C == ConstantBool::False) {
2394 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00002395 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002396 } else {
2397 // Change: A = select B, C, true --> A = or !B, C
2398 Value *NotCond =
2399 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2400 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00002401 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00002402 }
2403 }
2404
Chris Lattner2eefe512004-04-09 19:05:30 +00002405 // Selecting between two integer constants?
2406 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2407 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2408 // select C, 1, 0 -> cast C to int
2409 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2410 return new CastInst(CondVal, SI.getType());
2411 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2412 // select C, 0, 1 -> cast !C to int
2413 Value *NotCond =
2414 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00002415 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00002416 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00002417 }
Chris Lattner457dd822004-06-09 07:59:58 +00002418
2419 // If one of the constants is zero (we know they can't both be) and we
2420 // have a setcc instruction with zero, and we have an 'and' with the
2421 // non-constant value, eliminate this whole mess. This corresponds to
2422 // cases like this: ((X & 27) ? 27 : 0)
2423 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2424 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2425 if ((IC->getOpcode() == Instruction::SetEQ ||
2426 IC->getOpcode() == Instruction::SetNE) &&
2427 isa<ConstantInt>(IC->getOperand(1)) &&
2428 cast<Constant>(IC->getOperand(1))->isNullValue())
2429 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2430 if (ICA->getOpcode() == Instruction::And &&
2431 isa<ConstantInt>(ICA->getOperand(1)) &&
2432 (ICA->getOperand(1) == TrueValC ||
2433 ICA->getOperand(1) == FalseValC) &&
2434 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2435 // Okay, now we know that everything is set up, we just don't
2436 // know whether we have a setne or seteq and whether the true or
2437 // false val is the zero.
2438 bool ShouldNotVal = !TrueValC->isNullValue();
2439 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2440 Value *V = ICA;
2441 if (ShouldNotVal)
2442 V = InsertNewInstBefore(BinaryOperator::create(
2443 Instruction::Xor, V, ICA->getOperand(1)), SI);
2444 return ReplaceInstUsesWith(SI, V);
2445 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00002446 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00002447
2448 // See if we are selecting two values based on a comparison of the two values.
2449 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2450 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2451 // Transform (X == Y) ? X : Y -> Y
2452 if (SCI->getOpcode() == Instruction::SetEQ)
2453 return ReplaceInstUsesWith(SI, FalseVal);
2454 // Transform (X != Y) ? X : Y -> X
2455 if (SCI->getOpcode() == Instruction::SetNE)
2456 return ReplaceInstUsesWith(SI, TrueVal);
2457 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2458
2459 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2460 // Transform (X == Y) ? Y : X -> X
2461 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00002462 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00002463 // Transform (X != Y) ? Y : X -> Y
2464 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00002465 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00002466 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2467 }
2468 }
Chris Lattner0c199a72004-04-08 04:43:23 +00002469
Chris Lattnere576b912004-04-09 23:46:01 +00002470 // See if we can fold the select into one of our operands.
2471 if (SI.getType()->isInteger()) {
2472 // See the comment above GetSelectFoldableOperands for a description of the
2473 // transformation we are doing here.
2474 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2475 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2476 !isa<Constant>(FalseVal))
2477 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2478 unsigned OpToFold = 0;
2479 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2480 OpToFold = 1;
2481 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2482 OpToFold = 2;
2483 }
2484
2485 if (OpToFold) {
2486 Constant *C = GetSelectFoldableConstant(TVI);
2487 std::string Name = TVI->getName(); TVI->setName("");
2488 Instruction *NewSel =
2489 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2490 Name);
2491 InsertNewInstBefore(NewSel, SI);
2492 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2493 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2494 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2495 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2496 else {
2497 assert(0 && "Unknown instruction!!");
2498 }
2499 }
2500 }
2501
2502 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2503 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2504 !isa<Constant>(TrueVal))
2505 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2506 unsigned OpToFold = 0;
2507 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2508 OpToFold = 1;
2509 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2510 OpToFold = 2;
2511 }
2512
2513 if (OpToFold) {
2514 Constant *C = GetSelectFoldableConstant(FVI);
2515 std::string Name = FVI->getName(); FVI->setName("");
2516 Instruction *NewSel =
2517 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2518 Name);
2519 InsertNewInstBefore(NewSel, SI);
2520 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2521 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2522 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2523 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2524 else {
2525 assert(0 && "Unknown instruction!!");
2526 }
2527 }
2528 }
2529 }
Chris Lattner3d69f462004-03-12 05:52:32 +00002530 return 0;
2531}
2532
2533
Chris Lattner9fe38862003-06-19 17:00:31 +00002534// CallInst simplification
2535//
2536Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +00002537 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2538 // visitCallSite.
2539 if (Function *F = CI.getCalledFunction())
2540 switch (F->getIntrinsicID()) {
2541 case Intrinsic::memmove:
2542 case Intrinsic::memcpy:
2543 case Intrinsic::memset:
2544 // memmove/cpy/set of zero bytes is a noop.
2545 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2546 if (NumBytes->isNullValue())
2547 return EraseInstFromFunction(CI);
2548 }
2549 break;
2550 default:
2551 break;
2552 }
2553
Chris Lattnera44d8a22003-10-07 22:32:43 +00002554 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00002555}
2556
2557// InvokeInst simplification
2558//
2559Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00002560 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00002561}
2562
Chris Lattnera44d8a22003-10-07 22:32:43 +00002563// visitCallSite - Improvements for call and invoke instructions.
2564//
2565Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00002566 bool Changed = false;
2567
2568 // If the callee is a constexpr cast of a function, attempt to move the cast
2569 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00002570 if (transformConstExprCastCall(CS)) return 0;
2571
Chris Lattner6c266db2003-10-07 22:54:13 +00002572 Value *Callee = CS.getCalledValue();
2573 const PointerType *PTy = cast<PointerType>(Callee->getType());
2574 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2575 if (FTy->isVarArg()) {
2576 // See if we can optimize any arguments passed through the varargs area of
2577 // the call.
2578 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2579 E = CS.arg_end(); I != E; ++I)
2580 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2581 // If this cast does not effect the value passed through the varargs
2582 // area, we can eliminate the use of the cast.
2583 Value *Op = CI->getOperand(0);
2584 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2585 *I = Op;
2586 Changed = true;
2587 }
2588 }
2589 }
Chris Lattnera44d8a22003-10-07 22:32:43 +00002590
Chris Lattner6c266db2003-10-07 22:54:13 +00002591 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00002592}
2593
Chris Lattner9fe38862003-06-19 17:00:31 +00002594// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2595// attempt to move the cast to the arguments of the call/invoke.
2596//
2597bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2598 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2599 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00002600 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00002601 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00002602 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00002603 Instruction *Caller = CS.getInstruction();
2604
2605 // Okay, this is a cast from a function to a different type. Unless doing so
2606 // would cause a type conversion of one of our arguments, change this call to
2607 // be a direct call with arguments casted to the appropriate types.
2608 //
2609 const FunctionType *FT = Callee->getFunctionType();
2610 const Type *OldRetTy = Caller->getType();
2611
Chris Lattnerf78616b2004-01-14 06:06:08 +00002612 // Check to see if we are changing the return type...
2613 if (OldRetTy != FT->getReturnType()) {
2614 if (Callee->isExternal() &&
2615 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2616 !Caller->use_empty())
2617 return false; // Cannot transform this return value...
2618
2619 // If the callsite is an invoke instruction, and the return value is used by
2620 // a PHI node in a successor, we cannot change the return type of the call
2621 // because there is no place to put the cast instruction (without breaking
2622 // the critical edge). Bail out in this case.
2623 if (!Caller->use_empty())
2624 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2625 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2626 UI != E; ++UI)
2627 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2628 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00002629 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00002630 return false;
2631 }
Chris Lattner9fe38862003-06-19 17:00:31 +00002632
2633 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2634 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2635
2636 CallSite::arg_iterator AI = CS.arg_begin();
2637 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2638 const Type *ParamTy = FT->getParamType(i);
2639 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2640 if (Callee->isExternal() && !isConvertible) return false;
2641 }
2642
2643 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2644 Callee->isExternal())
2645 return false; // Do not delete arguments unless we have a function body...
2646
2647 // Okay, we decided that this is a safe thing to do: go ahead and start
2648 // inserting cast instructions as necessary...
2649 std::vector<Value*> Args;
2650 Args.reserve(NumActualArgs);
2651
2652 AI = CS.arg_begin();
2653 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2654 const Type *ParamTy = FT->getParamType(i);
2655 if ((*AI)->getType() == ParamTy) {
2656 Args.push_back(*AI);
2657 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00002658 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2659 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00002660 }
2661 }
2662
2663 // If the function takes more arguments than the call was taking, add them
2664 // now...
2665 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2666 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2667
2668 // If we are removing arguments to the function, emit an obnoxious warning...
2669 if (FT->getNumParams() < NumActualArgs)
2670 if (!FT->isVarArg()) {
2671 std::cerr << "WARNING: While resolving call to function '"
2672 << Callee->getName() << "' arguments were dropped!\n";
2673 } else {
2674 // Add all of the arguments in their promoted form to the arg list...
2675 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2676 const Type *PTy = getPromotedType((*AI)->getType());
2677 if (PTy != (*AI)->getType()) {
2678 // Must promote to pass through va_arg area!
2679 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2680 InsertNewInstBefore(Cast, *Caller);
2681 Args.push_back(Cast);
2682 } else {
2683 Args.push_back(*AI);
2684 }
2685 }
2686 }
2687
2688 if (FT->getReturnType() == Type::VoidTy)
2689 Caller->setName(""); // Void type should not have a name...
2690
2691 Instruction *NC;
2692 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00002693 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00002694 Args, Caller->getName(), Caller);
2695 } else {
2696 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2697 }
2698
2699 // Insert a cast of the return type as necessary...
2700 Value *NV = NC;
2701 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2702 if (NV->getType() != Type::VoidTy) {
2703 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00002704
2705 // If this is an invoke instruction, we should insert it after the first
2706 // non-phi, instruction in the normal successor block.
2707 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2708 BasicBlock::iterator I = II->getNormalDest()->begin();
2709 while (isa<PHINode>(I)) ++I;
2710 InsertNewInstBefore(NC, *I);
2711 } else {
2712 // Otherwise, it's a call, just insert cast right after the call instr
2713 InsertNewInstBefore(NC, *Caller);
2714 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00002715 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00002716 } else {
2717 NV = Constant::getNullValue(Caller->getType());
2718 }
2719 }
2720
2721 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2722 Caller->replaceAllUsesWith(NV);
2723 Caller->getParent()->getInstList().erase(Caller);
2724 removeFromWorkList(Caller);
2725 return true;
2726}
2727
2728
Chris Lattnera1be5662002-05-02 17:06:02 +00002729
Chris Lattner473945d2002-05-06 18:06:38 +00002730// PHINode simplification
2731//
Chris Lattner7e708292002-06-25 16:13:24 +00002732Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner60921c92003-12-19 05:58:40 +00002733 if (Value *V = hasConstantValue(&PN))
2734 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00002735
2736 // If the only user of this instruction is a cast instruction, and all of the
2737 // incoming values are constants, change this PHI to merge together the casted
2738 // constants.
2739 if (PN.hasOneUse())
2740 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2741 if (CI->getType() != PN.getType()) { // noop casts will be folded
2742 bool AllConstant = true;
2743 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2744 if (!isa<Constant>(PN.getIncomingValue(i))) {
2745 AllConstant = false;
2746 break;
2747 }
2748 if (AllConstant) {
2749 // Make a new PHI with all casted values.
2750 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2751 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2752 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2753 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2754 PN.getIncomingBlock(i));
2755 }
2756
2757 // Update the cast instruction.
2758 CI->setOperand(0, New);
2759 WorkList.push_back(CI); // revisit the cast instruction to fold.
2760 WorkList.push_back(New); // Make sure to revisit the new Phi
2761 return &PN; // PN is now dead!
2762 }
2763 }
Chris Lattner60921c92003-12-19 05:58:40 +00002764 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00002765}
2766
Chris Lattner28977af2004-04-05 01:30:19 +00002767static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
2768 Instruction *InsertPoint,
2769 InstCombiner *IC) {
2770 unsigned PS = IC->getTargetData().getPointerSize();
2771 const Type *VTy = V->getType();
2772 Instruction *Cast;
2773 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
2774 // We must insert a cast to ensure we sign-extend.
2775 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
2776 V->getName()), *InsertPoint);
2777 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
2778 *InsertPoint);
2779}
2780
Chris Lattnera1be5662002-05-02 17:06:02 +00002781
Chris Lattner7e708292002-06-25 16:13:24 +00002782Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00002783 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00002784 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00002785 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002786 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00002787 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002788
2789 bool HasZeroPointerIndex = false;
2790 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2791 HasZeroPointerIndex = C->isNullValue();
2792
2793 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00002794 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00002795
Chris Lattner28977af2004-04-05 01:30:19 +00002796 // Eliminate unneeded casts for indices.
2797 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002798 gep_type_iterator GTI = gep_type_begin(GEP);
2799 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
2800 if (isa<SequentialType>(*GTI)) {
2801 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
2802 Value *Src = CI->getOperand(0);
2803 const Type *SrcTy = Src->getType();
2804 const Type *DestTy = CI->getType();
2805 if (Src->getType()->isInteger()) {
2806 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
2807 // We can always eliminate a cast from ulong or long to the other.
2808 // We can always eliminate a cast from uint to int or the other on
2809 // 32-bit pointer platforms.
2810 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
2811 MadeChange = true;
2812 GEP.setOperand(i, Src);
2813 }
2814 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2815 SrcTy->getPrimitiveSize() == 4) {
2816 // We can always eliminate a cast from int to [u]long. We can
2817 // eliminate a cast from uint to [u]long iff the target is a 32-bit
2818 // pointer target.
2819 if (SrcTy->isSigned() ||
2820 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
2821 MadeChange = true;
2822 GEP.setOperand(i, Src);
2823 }
Chris Lattner28977af2004-04-05 01:30:19 +00002824 }
2825 }
2826 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002827 // If we are using a wider index than needed for this platform, shrink it
2828 // to what we need. If the incoming value needs a cast instruction,
2829 // insert it. This explicit cast can make subsequent optimizations more
2830 // obvious.
2831 Value *Op = GEP.getOperand(i);
2832 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00002833 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00002834 GEP.setOperand(i, ConstantExpr::getCast(C,
2835 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00002836 MadeChange = true;
2837 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00002838 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
2839 Op->getName()), GEP);
2840 GEP.setOperand(i, Op);
2841 MadeChange = true;
2842 }
Chris Lattner67769e52004-07-20 01:48:15 +00002843
2844 // If this is a constant idx, make sure to canonicalize it to be a signed
2845 // operand, otherwise CSE and other optimizations are pessimized.
2846 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
2847 GEP.setOperand(i, ConstantExpr::getCast(CUI,
2848 CUI->getType()->getSignedVersion()));
2849 MadeChange = true;
2850 }
Chris Lattner28977af2004-04-05 01:30:19 +00002851 }
2852 if (MadeChange) return &GEP;
2853
Chris Lattner90ac28c2002-08-02 19:29:35 +00002854 // Combine Indices - If the source pointer to this getelementptr instruction
2855 // is a getelementptr instruction, combine the indices of the two
2856 // getelementptr instructions into a single instruction.
2857 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00002858 std::vector<Value*> SrcGEPOperands;
Chris Lattner620ce142004-05-07 22:09:22 +00002859 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00002860 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner620ce142004-05-07 22:09:22 +00002861 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerebd985c2004-03-25 22:59:29 +00002862 if (CE->getOpcode() == Instruction::GetElementPtr)
2863 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
2864 }
2865
2866 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00002867 // Note that if our source is a gep chain itself that we wait for that
2868 // chain to be resolved before we perform this transformation. This
2869 // avoids us creating a TON of code in some cases.
2870 //
2871 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
2872 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
2873 return 0; // Wait until our source is folded to completion.
2874
Chris Lattner90ac28c2002-08-02 19:29:35 +00002875 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00002876
2877 // Find out whether the last index in the source GEP is a sequential idx.
2878 bool EndsWithSequential = false;
2879 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
2880 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00002881 EndsWithSequential = !isa<StructType>(*I);
Chris Lattner8a2a3112001-12-14 16:52:21 +00002882
Chris Lattner90ac28c2002-08-02 19:29:35 +00002883 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00002884 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00002885 // Replace: gep (gep %P, long B), long A, ...
2886 // With: T = long A+B; gep %P, T, ...
2887 //
Chris Lattner620ce142004-05-07 22:09:22 +00002888 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00002889 if (SO1 == Constant::getNullValue(SO1->getType())) {
2890 Sum = GO1;
2891 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2892 Sum = SO1;
2893 } else {
2894 // If they aren't the same type, convert both to an integer of the
2895 // target's pointer size.
2896 if (SO1->getType() != GO1->getType()) {
2897 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
2898 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
2899 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
2900 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
2901 } else {
2902 unsigned PS = TD->getPointerSize();
2903 Instruction *Cast;
2904 if (SO1->getType()->getPrimitiveSize() == PS) {
2905 // Convert GO1 to SO1's type.
2906 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
2907
2908 } else if (GO1->getType()->getPrimitiveSize() == PS) {
2909 // Convert SO1 to GO1's type.
2910 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
2911 } else {
2912 const Type *PT = TD->getIntPtrType();
2913 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
2914 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
2915 }
2916 }
2917 }
Chris Lattner620ce142004-05-07 22:09:22 +00002918 if (isa<Constant>(SO1) && isa<Constant>(GO1))
2919 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
2920 else {
Chris Lattner48595f12004-06-10 02:07:29 +00002921 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
2922 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00002923 }
Chris Lattner28977af2004-04-05 01:30:19 +00002924 }
Chris Lattner620ce142004-05-07 22:09:22 +00002925
2926 // Recycle the GEP we already have if possible.
2927 if (SrcGEPOperands.size() == 2) {
2928 GEP.setOperand(0, SrcGEPOperands[0]);
2929 GEP.setOperand(1, Sum);
2930 return &GEP;
2931 } else {
2932 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2933 SrcGEPOperands.end()-1);
2934 Indices.push_back(Sum);
2935 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
2936 }
Chris Lattner28977af2004-04-05 01:30:19 +00002937 } else if (isa<Constant>(*GEP.idx_begin()) &&
2938 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerebd985c2004-03-25 22:59:29 +00002939 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00002940 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00002941 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2942 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00002943 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
2944 }
2945
2946 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00002947 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00002948
Chris Lattner620ce142004-05-07 22:09:22 +00002949 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00002950 // GEP of global variable. If all of the indices for this GEP are
2951 // constants, we can promote this to a constexpr instead of an instruction.
2952
2953 // Scan for nonconstants...
2954 std::vector<Constant*> Indices;
2955 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2956 for (; I != E && isa<Constant>(*I); ++I)
2957 Indices.push_back(cast<Constant>(*I));
2958
2959 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00002960 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00002961
2962 // Replace all uses of the GEP with the new constexpr...
2963 return ReplaceInstUsesWith(GEP, CE);
2964 }
Chris Lattner620ce142004-05-07 22:09:22 +00002965 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattnerc6bd1952004-02-22 05:25:17 +00002966 if (CE->getOpcode() == Instruction::Cast) {
2967 if (HasZeroPointerIndex) {
2968 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2969 // into : GEP [10 x ubyte]* X, long 0, ...
2970 //
2971 // This occurs when the program declares an array extern like "int X[];"
2972 //
2973 Constant *X = CE->getOperand(0);
2974 const PointerType *CPTy = cast<PointerType>(CE->getType());
2975 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2976 if (const ArrayType *XATy =
2977 dyn_cast<ArrayType>(XTy->getElementType()))
2978 if (const ArrayType *CATy =
2979 dyn_cast<ArrayType>(CPTy->getElementType()))
2980 if (CATy->getElementType() == XATy->getElementType()) {
2981 // At this point, we know that the cast source type is a pointer
2982 // to an array of the same type as the destination pointer
2983 // array. Because the array type is never stepped over (there
2984 // is a leading zero) we can fold the cast into this GEP.
2985 GEP.setOperand(0, X);
2986 return &GEP;
2987 }
2988 }
2989 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00002990 }
2991
Chris Lattner8a2a3112001-12-14 16:52:21 +00002992 return 0;
2993}
2994
Chris Lattner0864acf2002-11-04 16:18:53 +00002995Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2996 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
2997 if (AI.isArrayAllocation()) // Check C != 1
2998 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
2999 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00003000 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00003001
3002 // Create and insert the replacement instruction...
3003 if (isa<MallocInst>(AI))
Chris Lattner7c881df2004-03-19 06:08:10 +00003004 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00003005 else {
3006 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner7c881df2004-03-19 06:08:10 +00003007 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00003008 }
Chris Lattner7c881df2004-03-19 06:08:10 +00003009
3010 InsertNewInstBefore(New, AI);
Chris Lattner0864acf2002-11-04 16:18:53 +00003011
3012 // Scan to the end of the allocation instructions, to skip over a block of
3013 // allocas if possible...
3014 //
3015 BasicBlock::iterator It = New;
3016 while (isa<AllocationInst>(*It)) ++It;
3017
3018 // Now that I is pointing to the first non-allocation-inst in the block,
3019 // insert our getelementptr instruction...
3020 //
Chris Lattner28977af2004-04-05 01:30:19 +00003021 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner0864acf2002-11-04 16:18:53 +00003022 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3023
3024 // Now make everything use the getelementptr instead of the original
3025 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00003026 return ReplaceInstUsesWith(AI, V);
Chris Lattner0864acf2002-11-04 16:18:53 +00003027 }
Chris Lattner7c881df2004-03-19 06:08:10 +00003028
3029 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3030 // Note that we only do this for alloca's, because malloc should allocate and
3031 // return a unique pointer, even for a zero byte allocation.
Chris Lattnercf27afb2004-07-02 22:55:47 +00003032 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3033 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00003034 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3035
Chris Lattner0864acf2002-11-04 16:18:53 +00003036 return 0;
3037}
3038
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003039Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3040 Value *Op = FI.getOperand(0);
3041
3042 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3043 if (CastInst *CI = dyn_cast<CastInst>(Op))
3044 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3045 FI.setOperand(0, CI->getOperand(0));
3046 return &FI;
3047 }
3048
Chris Lattner6160e852004-02-28 04:57:37 +00003049 // If we have 'free null' delete the instruction. This can happen in stl code
3050 // when lots of inlining happens.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003051 if (isa<ConstantPointerNull>(Op))
3052 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00003053
Chris Lattner67b1e1b2003-12-07 01:24:23 +00003054 return 0;
3055}
3056
3057
Chris Lattner833b8a42003-06-26 05:06:25 +00003058/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3059/// constantexpr, return the constant value being addressed by the constant
3060/// expression, or null if something is funny.
3061///
3062static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner28977af2004-04-05 01:30:19 +00003063 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner833b8a42003-06-26 05:06:25 +00003064 return 0; // Do not allow stepping over the value!
3065
3066 // Loop over all of the operands, tracking down which value we are
3067 // addressing...
Chris Lattnere1368ae2004-05-27 17:30:27 +00003068 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3069 for (++I; I != E; ++I)
3070 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3071 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3072 assert(CU->getValue() < STy->getNumElements() &&
3073 "Struct index out of range!");
3074 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +00003075 C = CS->getOperand(CU->getValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00003076 } else if (isa<ConstantAggregateZero>(C)) {
3077 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3078 } else {
3079 return 0;
3080 }
3081 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3082 const ArrayType *ATy = cast<ArrayType>(*I);
3083 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3084 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos15876bb2004-08-04 08:44:43 +00003085 C = CA->getOperand(CI->getRawValue());
Chris Lattnere1368ae2004-05-27 17:30:27 +00003086 else if (isa<ConstantAggregateZero>(C))
3087 C = Constant::getNullValue(ATy->getElementType());
3088 else
3089 return 0;
3090 } else {
Chris Lattner833b8a42003-06-26 05:06:25 +00003091 return 0;
Chris Lattnere1368ae2004-05-27 17:30:27 +00003092 }
Chris Lattner833b8a42003-06-26 05:06:25 +00003093 return C;
3094}
3095
Chris Lattnerb89e0712004-07-13 01:49:43 +00003096static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3097 User *CI = cast<User>(LI.getOperand(0));
3098
3099 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3100 if (const PointerType *SrcTy =
3101 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3102 const Type *SrcPTy = SrcTy->getElementType();
3103 if (SrcPTy->isSized() && DestPTy->isSized() &&
3104 IC.getTargetData().getTypeSize(SrcPTy) ==
3105 IC.getTargetData().getTypeSize(DestPTy) &&
3106 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3107 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3108 // Okay, we are casting from one integer or pointer type to another of
3109 // the same size. Instead of casting the pointer before the load, cast
3110 // the result of the loaded value.
3111 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerc10aced2004-09-19 18:43:46 +00003112 CI->getName(),
3113 LI.isVolatile()),LI);
Chris Lattnerb89e0712004-07-13 01:49:43 +00003114 // Now cast the result of the load.
3115 return new CastInst(NewLoad, LI.getType());
3116 }
3117 }
3118 return 0;
3119}
3120
Chris Lattnerc10aced2004-09-19 18:43:46 +00003121/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00003122/// from this value cannot trap. If it is not obviously safe to load from the
3123/// specified pointer, we do a quick local scan of the basic block containing
3124/// ScanFrom, to determine if the address is already accessed.
3125static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3126 // If it is an alloca or global variable, it is always safe to load from.
3127 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3128
3129 // Otherwise, be a little bit agressive by scanning the local block where we
3130 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003131 // from/to. If so, the previous load or store would have already trapped,
3132 // so there is no harm doing an extra load (also, CSE will later eliminate
3133 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00003134 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3135
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003136 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00003137 --BBI;
3138
3139 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3140 if (LI->getOperand(0) == V) return true;
3141 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3142 if (SI->getOperand(1) == V) return true;
3143
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00003144 }
Chris Lattner8a375202004-09-19 19:18:10 +00003145 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00003146}
3147
Chris Lattner833b8a42003-06-26 05:06:25 +00003148Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3149 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00003150
Chris Lattnerd9955aa2004-04-14 03:28:36 +00003151 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerc10aced2004-09-19 18:43:46 +00003152 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattnerd9955aa2004-04-14 03:28:36 +00003153 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner833b8a42003-06-26 05:06:25 +00003154
3155 // Instcombine load (constant global) into the value loaded...
3156 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00003157 if (GV->isConstant() && !GV->isExternal())
Chris Lattner833b8a42003-06-26 05:06:25 +00003158 return ReplaceInstUsesWith(LI, GV->getInitializer());
3159
3160 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3161 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattnerb89e0712004-07-13 01:49:43 +00003162 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer8863f182004-07-18 00:38:32 +00003163 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3164 if (GV->isConstant() && !GV->isExternal())
3165 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3166 return ReplaceInstUsesWith(LI, V);
Chris Lattnerb89e0712004-07-13 01:49:43 +00003167 } else if (CE->getOpcode() == Instruction::Cast) {
3168 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3169 return Res;
3170 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00003171
3172 // load (cast X) --> cast (load X) iff safe
Chris Lattnerb89e0712004-07-13 01:49:43 +00003173 if (CastInst *CI = dyn_cast<CastInst>(Op))
3174 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3175 return Res;
Chris Lattnerf499eac2004-04-08 20:39:49 +00003176
Chris Lattnerc10aced2004-09-19 18:43:46 +00003177 if (!LI.isVolatile() && Op->hasOneUse()) {
3178 // Change select and PHI nodes to select values instead of addresses: this
3179 // helps alias analysis out a lot, allows many others simplifications, and
3180 // exposes redundancy in the code.
3181 //
3182 // Note that we cannot do the transformation unless we know that the
3183 // introduced loads cannot trap! Something like this is valid as long as
3184 // the condition is always false: load (select bool %C, int* null, int* %G),
3185 // but it would not be valid if we transformed it to load from null
3186 // unconditionally.
3187 //
3188 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3189 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00003190 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3191 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00003192 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003193 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00003194 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003195 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00003196 return new SelectInst(SI->getCondition(), V1, V2);
3197 }
3198
Chris Lattner684fe212004-09-23 15:46:00 +00003199 // load (select (cond, null, P)) -> load P
3200 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3201 if (C->isNullValue()) {
3202 LI.setOperand(0, SI->getOperand(2));
3203 return &LI;
3204 }
3205
3206 // load (select (cond, P, null)) -> load P
3207 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3208 if (C->isNullValue()) {
3209 LI.setOperand(0, SI->getOperand(1));
3210 return &LI;
3211 }
3212
Chris Lattnerc10aced2004-09-19 18:43:46 +00003213 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3214 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003215 bool Safe = PN->getParent() == LI.getParent();
3216
3217 // Scan all of the instructions between the PHI and the load to make
3218 // sure there are no instructions that might possibly alter the value
3219 // loaded from the PHI.
3220 if (Safe) {
3221 BasicBlock::iterator I = &LI;
3222 for (--I; !isa<PHINode>(I); --I)
3223 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3224 Safe = false;
3225 break;
3226 }
3227 }
3228
3229 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00003230 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003231 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00003232 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00003233
Chris Lattnerc10aced2004-09-19 18:43:46 +00003234 if (Safe) {
3235 // Create the PHI.
3236 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3237 InsertNewInstBefore(NewPN, *PN);
3238 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3239
3240 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3241 BasicBlock *BB = PN->getIncomingBlock(i);
3242 Value *&TheLoad = LoadMap[BB];
3243 if (TheLoad == 0) {
3244 Value *InVal = PN->getIncomingValue(i);
3245 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3246 InVal->getName()+".val"),
3247 *BB->getTerminator());
3248 }
3249 NewPN->addIncoming(TheLoad, BB);
3250 }
3251 return ReplaceInstUsesWith(LI, NewPN);
3252 }
3253 }
3254 }
Chris Lattner833b8a42003-06-26 05:06:25 +00003255 return 0;
3256}
3257
3258
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003259Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3260 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003261 Value *X;
3262 BasicBlock *TrueDest;
3263 BasicBlock *FalseDest;
3264 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3265 !isa<Constant>(X)) {
3266 // Swap Destinations and condition...
3267 BI.setCondition(X);
3268 BI.setSuccessor(0, FalseDest);
3269 BI.setSuccessor(1, TrueDest);
3270 return &BI;
3271 }
3272
3273 // Cannonicalize setne -> seteq
3274 Instruction::BinaryOps Op; Value *Y;
3275 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3276 TrueDest, FalseDest)))
3277 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3278 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3279 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3280 std::string Name = I->getName(); I->setName("");
3281 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3282 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00003283 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003284 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00003285 BI.setSuccessor(0, FalseDest);
3286 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003287 removeFromWorkList(I);
3288 I->getParent()->getInstList().erase(I);
3289 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00003290 return &BI;
3291 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003292
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00003293 return 0;
3294}
Chris Lattner0864acf2002-11-04 16:18:53 +00003295
Chris Lattner46238a62004-07-03 00:26:11 +00003296Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3297 Value *Cond = SI.getCondition();
3298 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3299 if (I->getOpcode() == Instruction::Add)
3300 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3301 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3302 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3303 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3304 AddRHS));
3305 SI.setOperand(0, I->getOperand(0));
3306 WorkList.push_back(I);
3307 return &SI;
3308 }
3309 }
3310 return 0;
3311}
3312
Chris Lattner8a2a3112001-12-14 16:52:21 +00003313
Chris Lattner62b14df2002-09-02 04:59:56 +00003314void InstCombiner::removeFromWorkList(Instruction *I) {
3315 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3316 WorkList.end());
3317}
3318
Chris Lattner7e708292002-06-25 16:13:24 +00003319bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003320 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00003321 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00003322
Chris Lattner216d4d82004-05-01 23:19:52 +00003323 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3324 WorkList.push_back(&*i);
Chris Lattner6ffe5512004-04-27 15:13:33 +00003325
Chris Lattner8a2a3112001-12-14 16:52:21 +00003326
3327 while (!WorkList.empty()) {
3328 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3329 WorkList.pop_back();
3330
Misha Brukmana3bbcb52002-10-29 23:06:16 +00003331 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00003332 // Check to see if we can DIE the instruction...
3333 if (isInstructionTriviallyDead(I)) {
3334 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00003335 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003336 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00003337 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00003338
3339 I->getParent()->getInstList().erase(I);
3340 removeFromWorkList(I);
3341 continue;
3342 }
Chris Lattner62b14df2002-09-02 04:59:56 +00003343
Misha Brukmana3bbcb52002-10-29 23:06:16 +00003344 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00003345 if (Constant *C = ConstantFoldInstruction(I)) {
3346 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00003347 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00003348 ReplaceInstUsesWith(*I, C);
3349
Chris Lattner62b14df2002-09-02 04:59:56 +00003350 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00003351 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00003352 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003353 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00003354 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00003355
Chris Lattner8a2a3112001-12-14 16:52:21 +00003356 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00003357 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00003358 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003359 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003360 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00003361 DEBUG(std::cerr << "IC: Old = " << *I
3362 << " New = " << *Result);
3363
Chris Lattnerf523d062004-06-09 05:08:07 +00003364 // Everything uses the new instruction now.
3365 I->replaceAllUsesWith(Result);
3366
3367 // Push the new instruction and any users onto the worklist.
3368 WorkList.push_back(Result);
3369 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003370
3371 // Move the name to the new instruction first...
3372 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00003373 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003374
3375 // Insert the new instruction into the basic block...
3376 BasicBlock *InstParent = I->getParent();
3377 InstParent->getInstList().insert(I, Result);
3378
Chris Lattner00d51312004-05-01 23:27:23 +00003379 // Make sure that we reprocess all operands now that we reduced their
3380 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00003381 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3382 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3383 WorkList.push_back(OpI);
3384
Chris Lattnerf523d062004-06-09 05:08:07 +00003385 // Instructions can end up on the worklist more than once. Make sure
3386 // we do not process an instruction that has been deleted.
3387 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00003388
3389 // Erase the old instruction.
3390 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003391 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00003392 DEBUG(std::cerr << "IC: MOD = " << *I);
3393
Chris Lattner90ac28c2002-08-02 19:29:35 +00003394 // If the instruction was modified, it's possible that it is now dead.
3395 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00003396 if (isInstructionTriviallyDead(I)) {
3397 // Make sure we process all operands now that we are reducing their
3398 // use counts.
3399 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3400 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3401 WorkList.push_back(OpI);
3402
3403 // Instructions may end up in the worklist more than once. Erase all
3404 // occurrances of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00003405 removeFromWorkList(I);
Chris Lattner00d51312004-05-01 23:27:23 +00003406 I->getParent()->getInstList().erase(I);
Chris Lattnerf523d062004-06-09 05:08:07 +00003407 } else {
3408 WorkList.push_back(Result);
3409 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00003410 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00003411 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003412 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00003413 }
3414 }
3415
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003416 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003417}
3418
Brian Gaeke96d4bf72004-07-27 17:43:21 +00003419FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003420 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00003421}
Brian Gaeked0fde302003-11-11 22:41:34 +00003422