blob: 5af9aee165d33da39b21898caf61f0e75ec58d65 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
46#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000047#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000049#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000050#include "llvm/Support/Debug.h"
51#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000052#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000053using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000054using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000055
Chris Lattner260ab202002-04-18 17:39:14 +000056namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000057 Statistic<> NumCombined ("instcombine", "Number of insts combined");
58 Statistic<> NumConstProp("instcombine", "Number of constant folds");
59 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
60
Chris Lattnerc8e66542002-04-27 06:56:12 +000061 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000062 public InstVisitor<InstCombiner, Instruction*> {
63 // Worklist of all of the instructions that need to be simplified.
64 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000065 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000066
Chris Lattner51ea1272004-02-28 05:22:00 +000067 /// AddUsersToWorkList - When an instruction is simplified, add all users of
68 /// the instruction to the work lists because they might get more simplified
69 /// now.
70 ///
71 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000072 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000073 UI != UE; ++UI)
74 WorkList.push_back(cast<Instruction>(*UI));
75 }
76
Chris Lattner51ea1272004-02-28 05:22:00 +000077 /// AddUsesToWorkList - When an instruction is simplified, add operands to
78 /// the work lists because they might get more simplified now.
79 ///
80 void AddUsesToWorkList(Instruction &I) {
81 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83 WorkList.push_back(Op);
84 }
85
Chris Lattner99f48c62002-09-02 04:59:56 +000086 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000088 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000089 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000090
Chris Lattnerf12cc842002-04-28 21:27:06 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000092 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000093 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000094 }
95
Chris Lattner69193f92004-04-05 01:30:19 +000096 TargetData &getTargetData() const { return *TD; }
97
Chris Lattner260ab202002-04-18 17:39:14 +000098 // Visitation implementation - Implement instruction combining for different
99 // instruction types. The semantics are as follows:
100 // Return Value:
101 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000102 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // otherwise - Change was made, replace I with returned instruction
104 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000105 Instruction *visitAdd(BinaryOperator &I);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitMul(BinaryOperator &I);
108 Instruction *visitDiv(BinaryOperator &I);
109 Instruction *visitRem(BinaryOperator &I);
110 Instruction *visitAnd(BinaryOperator &I);
111 Instruction *visitOr (BinaryOperator &I);
112 Instruction *visitXor(BinaryOperator &I);
113 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000114 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000115 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000116 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000121 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000122 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000123 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000124 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000125 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000126
127 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000129
Chris Lattner970c33a2003-06-19 17:00:31 +0000130 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000131 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 bool transformConstExprCastCall(CallSite CS);
133
Chris Lattner69193f92004-04-05 01:30:19 +0000134 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000135 // InsertNewInstBefore - insert an instruction New before instruction Old
136 // in the program. Add the new instruction to the worklist.
137 //
Chris Lattner623826c2004-09-28 21:48:02 +0000138 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000139 assert(New && New->getParent() == 0 &&
140 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000141 BasicBlock *BB = Old.getParent();
142 BB->getInstList().insert(&Old, New); // Insert inst
143 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000144 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145 }
146
Chris Lattner7e794272004-09-24 15:21:34 +0000147 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
148 /// This also adds the cast to the worklist. Finally, this returns the
149 /// cast.
150 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
151 if (V->getType() == Ty) return V;
152
153 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
154 WorkList.push_back(C);
155 return C;
156 }
157
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000158 // ReplaceInstUsesWith - This method is to be used when an instruction is
159 // found to be dead, replacable with another preexisting expression. Here
160 // we add all uses of I to the worklist, replace all uses of I with the new
161 // value, then return I, so that the inst combiner will know that I was
162 // modified.
163 //
164 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000165 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000166 if (&I != V) {
167 I.replaceAllUsesWith(V);
168 return &I;
169 } else {
170 // If we are replacing the instruction with itself, this must be in a
171 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000172 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000173 return &I;
174 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000175 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000176
177 // EraseInstFromFunction - When dealing with an instruction that has side
178 // effects or produces a void value, we can't rely on DCE to delete the
179 // instruction. Instead, visit methods should return the value returned by
180 // this function.
181 Instruction *EraseInstFromFunction(Instruction &I) {
182 assert(I.use_empty() && "Cannot erase instruction that is used!");
183 AddUsesToWorkList(I);
184 removeFromWorkList(&I);
185 I.getParent()->getInstList().erase(&I);
186 return 0; // Don't do anything with FI
187 }
188
189
Chris Lattner3ac7c262003-08-13 20:16:26 +0000190 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000191 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
192 /// InsertBefore instruction. This is specialized a bit to avoid inserting
193 /// casts that are known to not do anything...
194 ///
195 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
196 Instruction *InsertBefore);
197
Chris Lattner7fb29e12003-03-11 00:12:48 +0000198 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000199 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000200 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000201
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000202
203 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
204 // PHI node as operand #0, see if we can fold the instruction into the PHI
205 // (which is only possible if all operands to the PHI are constants).
206 Instruction *FoldOpIntoPhi(Instruction &I);
207
Chris Lattnerba1cb382003-09-19 17:17:26 +0000208 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
209 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000210
211 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
212 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000213 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000214
Chris Lattnerc8b70922002-07-26 21:12:46 +0000215 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000216}
217
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000218// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000219// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000220static unsigned getComplexity(Value *V) {
221 if (isa<Instruction>(V)) {
222 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000223 return 3;
224 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000225 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000226 if (isa<Argument>(V)) return 3;
227 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000228}
Chris Lattner260ab202002-04-18 17:39:14 +0000229
Chris Lattner7fb29e12003-03-11 00:12:48 +0000230// isOnlyUse - Return true if this instruction will be deleted if we stop using
231// it.
232static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000233 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000234}
235
Chris Lattnere79e8542004-02-23 06:38:22 +0000236// getPromotedType - Return the specified type promoted as it would be to pass
237// though a va_arg area...
238static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000239 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000240 case Type::SByteTyID:
241 case Type::ShortTyID: return Type::IntTy;
242 case Type::UByteTyID:
243 case Type::UShortTyID: return Type::UIntTy;
244 case Type::FloatTyID: return Type::DoubleTy;
245 default: return Ty;
246 }
247}
248
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000249// SimplifyCommutative - This performs a few simplifications for commutative
250// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000251//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000252// 1. Order operands such that they are listed from right (least complex) to
253// left (most complex). This puts constants before unary operators before
254// binary operators.
255//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000256// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
257// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000258//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000259bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000260 bool Changed = false;
261 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
262 Changed = !I.swapOperands();
263
264 if (!I.isAssociative()) return Changed;
265 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000266 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
267 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
268 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000269 Constant *Folded = ConstantExpr::get(I.getOpcode(),
270 cast<Constant>(I.getOperand(1)),
271 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000272 I.setOperand(0, Op->getOperand(0));
273 I.setOperand(1, Folded);
274 return true;
275 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
276 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
277 isOnlyUse(Op) && isOnlyUse(Op1)) {
278 Constant *C1 = cast<Constant>(Op->getOperand(1));
279 Constant *C2 = cast<Constant>(Op1->getOperand(1));
280
281 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000282 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000283 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
284 Op1->getOperand(0),
285 Op1->getName(), &I);
286 WorkList.push_back(New);
287 I.setOperand(0, New);
288 I.setOperand(1, Folded);
289 return true;
290 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000291 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000292 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000293}
Chris Lattnerca081252001-12-14 16:52:21 +0000294
Chris Lattnerbb74e222003-03-10 23:06:50 +0000295// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
296// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000297//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000298static inline Value *dyn_castNegVal(Value *V) {
299 if (BinaryOperator::isNeg(V))
300 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
301
Chris Lattner9244df62003-04-30 22:19:10 +0000302 // Constants can be considered to be negated values if they can be folded...
303 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000304 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000305 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000306}
307
Chris Lattnerbb74e222003-03-10 23:06:50 +0000308static inline Value *dyn_castNotVal(Value *V) {
309 if (BinaryOperator::isNot(V))
310 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
311
312 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000313 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000314 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000315 return 0;
316}
317
Chris Lattner7fb29e12003-03-11 00:12:48 +0000318// dyn_castFoldableMul - If this value is a multiply that can be folded into
319// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000320// non-constant operand of the multiply, and set CST to point to the multiplier.
321// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000322//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000323static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000324 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000325 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000326 if (I->getOpcode() == Instruction::Mul)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000327 if (CST = dyn_cast<ConstantInt>(I->getOperand(1)))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000328 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000329 if (I->getOpcode() == Instruction::Shl)
330 if (CST = dyn_cast<ConstantInt>(I->getOperand(1))) {
331 // The multiplier is really 1 << CST.
332 Constant *One = ConstantInt::get(V->getType(), 1);
333 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
334 return I->getOperand(0);
335 }
336 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000338}
Chris Lattner31ae8632002-08-14 17:51:49 +0000339
Chris Lattner3082c5a2003-02-18 19:28:33 +0000340// Log2 - Calculate the log base 2 for the specified value if it is exactly a
341// power of 2.
342static unsigned Log2(uint64_t Val) {
343 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
344 unsigned Count = 0;
345 while (Val != 1) {
346 if (Val & 1) return 0; // Multiple bits set?
347 Val >>= 1;
348 ++Count;
349 }
350 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000351}
352
Chris Lattner623826c2004-09-28 21:48:02 +0000353// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000354static ConstantInt *AddOne(ConstantInt *C) {
355 return cast<ConstantInt>(ConstantExpr::getAdd(C,
356 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000357}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000358static ConstantInt *SubOne(ConstantInt *C) {
359 return cast<ConstantInt>(ConstantExpr::getSub(C,
360 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000361}
362
363// isTrueWhenEqual - Return true if the specified setcondinst instruction is
364// true when both operands are equal...
365//
366static bool isTrueWhenEqual(Instruction &I) {
367 return I.getOpcode() == Instruction::SetEQ ||
368 I.getOpcode() == Instruction::SetGE ||
369 I.getOpcode() == Instruction::SetLE;
370}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000371
372/// AssociativeOpt - Perform an optimization on an associative operator. This
373/// function is designed to check a chain of associative operators for a
374/// potential to apply a certain optimization. Since the optimization may be
375/// applicable if the expression was reassociated, this checks the chain, then
376/// reassociates the expression as necessary to expose the optimization
377/// opportunity. This makes use of a special Functor, which must define
378/// 'shouldApply' and 'apply' methods.
379///
380template<typename Functor>
381Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
382 unsigned Opcode = Root.getOpcode();
383 Value *LHS = Root.getOperand(0);
384
385 // Quick check, see if the immediate LHS matches...
386 if (F.shouldApply(LHS))
387 return F.apply(Root);
388
389 // Otherwise, if the LHS is not of the same opcode as the root, return.
390 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000391 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000392 // Should we apply this transform to the RHS?
393 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
394
395 // If not to the RHS, check to see if we should apply to the LHS...
396 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
397 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
398 ShouldApply = true;
399 }
400
401 // If the functor wants to apply the optimization to the RHS of LHSI,
402 // reassociate the expression from ((? op A) op B) to (? op (A op B))
403 if (ShouldApply) {
404 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000405
406 // Now all of the instructions are in the current basic block, go ahead
407 // and perform the reassociation.
408 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
409
410 // First move the selected RHS to the LHS of the root...
411 Root.setOperand(0, LHSI->getOperand(1));
412
413 // Make what used to be the LHS of the root be the user of the root...
414 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000415 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000416 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
417 return 0;
418 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000419 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000420 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000421 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
422 BasicBlock::iterator ARI = &Root; ++ARI;
423 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
424 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000425
426 // Now propagate the ExtraOperand down the chain of instructions until we
427 // get to LHSI.
428 while (TmpLHSI != LHSI) {
429 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000430 // Move the instruction to immediately before the chain we are
431 // constructing to avoid breaking dominance properties.
432 NextLHSI->getParent()->getInstList().remove(NextLHSI);
433 BB->getInstList().insert(ARI, NextLHSI);
434 ARI = NextLHSI;
435
Chris Lattnerb8b97502003-08-13 19:01:45 +0000436 Value *NextOp = NextLHSI->getOperand(1);
437 NextLHSI->setOperand(1, ExtraOperand);
438 TmpLHSI = NextLHSI;
439 ExtraOperand = NextOp;
440 }
441
442 // Now that the instructions are reassociated, have the functor perform
443 // the transformation...
444 return F.apply(Root);
445 }
446
447 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
448 }
449 return 0;
450}
451
452
453// AddRHS - Implements: X + X --> X << 1
454struct AddRHS {
455 Value *RHS;
456 AddRHS(Value *rhs) : RHS(rhs) {}
457 bool shouldApply(Value *LHS) const { return LHS == RHS; }
458 Instruction *apply(BinaryOperator &Add) const {
459 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
460 ConstantInt::get(Type::UByteTy, 1));
461 }
462};
463
464// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
465// iff C1&C2 == 0
466struct AddMaskingAnd {
467 Constant *C2;
468 AddMaskingAnd(Constant *c) : C2(c) {}
469 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000470 ConstantInt *C1;
471 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
472 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000473 }
474 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000475 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000476 }
477};
478
Chris Lattner183b3362004-04-09 19:05:30 +0000479static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
480 InstCombiner *IC) {
481 // Figure out if the constant is the left or the right argument.
482 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
483 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000484
Chris Lattner183b3362004-04-09 19:05:30 +0000485 if (Constant *SOC = dyn_cast<Constant>(SO)) {
486 if (ConstIsRHS)
487 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
488 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
489 }
490
491 Value *Op0 = SO, *Op1 = ConstOperand;
492 if (!ConstIsRHS)
493 std::swap(Op0, Op1);
494 Instruction *New;
495 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
496 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
497 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
498 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000499 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000500 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000501 abort();
502 }
Chris Lattner183b3362004-04-09 19:05:30 +0000503 return IC->InsertNewInstBefore(New, BI);
504}
505
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000506
507/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
508/// node as operand #0, see if we can fold the instruction into the PHI (which
509/// is only possible if all operands to the PHI are constants).
510Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
511 PHINode *PN = cast<PHINode>(I.getOperand(0));
512 if (!PN->hasOneUse()) return 0;
513
514 // Check to see if all of the operands of the PHI are constants. If not, we
515 // cannot do the transformation.
516 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
517 if (!isa<Constant>(PN->getIncomingValue(i)))
518 return 0;
519
520 // Okay, we can do the transformation: create the new PHI node.
521 PHINode *NewPN = new PHINode(I.getType(), I.getName());
522 I.setName("");
523 NewPN->op_reserve(PN->getNumOperands());
524 InsertNewInstBefore(NewPN, *PN);
525
526 // Next, add all of the operands to the PHI.
527 if (I.getNumOperands() == 2) {
528 Constant *C = cast<Constant>(I.getOperand(1));
529 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
530 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
531 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
532 PN->getIncomingBlock(i));
533 }
534 } else {
535 assert(isa<CastInst>(I) && "Unary op should be a cast!");
536 const Type *RetTy = I.getType();
537 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
538 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
539 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
540 PN->getIncomingBlock(i));
541 }
542 }
543 return ReplaceInstUsesWith(I, NewPN);
544}
545
Chris Lattner183b3362004-04-09 19:05:30 +0000546// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
547// constant as the other operand, try to fold the binary operator into the
548// select arguments.
549static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
550 InstCombiner *IC) {
551 // Don't modify shared select instructions
552 if (!SI->hasOneUse()) return 0;
553 Value *TV = SI->getOperand(1);
554 Value *FV = SI->getOperand(2);
555
556 if (isa<Constant>(TV) || isa<Constant>(FV)) {
557 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
558 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
559
560 return new SelectInst(SI->getCondition(), SelectTrueVal,
561 SelectFalseVal);
562 }
563 return 0;
564}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000565
Chris Lattner113f4f42002-06-25 16:13:24 +0000566Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000567 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000568 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000569
Chris Lattnercf4a9962004-04-10 22:01:55 +0000570 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000571 // X + undef -> undef
572 if (isa<UndefValue>(RHS))
573 return ReplaceInstUsesWith(I, RHS);
574
Chris Lattnercf4a9962004-04-10 22:01:55 +0000575 // X + 0 --> X
576 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
577 RHSC->isNullValue())
578 return ReplaceInstUsesWith(I, LHS);
579
580 // X + (signbit) --> X ^ signbit
581 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
582 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
583 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000584 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000585 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000586 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000587
588 if (isa<PHINode>(LHS))
589 if (Instruction *NV = FoldOpIntoPhi(I))
590 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000591 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000592
Chris Lattnerb8b97502003-08-13 19:01:45 +0000593 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000594 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000595 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000596 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000597
Chris Lattner147e9752002-05-08 22:46:53 +0000598 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000599 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000600 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000601
602 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000603 if (!isa<Constant>(RHS))
604 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000605 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000606
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000607 ConstantInt *C2;
608 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
609 if (X == RHS) // X*C + X --> X * (C+1)
610 return BinaryOperator::createMul(RHS, AddOne(C2));
611
612 // X*C1 + X*C2 --> X * (C1+C2)
613 ConstantInt *C1;
614 if (X == dyn_castFoldableMul(RHS, C1))
615 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000616 }
617
618 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000619 if (dyn_castFoldableMul(RHS, C2) == LHS)
620 return BinaryOperator::createMul(LHS, AddOne(C2));
621
Chris Lattner57c8d992003-02-18 19:57:07 +0000622
Chris Lattnerb8b97502003-08-13 19:01:45 +0000623 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000624 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000625 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000626
Chris Lattnerb9cde762003-10-02 15:11:26 +0000627 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000628 Value *X;
629 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
630 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
631 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000632 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000633
Chris Lattnerbff91d92004-10-08 05:07:56 +0000634 // (X & FF00) + xx00 -> (X+xx00) & FF00
635 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
636 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
637 if (Anded == CRHS) {
638 // See if all bits from the first bit set in the Add RHS up are included
639 // in the mask. First, get the rightmost bit.
640 uint64_t AddRHSV = CRHS->getRawValue();
641
642 // Form a mask of all bits from the lowest bit added through the top.
643 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
644 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
645
646 // See if the and mask includes all of these bits.
647 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
648
649 if (AddRHSHighBits == AddRHSHighBitsAnd) {
650 // Okay, the xform is safe. Insert the new add pronto.
651 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
652 LHS->getName()), I);
653 return BinaryOperator::createAnd(NewAdd, C2);
654 }
655 }
656 }
657
658
Chris Lattnerd4252a72004-07-30 07:50:03 +0000659 // Try to fold constant add into select arguments.
660 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
661 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
662 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000663 }
664
Chris Lattner113f4f42002-06-25 16:13:24 +0000665 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000666}
667
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000668// isSignBit - Return true if the value represented by the constant only has the
669// highest order bit set.
670static bool isSignBit(ConstantInt *CI) {
671 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
672 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
673}
674
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000675static unsigned getTypeSizeInBits(const Type *Ty) {
676 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
677}
678
Chris Lattner022167f2004-03-13 00:11:49 +0000679/// RemoveNoopCast - Strip off nonconverting casts from the value.
680///
681static Value *RemoveNoopCast(Value *V) {
682 if (CastInst *CI = dyn_cast<CastInst>(V)) {
683 const Type *CTy = CI->getType();
684 const Type *OpTy = CI->getOperand(0)->getType();
685 if (CTy->isInteger() && OpTy->isInteger()) {
686 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
687 return RemoveNoopCast(CI->getOperand(0));
688 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
689 return RemoveNoopCast(CI->getOperand(0));
690 }
691 return V;
692}
693
Chris Lattner113f4f42002-06-25 16:13:24 +0000694Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000695 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000696
Chris Lattnere6794492002-08-12 21:17:25 +0000697 if (Op0 == Op1) // sub X, X -> 0
698 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000699
Chris Lattnere6794492002-08-12 21:17:25 +0000700 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000701 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000702 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000703
Chris Lattner81a7a232004-10-16 18:11:37 +0000704 if (isa<UndefValue>(Op0))
705 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
706 if (isa<UndefValue>(Op1))
707 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
708
Chris Lattner8f2f5982003-11-05 01:06:05 +0000709 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
710 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000711 if (C->isAllOnesValue())
712 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000713
Chris Lattner8f2f5982003-11-05 01:06:05 +0000714 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000715 Value *X;
716 if (match(Op1, m_Not(m_Value(X))))
717 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000718 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000719 // -((uint)X >> 31) -> ((int)X >> 31)
720 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000721 if (C->isNullValue()) {
722 Value *NoopCastedRHS = RemoveNoopCast(Op1);
723 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000724 if (SI->getOpcode() == Instruction::Shr)
725 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
726 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000727 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000728 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000729 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000730 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000731 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000732 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000733 // Ok, the transformation is safe. Insert a cast of the incoming
734 // value, then the new shift, then the new cast.
735 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
736 SI->getOperand(0)->getName());
737 Value *InV = InsertNewInstBefore(FirstCast, I);
738 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
739 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000740 if (NewShift->getType() == I.getType())
741 return NewShift;
742 else {
743 InV = InsertNewInstBefore(NewShift, I);
744 return new CastInst(NewShift, I.getType());
745 }
Chris Lattner92295c52004-03-12 23:53:13 +0000746 }
747 }
Chris Lattner022167f2004-03-13 00:11:49 +0000748 }
Chris Lattner183b3362004-04-09 19:05:30 +0000749
750 // Try to fold constant sub into select arguments.
751 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
752 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
753 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000754
755 if (isa<PHINode>(Op0))
756 if (Instruction *NV = FoldOpIntoPhi(I))
757 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000758 }
759
Chris Lattner3082c5a2003-02-18 19:28:33 +0000760 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000761 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000762 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
763 // is not used by anyone else...
764 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000765 if (Op1I->getOpcode() == Instruction::Sub &&
766 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000767 // Swap the two operands of the subexpr...
768 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
769 Op1I->setOperand(0, IIOp1);
770 Op1I->setOperand(1, IIOp0);
771
772 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000773 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000774 }
775
776 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
777 //
778 if (Op1I->getOpcode() == Instruction::And &&
779 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
780 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
781
Chris Lattner396dbfe2004-06-09 05:08:07 +0000782 Value *NewNot =
783 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000784 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000785 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000786
Chris Lattner0aee4b72004-10-06 15:08:25 +0000787 // -(X sdiv C) -> (X sdiv -C)
788 if (Op1I->getOpcode() == Instruction::Div)
789 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
790 if (CSI->getValue() == 0)
791 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
792 return BinaryOperator::createDiv(Op1I->getOperand(0),
793 ConstantExpr::getNeg(DivRHS));
794
Chris Lattner57c8d992003-02-18 19:57:07 +0000795 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000796 ConstantInt *C2;
797 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
798 Constant *CP1 =
799 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000800 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000801 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000802 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000803
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000804
805 ConstantInt *C1;
806 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
807 if (X == Op1) { // X*C - X --> X * (C-1)
808 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
809 return BinaryOperator::createMul(Op1, CP1);
810 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000811
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000812 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
813 if (X == dyn_castFoldableMul(Op1, C2))
814 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
815 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000816 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000817}
818
Chris Lattnere79e8542004-02-23 06:38:22 +0000819/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
820/// really just returns true if the most significant (sign) bit is set.
821static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
822 if (RHS->getType()->isSigned()) {
823 // True if source is LHS < 0 or LHS <= -1
824 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
825 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
826 } else {
827 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
828 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
829 // the size of the integer type.
830 if (Opcode == Instruction::SetGE)
831 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
832 if (Opcode == Instruction::SetGT)
833 return RHSC->getValue() ==
834 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
835 }
836 return false;
837}
838
Chris Lattner113f4f42002-06-25 16:13:24 +0000839Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000840 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000841 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000842
Chris Lattner81a7a232004-10-16 18:11:37 +0000843 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
844 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
845
Chris Lattnere6794492002-08-12 21:17:25 +0000846 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000847 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
848 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000849
850 // ((X << C1)*C2) == (X * (C2 << C1))
851 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
852 if (SI->getOpcode() == Instruction::Shl)
853 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000854 return BinaryOperator::createMul(SI->getOperand(0),
855 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000856
Chris Lattnercce81be2003-09-11 22:24:54 +0000857 if (CI->isNullValue())
858 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
859 if (CI->equalsInt(1)) // X * 1 == X
860 return ReplaceInstUsesWith(I, Op0);
861 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000862 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000863
Chris Lattnercce81be2003-09-11 22:24:54 +0000864 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000865 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
866 return new ShiftInst(Instruction::Shl, Op0,
867 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000868 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000869 if (Op1F->isNullValue())
870 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000871
Chris Lattner3082c5a2003-02-18 19:28:33 +0000872 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
873 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
874 if (Op1F->getValue() == 1.0)
875 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
876 }
Chris Lattner183b3362004-04-09 19:05:30 +0000877
878 // Try to fold constant mul into select arguments.
879 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
880 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
881 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000882
883 if (isa<PHINode>(Op0))
884 if (Instruction *NV = FoldOpIntoPhi(I))
885 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000886 }
887
Chris Lattner934a64cf2003-03-10 23:23:04 +0000888 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
889 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000890 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000891
Chris Lattner2635b522004-02-23 05:39:21 +0000892 // If one of the operands of the multiply is a cast from a boolean value, then
893 // we know the bool is either zero or one, so this is a 'masking' multiply.
894 // See if we can simplify things based on how the boolean was originally
895 // formed.
896 CastInst *BoolCast = 0;
897 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
898 if (CI->getOperand(0)->getType() == Type::BoolTy)
899 BoolCast = CI;
900 if (!BoolCast)
901 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
902 if (CI->getOperand(0)->getType() == Type::BoolTy)
903 BoolCast = CI;
904 if (BoolCast) {
905 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
906 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
907 const Type *SCOpTy = SCIOp0->getType();
908
Chris Lattnere79e8542004-02-23 06:38:22 +0000909 // If the setcc is true iff the sign bit of X is set, then convert this
910 // multiply into a shift/and combination.
911 if (isa<ConstantInt>(SCIOp1) &&
912 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000913 // Shift the X value right to turn it into "all signbits".
914 Constant *Amt = ConstantUInt::get(Type::UByteTy,
915 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000916 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000917 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000918 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
919 SCIOp0->getName()), I);
920 }
921
922 Value *V =
923 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
924 BoolCast->getOperand(0)->getName()+
925 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000926
927 // If the multiply type is not the same as the source type, sign extend
928 // or truncate to the multiply type.
929 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000930 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000931
932 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000933 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000934 }
935 }
936 }
937
Chris Lattner113f4f42002-06-25 16:13:24 +0000938 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000939}
940
Chris Lattner113f4f42002-06-25 16:13:24 +0000941Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000942 if (isa<UndefValue>(I.getOperand(0))) // undef / X -> 0
943 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
944 if (isa<UndefValue>(I.getOperand(1)))
945 return ReplaceInstUsesWith(I, I.getOperand(1)); // X / undef -> undef
946
Chris Lattner3082c5a2003-02-18 19:28:33 +0000947 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000948 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000949 if (RHS->equalsInt(1))
950 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000951
Chris Lattnere20c3342004-04-26 14:01:59 +0000952 // div X, -1 == -X
953 if (RHS->isAllOnesValue())
954 return BinaryOperator::createNeg(I.getOperand(0));
955
Chris Lattner272d5ca2004-09-28 18:22:15 +0000956 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
957 if (LHS->getOpcode() == Instruction::Div)
958 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000959 // (X / C1) / C2 -> X / (C1*C2)
960 return BinaryOperator::createDiv(LHS->getOperand(0),
961 ConstantExpr::getMul(RHS, LHSRHS));
962 }
963
Chris Lattner3082c5a2003-02-18 19:28:33 +0000964 // Check to see if this is an unsigned division with an exact power of 2,
965 // if so, convert to a right shift.
966 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
967 if (uint64_t Val = C->getValue()) // Don't break X / 0
968 if (uint64_t C = Log2(Val))
969 return new ShiftInst(Instruction::Shr, I.getOperand(0),
970 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000971
Chris Lattner4ad08352004-10-09 02:50:40 +0000972 // -X/C -> X/-C
973 if (RHS->getType()->isSigned())
974 if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
975 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
976
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000977 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
978 if (Instruction *NV = FoldOpIntoPhi(I))
979 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000980 }
981
982 // 0 / X == 0, we don't need to preserve faults!
983 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
984 if (LHS->equalsInt(0))
985 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
986
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000987 return 0;
988}
989
990
Chris Lattner113f4f42002-06-25 16:13:24 +0000991Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000992 if (I.getType()->isSigned())
993 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000994 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000995 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000996 // X % -Y -> X % Y
997 AddUsesToWorkList(I);
998 I.setOperand(1, RHSNeg);
999 return &I;
1000 }
1001
Chris Lattner81a7a232004-10-16 18:11:37 +00001002 if (isa<UndefValue>(I.getOperand(0))) // undef % X -> 0
1003 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1004 if (isa<UndefValue>(I.getOperand(1)))
1005 return ReplaceInstUsesWith(I, I.getOperand(1)); // X % undef -> undef
1006
Chris Lattner3082c5a2003-02-18 19:28:33 +00001007 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
1008 if (RHS->equalsInt(1)) // X % 1 == 0
1009 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1010
1011 // Check to see if this is an unsigned remainder with an exact power of 2,
1012 // if so, convert to a bitwise and.
1013 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1014 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001015 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001016 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +00001017 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001018 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1019 if (Instruction *NV = FoldOpIntoPhi(I))
1020 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +00001021 }
1022
1023 // 0 % X == 0, we don't need to preserve faults!
1024 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
1025 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001026 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1027
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001028 return 0;
1029}
1030
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001031// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001032static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001033 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1034 // Calculate -1 casted to the right type...
1035 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1036 uint64_t Val = ~0ULL; // All ones
1037 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1038 return CU->getValue() == Val-1;
1039 }
1040
1041 const ConstantSInt *CS = cast<ConstantSInt>(C);
1042
1043 // Calculate 0111111111..11111
1044 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1045 int64_t Val = INT64_MAX; // All ones
1046 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1047 return CS->getValue() == Val-1;
1048}
1049
1050// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001051static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001052 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1053 return CU->getValue() == 1;
1054
1055 const ConstantSInt *CS = cast<ConstantSInt>(C);
1056
1057 // Calculate 1111111111000000000000
1058 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1059 int64_t Val = -1; // All ones
1060 Val <<= TypeBits-1; // Shift over to the right spot
1061 return CS->getValue() == Val+1;
1062}
1063
Chris Lattner35167c32004-06-09 07:59:58 +00001064// isOneBitSet - Return true if there is exactly one bit set in the specified
1065// constant.
1066static bool isOneBitSet(const ConstantInt *CI) {
1067 uint64_t V = CI->getRawValue();
1068 return V && (V & (V-1)) == 0;
1069}
1070
Chris Lattner8fc5af42004-09-23 21:46:38 +00001071#if 0 // Currently unused
1072// isLowOnes - Return true if the constant is of the form 0+1+.
1073static bool isLowOnes(const ConstantInt *CI) {
1074 uint64_t V = CI->getRawValue();
1075
1076 // There won't be bits set in parts that the type doesn't contain.
1077 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1078
1079 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1080 return U && V && (U & V) == 0;
1081}
1082#endif
1083
1084// isHighOnes - Return true if the constant is of the form 1+0+.
1085// This is the same as lowones(~X).
1086static bool isHighOnes(const ConstantInt *CI) {
1087 uint64_t V = ~CI->getRawValue();
1088
1089 // There won't be bits set in parts that the type doesn't contain.
1090 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1091
1092 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1093 return U && V && (U & V) == 0;
1094}
1095
1096
Chris Lattner3ac7c262003-08-13 20:16:26 +00001097/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1098/// are carefully arranged to allow folding of expressions such as:
1099///
1100/// (A < B) | (A > B) --> (A != B)
1101///
1102/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1103/// represents that the comparison is true if A == B, and bit value '1' is true
1104/// if A < B.
1105///
1106static unsigned getSetCondCode(const SetCondInst *SCI) {
1107 switch (SCI->getOpcode()) {
1108 // False -> 0
1109 case Instruction::SetGT: return 1;
1110 case Instruction::SetEQ: return 2;
1111 case Instruction::SetGE: return 3;
1112 case Instruction::SetLT: return 4;
1113 case Instruction::SetNE: return 5;
1114 case Instruction::SetLE: return 6;
1115 // True -> 7
1116 default:
1117 assert(0 && "Invalid SetCC opcode!");
1118 return 0;
1119 }
1120}
1121
1122/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1123/// opcode and two operands into either a constant true or false, or a brand new
1124/// SetCC instruction.
1125static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1126 switch (Opcode) {
1127 case 0: return ConstantBool::False;
1128 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1129 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1130 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1131 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1132 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1133 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1134 case 7: return ConstantBool::True;
1135 default: assert(0 && "Illegal SetCCCode!"); return 0;
1136 }
1137}
1138
1139// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1140struct FoldSetCCLogical {
1141 InstCombiner &IC;
1142 Value *LHS, *RHS;
1143 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1144 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1145 bool shouldApply(Value *V) const {
1146 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1147 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1148 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1149 return false;
1150 }
1151 Instruction *apply(BinaryOperator &Log) const {
1152 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1153 if (SCI->getOperand(0) != LHS) {
1154 assert(SCI->getOperand(1) == LHS);
1155 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1156 }
1157
1158 unsigned LHSCode = getSetCondCode(SCI);
1159 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1160 unsigned Code;
1161 switch (Log.getOpcode()) {
1162 case Instruction::And: Code = LHSCode & RHSCode; break;
1163 case Instruction::Or: Code = LHSCode | RHSCode; break;
1164 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001165 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001166 }
1167
1168 Value *RV = getSetCCValue(Code, LHS, RHS);
1169 if (Instruction *I = dyn_cast<Instruction>(RV))
1170 return I;
1171 // Otherwise, it's a constant boolean value...
1172 return IC.ReplaceInstUsesWith(Log, RV);
1173 }
1174};
1175
1176
Chris Lattnerba1cb382003-09-19 17:17:26 +00001177// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1178// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1179// guaranteed to be either a shift instruction or a binary operator.
1180Instruction *InstCombiner::OptAndOp(Instruction *Op,
1181 ConstantIntegral *OpRHS,
1182 ConstantIntegral *AndRHS,
1183 BinaryOperator &TheAnd) {
1184 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001185 Constant *Together = 0;
1186 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001187 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001188
Chris Lattnerba1cb382003-09-19 17:17:26 +00001189 switch (Op->getOpcode()) {
1190 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001191 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001192 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001193 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001194 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001195 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1196 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001197 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001198 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001199 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001200 }
1201 break;
1202 case Instruction::Or:
1203 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001204 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001205 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001206 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001207 if (Together == AndRHS) // (X | C) & C --> C
1208 return ReplaceInstUsesWith(TheAnd, AndRHS);
1209
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001210 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001211 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1212 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001213 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001214 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001215 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001216 }
1217 }
1218 break;
1219 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001220 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001221 // Adding a one to a single bit bit-field should be turned into an XOR
1222 // of the bit. First thing to check is to see if this AND is with a
1223 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001224 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001225
1226 // Clear bits that are not part of the constant.
1227 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1228
1229 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001230 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001231 // Ok, at this point, we know that we are masking the result of the
1232 // ADD down to exactly one bit. If the constant we are adding has
1233 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001234 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001235
1236 // Check to see if any bits below the one bit set in AndRHSV are set.
1237 if ((AddRHS & (AndRHSV-1)) == 0) {
1238 // If not, the only thing that can effect the output of the AND is
1239 // the bit specified by AndRHSV. If that bit is set, the effect of
1240 // the XOR is to toggle the bit. If it is clear, then the ADD has
1241 // no effect.
1242 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1243 TheAnd.setOperand(0, X);
1244 return &TheAnd;
1245 } else {
1246 std::string Name = Op->getName(); Op->setName("");
1247 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001248 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001249 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001250 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001251 }
1252 }
1253 }
1254 }
1255 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001256
1257 case Instruction::Shl: {
1258 // We know that the AND will not produce any of the bits shifted in, so if
1259 // the anded constant includes them, clear them now!
1260 //
1261 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001262 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1263 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1264
1265 if (CI == ShlMask) { // Masking out bits that the shift already masks
1266 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1267 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001268 TheAnd.setOperand(1, CI);
1269 return &TheAnd;
1270 }
1271 break;
1272 }
1273 case Instruction::Shr:
1274 // We know that the AND will not produce any of the bits shifted in, so if
1275 // the anded constant includes them, clear them now! This only applies to
1276 // unsigned shifts, because a signed shr may bring in set bits!
1277 //
1278 if (AndRHS->getType()->isUnsigned()) {
1279 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001280 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1281 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1282
1283 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1284 return ReplaceInstUsesWith(TheAnd, Op);
1285 } else if (CI != AndRHS) {
1286 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001287 return &TheAnd;
1288 }
Chris Lattner7e794272004-09-24 15:21:34 +00001289 } else { // Signed shr.
1290 // See if this is shifting in some sign extension, then masking it out
1291 // with an and.
1292 if (Op->hasOneUse()) {
1293 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1294 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1295 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001296 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001297 // Make the argument unsigned.
1298 Value *ShVal = Op->getOperand(0);
1299 ShVal = InsertCastBefore(ShVal,
1300 ShVal->getType()->getUnsignedVersion(),
1301 TheAnd);
1302 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1303 OpRHS, Op->getName()),
1304 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001305 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1306 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1307 TheAnd.getName()),
1308 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001309 return new CastInst(ShVal, Op->getType());
1310 }
1311 }
Chris Lattner2da29172003-09-19 19:05:02 +00001312 }
1313 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001314 }
1315 return 0;
1316}
1317
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001318
Chris Lattner6862fbd2004-09-29 17:40:11 +00001319/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1320/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1321/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1322/// insert new instructions.
1323Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1324 bool Inside, Instruction &IB) {
1325 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1326 "Lo is not <= Hi in range emission code!");
1327 if (Inside) {
1328 if (Lo == Hi) // Trivially false.
1329 return new SetCondInst(Instruction::SetNE, V, V);
1330 if (cast<ConstantIntegral>(Lo)->isMinValue())
1331 return new SetCondInst(Instruction::SetLT, V, Hi);
1332
1333 Constant *AddCST = ConstantExpr::getNeg(Lo);
1334 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1335 InsertNewInstBefore(Add, IB);
1336 // Convert to unsigned for the comparison.
1337 const Type *UnsType = Add->getType()->getUnsignedVersion();
1338 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1339 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1340 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1341 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1342 }
1343
1344 if (Lo == Hi) // Trivially true.
1345 return new SetCondInst(Instruction::SetEQ, V, V);
1346
1347 Hi = SubOne(cast<ConstantInt>(Hi));
1348 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1349 return new SetCondInst(Instruction::SetGT, V, Hi);
1350
1351 // Emit X-Lo > Hi-Lo-1
1352 Constant *AddCST = ConstantExpr::getNeg(Lo);
1353 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1354 InsertNewInstBefore(Add, IB);
1355 // Convert to unsigned for the comparison.
1356 const Type *UnsType = Add->getType()->getUnsignedVersion();
1357 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1358 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1359 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1360 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1361}
1362
1363
Chris Lattner113f4f42002-06-25 16:13:24 +00001364Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001365 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001366 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001367
Chris Lattner81a7a232004-10-16 18:11:37 +00001368 if (isa<UndefValue>(Op1)) // X & undef -> 0
1369 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1370
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001371 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001372 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1373 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001374
1375 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001376 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001377 if (RHS->isAllOnesValue())
1378 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001379
Chris Lattnerba1cb382003-09-19 17:17:26 +00001380 // Optimize a variety of ((val OP C1) & C2) combinations...
1381 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1382 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001383 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001384 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001385 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1386 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001387 }
Chris Lattner183b3362004-04-09 19:05:30 +00001388
1389 // Try to fold constant and into select arguments.
1390 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1391 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1392 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001393 if (isa<PHINode>(Op0))
1394 if (Instruction *NV = FoldOpIntoPhi(I))
1395 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001396 }
1397
Chris Lattnerbb74e222003-03-10 23:06:50 +00001398 Value *Op0NotVal = dyn_castNotVal(Op0);
1399 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001400
Chris Lattner023a4832004-06-18 06:07:51 +00001401 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1402 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1403
Misha Brukman9c003d82004-07-30 12:50:08 +00001404 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001405 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001406 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1407 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001408 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001409 return BinaryOperator::createNot(Or);
1410 }
1411
Chris Lattner623826c2004-09-28 21:48:02 +00001412 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1413 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001414 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1415 return R;
1416
Chris Lattner623826c2004-09-28 21:48:02 +00001417 Value *LHSVal, *RHSVal;
1418 ConstantInt *LHSCst, *RHSCst;
1419 Instruction::BinaryOps LHSCC, RHSCC;
1420 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1421 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1422 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1423 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1424 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1425 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1426 // Ensure that the larger constant is on the RHS.
1427 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1428 SetCondInst *LHS = cast<SetCondInst>(Op0);
1429 if (cast<ConstantBool>(Cmp)->getValue()) {
1430 std::swap(LHS, RHS);
1431 std::swap(LHSCst, RHSCst);
1432 std::swap(LHSCC, RHSCC);
1433 }
1434
1435 // At this point, we know we have have two setcc instructions
1436 // comparing a value against two constants and and'ing the result
1437 // together. Because of the above check, we know that we only have
1438 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1439 // FoldSetCCLogical check above), that the two constants are not
1440 // equal.
1441 assert(LHSCst != RHSCst && "Compares not folded above?");
1442
1443 switch (LHSCC) {
1444 default: assert(0 && "Unknown integer condition code!");
1445 case Instruction::SetEQ:
1446 switch (RHSCC) {
1447 default: assert(0 && "Unknown integer condition code!");
1448 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1449 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1450 return ReplaceInstUsesWith(I, ConstantBool::False);
1451 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1452 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1453 return ReplaceInstUsesWith(I, LHS);
1454 }
1455 case Instruction::SetNE:
1456 switch (RHSCC) {
1457 default: assert(0 && "Unknown integer condition code!");
1458 case Instruction::SetLT:
1459 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1460 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1461 break; // (X != 13 & X < 15) -> no change
1462 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1463 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1464 return ReplaceInstUsesWith(I, RHS);
1465 case Instruction::SetNE:
1466 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1467 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1468 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1469 LHSVal->getName()+".off");
1470 InsertNewInstBefore(Add, I);
1471 const Type *UnsType = Add->getType()->getUnsignedVersion();
1472 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1473 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1474 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1475 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1476 }
1477 break; // (X != 13 & X != 15) -> no change
1478 }
1479 break;
1480 case Instruction::SetLT:
1481 switch (RHSCC) {
1482 default: assert(0 && "Unknown integer condition code!");
1483 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1484 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1485 return ReplaceInstUsesWith(I, ConstantBool::False);
1486 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1487 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1488 return ReplaceInstUsesWith(I, LHS);
1489 }
1490 case Instruction::SetGT:
1491 switch (RHSCC) {
1492 default: assert(0 && "Unknown integer condition code!");
1493 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1494 return ReplaceInstUsesWith(I, LHS);
1495 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1496 return ReplaceInstUsesWith(I, RHS);
1497 case Instruction::SetNE:
1498 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1499 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1500 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001501 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1502 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001503 }
1504 }
1505 }
1506 }
1507
Chris Lattner113f4f42002-06-25 16:13:24 +00001508 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001509}
1510
Chris Lattner113f4f42002-06-25 16:13:24 +00001511Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001512 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001513 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001514
Chris Lattner81a7a232004-10-16 18:11:37 +00001515 if (isa<UndefValue>(Op1))
1516 return ReplaceInstUsesWith(I, // X | undef -> -1
1517 ConstantIntegral::getAllOnesValue(I.getType()));
1518
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001519 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001520 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1521 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001522
1523 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001524 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001525 if (RHS->isAllOnesValue())
1526 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001527
Chris Lattnerd4252a72004-07-30 07:50:03 +00001528 ConstantInt *C1; Value *X;
1529 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1530 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1531 std::string Op0Name = Op0->getName(); Op0->setName("");
1532 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1533 InsertNewInstBefore(Or, I);
1534 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1535 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001536
Chris Lattnerd4252a72004-07-30 07:50:03 +00001537 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1538 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1539 std::string Op0Name = Op0->getName(); Op0->setName("");
1540 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1541 InsertNewInstBefore(Or, I);
1542 return BinaryOperator::createXor(Or,
1543 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001544 }
Chris Lattner183b3362004-04-09 19:05:30 +00001545
1546 // Try to fold constant and into select arguments.
1547 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1548 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1549 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001550 if (isa<PHINode>(Op0))
1551 if (Instruction *NV = FoldOpIntoPhi(I))
1552 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001553 }
1554
Chris Lattner812aab72003-08-12 19:11:07 +00001555 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001556 Value *A, *B; ConstantInt *C1, *C2;
1557 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1558 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1559 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001560
Chris Lattnerd4252a72004-07-30 07:50:03 +00001561 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1562 if (A == Op1) // ~A | A == -1
1563 return ReplaceInstUsesWith(I,
1564 ConstantIntegral::getAllOnesValue(I.getType()));
1565 } else {
1566 A = 0;
1567 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001568
Chris Lattnerd4252a72004-07-30 07:50:03 +00001569 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1570 if (Op0 == B)
1571 return ReplaceInstUsesWith(I,
1572 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001573
Misha Brukman9c003d82004-07-30 12:50:08 +00001574 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001575 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1576 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1577 I.getName()+".demorgan"), I);
1578 return BinaryOperator::createNot(And);
1579 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001580 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001581
Chris Lattner3ac7c262003-08-13 20:16:26 +00001582 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001583 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001584 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1585 return R;
1586
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001587 Value *LHSVal, *RHSVal;
1588 ConstantInt *LHSCst, *RHSCst;
1589 Instruction::BinaryOps LHSCC, RHSCC;
1590 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1591 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1592 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1593 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1594 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1595 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1596 // Ensure that the larger constant is on the RHS.
1597 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1598 SetCondInst *LHS = cast<SetCondInst>(Op0);
1599 if (cast<ConstantBool>(Cmp)->getValue()) {
1600 std::swap(LHS, RHS);
1601 std::swap(LHSCst, RHSCst);
1602 std::swap(LHSCC, RHSCC);
1603 }
1604
1605 // At this point, we know we have have two setcc instructions
1606 // comparing a value against two constants and or'ing the result
1607 // together. Because of the above check, we know that we only have
1608 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1609 // FoldSetCCLogical check above), that the two constants are not
1610 // equal.
1611 assert(LHSCst != RHSCst && "Compares not folded above?");
1612
1613 switch (LHSCC) {
1614 default: assert(0 && "Unknown integer condition code!");
1615 case Instruction::SetEQ:
1616 switch (RHSCC) {
1617 default: assert(0 && "Unknown integer condition code!");
1618 case Instruction::SetEQ:
1619 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1620 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1621 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1622 LHSVal->getName()+".off");
1623 InsertNewInstBefore(Add, I);
1624 const Type *UnsType = Add->getType()->getUnsignedVersion();
1625 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1626 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1627 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1628 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1629 }
1630 break; // (X == 13 | X == 15) -> no change
1631
1632 case Instruction::SetGT:
1633 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1634 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1635 break; // (X == 13 | X > 15) -> no change
1636 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1637 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1638 return ReplaceInstUsesWith(I, RHS);
1639 }
1640 break;
1641 case Instruction::SetNE:
1642 switch (RHSCC) {
1643 default: assert(0 && "Unknown integer condition code!");
1644 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1645 return ReplaceInstUsesWith(I, RHS);
1646 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1647 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1648 return ReplaceInstUsesWith(I, LHS);
1649 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1650 return ReplaceInstUsesWith(I, ConstantBool::True);
1651 }
1652 break;
1653 case Instruction::SetLT:
1654 switch (RHSCC) {
1655 default: assert(0 && "Unknown integer condition code!");
1656 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1657 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001658 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1659 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001660 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1661 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1662 return ReplaceInstUsesWith(I, RHS);
1663 }
1664 break;
1665 case Instruction::SetGT:
1666 switch (RHSCC) {
1667 default: assert(0 && "Unknown integer condition code!");
1668 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1669 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1670 return ReplaceInstUsesWith(I, LHS);
1671 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1672 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1673 return ReplaceInstUsesWith(I, ConstantBool::True);
1674 }
1675 }
1676 }
1677 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001678 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001679}
1680
Chris Lattnerc2076352004-02-16 01:20:27 +00001681// XorSelf - Implements: X ^ X --> 0
1682struct XorSelf {
1683 Value *RHS;
1684 XorSelf(Value *rhs) : RHS(rhs) {}
1685 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1686 Instruction *apply(BinaryOperator &Xor) const {
1687 return &Xor;
1688 }
1689};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001690
1691
Chris Lattner113f4f42002-06-25 16:13:24 +00001692Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001693 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001694 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001695
Chris Lattner81a7a232004-10-16 18:11:37 +00001696 if (isa<UndefValue>(Op1))
1697 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1698
Chris Lattnerc2076352004-02-16 01:20:27 +00001699 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1700 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1701 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001702 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001703 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001704
Chris Lattner97638592003-07-23 21:37:07 +00001705 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001706 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001707 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001708 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001709
Chris Lattner97638592003-07-23 21:37:07 +00001710 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001711 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001712 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001713 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001714 return new SetCondInst(SCI->getInverseCondition(),
1715 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001716
Chris Lattner8f2f5982003-11-05 01:06:05 +00001717 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001718 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1719 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001720 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1721 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001722 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001723 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001724 }
Chris Lattner023a4832004-06-18 06:07:51 +00001725
1726 // ~(~X & Y) --> (X | ~Y)
1727 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1728 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1729 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1730 Instruction *NotY =
1731 BinaryOperator::createNot(Op0I->getOperand(1),
1732 Op0I->getOperand(1)->getName()+".not");
1733 InsertNewInstBefore(NotY, I);
1734 return BinaryOperator::createOr(Op0NotVal, NotY);
1735 }
1736 }
Chris Lattner97638592003-07-23 21:37:07 +00001737
1738 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001739 switch (Op0I->getOpcode()) {
1740 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001741 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001742 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001743 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1744 return BinaryOperator::createSub(
1745 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001746 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001747 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001748 }
Chris Lattnere5806662003-11-04 23:50:51 +00001749 break;
1750 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001751 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001752 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1753 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001754 break;
1755 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001756 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001757 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001758 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001759 break;
1760 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001761 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001762 }
Chris Lattner183b3362004-04-09 19:05:30 +00001763
1764 // Try to fold constant and into select arguments.
1765 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1766 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1767 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001768 if (isa<PHINode>(Op0))
1769 if (Instruction *NV = FoldOpIntoPhi(I))
1770 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001771 }
1772
Chris Lattnerbb74e222003-03-10 23:06:50 +00001773 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001774 if (X == Op1)
1775 return ReplaceInstUsesWith(I,
1776 ConstantIntegral::getAllOnesValue(I.getType()));
1777
Chris Lattnerbb74e222003-03-10 23:06:50 +00001778 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001779 if (X == Op0)
1780 return ReplaceInstUsesWith(I,
1781 ConstantIntegral::getAllOnesValue(I.getType()));
1782
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001783 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001784 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001785 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1786 cast<BinaryOperator>(Op1I)->swapOperands();
1787 I.swapOperands();
1788 std::swap(Op0, Op1);
1789 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1790 I.swapOperands();
1791 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001792 }
1793 } else if (Op1I->getOpcode() == Instruction::Xor) {
1794 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1795 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1796 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1797 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1798 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001799
1800 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001801 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001802 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1803 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001804 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001805 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1806 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001807 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001808 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001809 } else if (Op0I->getOpcode() == Instruction::Xor) {
1810 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1811 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1812 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1813 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001814 }
1815
Chris Lattner7aa2d472004-08-01 19:42:59 +00001816 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001817 Value *A, *B; ConstantInt *C1, *C2;
1818 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1819 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001820 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001821 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001822
Chris Lattner3ac7c262003-08-13 20:16:26 +00001823 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1824 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1825 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1826 return R;
1827
Chris Lattner113f4f42002-06-25 16:13:24 +00001828 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001829}
1830
Chris Lattner6862fbd2004-09-29 17:40:11 +00001831/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1832/// overflowed for this type.
1833static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1834 ConstantInt *In2) {
1835 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1836 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1837}
1838
1839static bool isPositive(ConstantInt *C) {
1840 return cast<ConstantSInt>(C)->getValue() >= 0;
1841}
1842
1843/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1844/// overflowed for this type.
1845static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1846 ConstantInt *In2) {
1847 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1848
1849 if (In1->getType()->isUnsigned())
1850 return cast<ConstantUInt>(Result)->getValue() <
1851 cast<ConstantUInt>(In1)->getValue();
1852 if (isPositive(In1) != isPositive(In2))
1853 return false;
1854 if (isPositive(In1))
1855 return cast<ConstantSInt>(Result)->getValue() <
1856 cast<ConstantSInt>(In1)->getValue();
1857 return cast<ConstantSInt>(Result)->getValue() >
1858 cast<ConstantSInt>(In1)->getValue();
1859}
1860
Chris Lattner113f4f42002-06-25 16:13:24 +00001861Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001862 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001863 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1864 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001865
1866 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001867 if (Op0 == Op1)
1868 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001869
Chris Lattner81a7a232004-10-16 18:11:37 +00001870 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1871 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1872
Chris Lattnerd07283a2003-08-13 05:38:46 +00001873 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1874 if (isa<ConstantPointerNull>(Op1) &&
1875 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001876 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1877
Chris Lattnerd07283a2003-08-13 05:38:46 +00001878
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001879 // setcc's with boolean values can always be turned into bitwise operations
1880 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001881 switch (I.getOpcode()) {
1882 default: assert(0 && "Invalid setcc instruction!");
1883 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001884 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001885 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001886 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001887 }
Chris Lattner4456da62004-08-11 00:50:51 +00001888 case Instruction::SetNE:
1889 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001890
Chris Lattner4456da62004-08-11 00:50:51 +00001891 case Instruction::SetGT:
1892 std::swap(Op0, Op1); // Change setgt -> setlt
1893 // FALL THROUGH
1894 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1895 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1896 InsertNewInstBefore(Not, I);
1897 return BinaryOperator::createAnd(Not, Op1);
1898 }
1899 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001900 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001901 // FALL THROUGH
1902 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1903 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1904 InsertNewInstBefore(Not, I);
1905 return BinaryOperator::createOr(Not, Op1);
1906 }
1907 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001908 }
1909
Chris Lattner2dd01742004-06-09 04:24:29 +00001910 // See if we are doing a comparison between a constant and an instruction that
1911 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001912 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001913 // Check to see if we are comparing against the minimum or maximum value...
1914 if (CI->isMinValue()) {
1915 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1916 return ReplaceInstUsesWith(I, ConstantBool::False);
1917 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1918 return ReplaceInstUsesWith(I, ConstantBool::True);
1919 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1920 return BinaryOperator::createSetEQ(Op0, Op1);
1921 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1922 return BinaryOperator::createSetNE(Op0, Op1);
1923
1924 } else if (CI->isMaxValue()) {
1925 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1926 return ReplaceInstUsesWith(I, ConstantBool::False);
1927 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1928 return ReplaceInstUsesWith(I, ConstantBool::True);
1929 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1930 return BinaryOperator::createSetEQ(Op0, Op1);
1931 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1932 return BinaryOperator::createSetNE(Op0, Op1);
1933
1934 // Comparing against a value really close to min or max?
1935 } else if (isMinValuePlusOne(CI)) {
1936 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1937 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1938 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1939 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1940
1941 } else if (isMaxValueMinusOne(CI)) {
1942 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1943 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1944 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1945 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1946 }
1947
1948 // If we still have a setle or setge instruction, turn it into the
1949 // appropriate setlt or setgt instruction. Since the border cases have
1950 // already been handled above, this requires little checking.
1951 //
1952 if (I.getOpcode() == Instruction::SetLE)
1953 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1954 if (I.getOpcode() == Instruction::SetGE)
1955 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1956
Chris Lattnere1e10e12004-05-25 06:32:08 +00001957 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001958 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001959 case Instruction::PHI:
1960 if (Instruction *NV = FoldOpIntoPhi(I))
1961 return NV;
1962 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001963 case Instruction::And:
1964 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1965 LHSI->getOperand(0)->hasOneUse()) {
1966 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1967 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1968 // happens a LOT in code produced by the C front-end, for bitfield
1969 // access.
1970 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1971 ConstantUInt *ShAmt;
1972 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1973 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1974 const Type *Ty = LHSI->getType();
1975
1976 // We can fold this as long as we can't shift unknown bits
1977 // into the mask. This can only happen with signed shift
1978 // rights, as they sign-extend.
1979 if (ShAmt) {
1980 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001981 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001982 if (!CanFold) {
1983 // To test for the bad case of the signed shr, see if any
1984 // of the bits shifted in could be tested after the mask.
1985 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001986 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001987 Constant *ShVal =
1988 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1989 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1990 CanFold = true;
1991 }
1992
1993 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001994 Constant *NewCst;
1995 if (Shift->getOpcode() == Instruction::Shl)
1996 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1997 else
1998 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001999
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002000 // Check to see if we are shifting out any of the bits being
2001 // compared.
2002 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2003 // If we shifted bits out, the fold is not going to work out.
2004 // As a special case, check to see if this means that the
2005 // result is always true or false now.
2006 if (I.getOpcode() == Instruction::SetEQ)
2007 return ReplaceInstUsesWith(I, ConstantBool::False);
2008 if (I.getOpcode() == Instruction::SetNE)
2009 return ReplaceInstUsesWith(I, ConstantBool::True);
2010 } else {
2011 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002012 Constant *NewAndCST;
2013 if (Shift->getOpcode() == Instruction::Shl)
2014 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2015 else
2016 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2017 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002018 LHSI->setOperand(0, Shift->getOperand(0));
2019 WorkList.push_back(Shift); // Shift is dead.
2020 AddUsesToWorkList(I);
2021 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002022 }
2023 }
Chris Lattner35167c32004-06-09 07:59:58 +00002024 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002025 }
2026 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002027
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002028 case Instruction::Cast: { // (setcc (cast X to larger), CI)
2029 const Type *SrcTy = LHSI->getOperand(0)->getType();
2030 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00002031 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002032 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00002033 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002034 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
Chris Lattner96f66162004-11-02 03:50:32 +00002035 if (SrcBits < DestBits &&
2036 // FIXME: Reenable the code below for < and >. However, we have
2037 // to handle the cases when the source of the cast and the dest of
2038 // the cast have different signs. e.g:
2039 // (cast sbyte %X to uint) >u 255U -> X <s (sbyte)0
2040 (I.getOpcode() == Instruction::SetEQ ||
2041 I.getOpcode() == Instruction::SetNE)) {
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002042 // Check to see if the comparison is always true or false.
2043 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2044 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002045 switch (I.getOpcode()) {
2046 default: assert(0 && "unknown integer comparison");
Chris Lattner96f66162004-11-02 03:50:32 +00002047#if 0
2048 case Instruction::SetLT: {
2049 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
2050 Max = ConstantExpr::getCast(Max, LHSI->getType());
2051 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2052 }
2053 case Instruction::SetGT: {
2054 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
2055 Min = ConstantExpr::getCast(Min, LHSI->getType());
2056 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2057 }
2058#endif
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002059 case Instruction::SetEQ:
2060 return ReplaceInstUsesWith(I, ConstantBool::False);
2061 case Instruction::SetNE:
2062 return ReplaceInstUsesWith(I, ConstantBool::True);
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002063 }
2064 }
2065
Chris Lattner96f66162004-11-02 03:50:32 +00002066 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0), NewCst);
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002067 }
2068 }
2069 break;
2070 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00002071 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2072 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2073 switch (I.getOpcode()) {
2074 default: break;
2075 case Instruction::SetEQ:
2076 case Instruction::SetNE: {
2077 // If we are comparing against bits always shifted out, the
2078 // comparison cannot succeed.
2079 Constant *Comp =
2080 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2081 if (Comp != CI) {// Comparing against a bit that we know is zero.
2082 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2083 Constant *Cst = ConstantBool::get(IsSetNE);
2084 return ReplaceInstUsesWith(I, Cst);
2085 }
2086
2087 if (LHSI->hasOneUse()) {
2088 // Otherwise strength reduce the shift into an and.
2089 unsigned ShAmtVal = ShAmt->getValue();
2090 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2091 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2092
2093 Constant *Mask;
2094 if (CI->getType()->isUnsigned()) {
2095 Mask = ConstantUInt::get(CI->getType(), Val);
2096 } else if (ShAmtVal != 0) {
2097 Mask = ConstantSInt::get(CI->getType(), Val);
2098 } else {
2099 Mask = ConstantInt::getAllOnesValue(CI->getType());
2100 }
2101
2102 Instruction *AndI =
2103 BinaryOperator::createAnd(LHSI->getOperand(0),
2104 Mask, LHSI->getName()+".mask");
2105 Value *And = InsertNewInstBefore(AndI, I);
2106 return new SetCondInst(I.getOpcode(), And,
2107 ConstantExpr::getUShr(CI, ShAmt));
2108 }
2109 }
2110 }
2111 }
2112 break;
2113
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002114 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002115 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002116 switch (I.getOpcode()) {
2117 default: break;
2118 case Instruction::SetEQ:
2119 case Instruction::SetNE: {
2120 // If we are comparing against bits always shifted out, the
2121 // comparison cannot succeed.
2122 Constant *Comp =
2123 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2124
2125 if (Comp != CI) {// Comparing against a bit that we know is zero.
2126 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2127 Constant *Cst = ConstantBool::get(IsSetNE);
2128 return ReplaceInstUsesWith(I, Cst);
2129 }
2130
2131 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002132 unsigned ShAmtVal = ShAmt->getValue();
2133
Chris Lattner1023b872004-09-27 16:18:50 +00002134 // Otherwise strength reduce the shift into an and.
2135 uint64_t Val = ~0ULL; // All ones.
2136 Val <<= ShAmtVal; // Shift over to the right spot.
2137
2138 Constant *Mask;
2139 if (CI->getType()->isUnsigned()) {
2140 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2141 Val &= (1ULL << TypeBits)-1;
2142 Mask = ConstantUInt::get(CI->getType(), Val);
2143 } else {
2144 Mask = ConstantSInt::get(CI->getType(), Val);
2145 }
2146
2147 Instruction *AndI =
2148 BinaryOperator::createAnd(LHSI->getOperand(0),
2149 Mask, LHSI->getName()+".mask");
2150 Value *And = InsertNewInstBefore(AndI, I);
2151 return new SetCondInst(I.getOpcode(), And,
2152 ConstantExpr::getShl(CI, ShAmt));
2153 }
2154 break;
2155 }
2156 }
2157 }
2158 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002159
Chris Lattner6862fbd2004-09-29 17:40:11 +00002160 case Instruction::Div:
2161 // Fold: (div X, C1) op C2 -> range check
2162 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2163 // Fold this div into the comparison, producing a range check.
2164 // Determine, based on the divide type, what the range is being
2165 // checked. If there is an overflow on the low or high side, remember
2166 // it, otherwise compute the range [low, hi) bounding the new value.
2167 bool LoOverflow = false, HiOverflow = 0;
2168 ConstantInt *LoBound = 0, *HiBound = 0;
2169
2170 ConstantInt *Prod;
2171 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2172
Chris Lattnera92af962004-10-11 19:40:04 +00002173 Instruction::BinaryOps Opcode = I.getOpcode();
2174
Chris Lattner6862fbd2004-09-29 17:40:11 +00002175 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2176 } else if (LHSI->getType()->isUnsigned()) { // udiv
2177 LoBound = Prod;
2178 LoOverflow = ProdOV;
2179 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2180 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2181 if (CI->isNullValue()) { // (X / pos) op 0
2182 // Can't overflow.
2183 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2184 HiBound = DivRHS;
2185 } else if (isPositive(CI)) { // (X / pos) op pos
2186 LoBound = Prod;
2187 LoOverflow = ProdOV;
2188 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2189 } else { // (X / pos) op neg
2190 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2191 LoOverflow = AddWithOverflow(LoBound, Prod,
2192 cast<ConstantInt>(DivRHSH));
2193 HiBound = Prod;
2194 HiOverflow = ProdOV;
2195 }
2196 } else { // Divisor is < 0.
2197 if (CI->isNullValue()) { // (X / neg) op 0
2198 LoBound = AddOne(DivRHS);
2199 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2200 } else if (isPositive(CI)) { // (X / neg) op pos
2201 HiOverflow = LoOverflow = ProdOV;
2202 if (!LoOverflow)
2203 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2204 HiBound = AddOne(Prod);
2205 } else { // (X / neg) op neg
2206 LoBound = Prod;
2207 LoOverflow = HiOverflow = ProdOV;
2208 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2209 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002210
Chris Lattnera92af962004-10-11 19:40:04 +00002211 // Dividing by a negate swaps the condition.
2212 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002213 }
2214
2215 if (LoBound) {
2216 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002217 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002218 default: assert(0 && "Unhandled setcc opcode!");
2219 case Instruction::SetEQ:
2220 if (LoOverflow && HiOverflow)
2221 return ReplaceInstUsesWith(I, ConstantBool::False);
2222 else if (HiOverflow)
2223 return new SetCondInst(Instruction::SetGE, X, LoBound);
2224 else if (LoOverflow)
2225 return new SetCondInst(Instruction::SetLT, X, HiBound);
2226 else
2227 return InsertRangeTest(X, LoBound, HiBound, true, I);
2228 case Instruction::SetNE:
2229 if (LoOverflow && HiOverflow)
2230 return ReplaceInstUsesWith(I, ConstantBool::True);
2231 else if (HiOverflow)
2232 return new SetCondInst(Instruction::SetLT, X, LoBound);
2233 else if (LoOverflow)
2234 return new SetCondInst(Instruction::SetGE, X, HiBound);
2235 else
2236 return InsertRangeTest(X, LoBound, HiBound, false, I);
2237 case Instruction::SetLT:
2238 if (LoOverflow)
2239 return ReplaceInstUsesWith(I, ConstantBool::False);
2240 return new SetCondInst(Instruction::SetLT, X, LoBound);
2241 case Instruction::SetGT:
2242 if (HiOverflow)
2243 return ReplaceInstUsesWith(I, ConstantBool::False);
2244 return new SetCondInst(Instruction::SetGE, X, HiBound);
2245 }
2246 }
2247 }
2248 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002249 case Instruction::Select:
2250 // If either operand of the select is a constant, we can fold the
2251 // comparison into the select arms, which will cause one to be
2252 // constant folded and the select turned into a bitwise or.
2253 Value *Op1 = 0, *Op2 = 0;
2254 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002255 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002256 // Fold the known value into the constant operand.
2257 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2258 // Insert a new SetCC of the other select operand.
2259 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002260 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002261 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002262 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002263 // Fold the known value into the constant operand.
2264 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2265 // Insert a new SetCC of the other select operand.
2266 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002267 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002268 I.getName()), I);
2269 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002270 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002271
2272 if (Op1)
2273 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2274 break;
2275 }
2276
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002277 // Simplify seteq and setne instructions...
2278 if (I.getOpcode() == Instruction::SetEQ ||
2279 I.getOpcode() == Instruction::SetNE) {
2280 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2281
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002282 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002283 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2285 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002286 case Instruction::Rem:
2287 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2288 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2289 BO->hasOneUse() &&
2290 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2291 if (unsigned L2 =
2292 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2293 const Type *UTy = BO->getType()->getUnsignedVersion();
2294 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2295 UTy, "tmp"), I);
2296 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2297 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2298 RHSCst, BO->getName()), I);
2299 return BinaryOperator::create(I.getOpcode(), NewRem,
2300 Constant::getNullValue(UTy));
2301 }
2302 break;
2303
Chris Lattnerc992add2003-08-13 05:33:12 +00002304 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002305 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2306 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002307 if (BO->hasOneUse())
2308 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2309 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002310 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002311 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2312 // efficiently invertible, or if the add has just this one use.
2313 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002314
Chris Lattnerc992add2003-08-13 05:33:12 +00002315 if (Value *NegVal = dyn_castNegVal(BOp1))
2316 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2317 else if (Value *NegVal = dyn_castNegVal(BOp0))
2318 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002319 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002320 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2321 BO->setName("");
2322 InsertNewInstBefore(Neg, I);
2323 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2324 }
2325 }
2326 break;
2327 case Instruction::Xor:
2328 // For the xor case, we can xor two constants together, eliminating
2329 // the explicit xor.
2330 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2331 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002332 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002333
2334 // FALLTHROUGH
2335 case Instruction::Sub:
2336 // Replace (([sub|xor] A, B) != 0) with (A != B)
2337 if (CI->isNullValue())
2338 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2339 BO->getOperand(1));
2340 break;
2341
2342 case Instruction::Or:
2343 // If bits are being or'd in that are not present in the constant we
2344 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002345 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002346 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002347 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002348 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002349 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002350 break;
2351
2352 case Instruction::And:
2353 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002354 // If bits are being compared against that are and'd out, then the
2355 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002356 if (!ConstantExpr::getAnd(CI,
2357 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002358 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002359
Chris Lattner35167c32004-06-09 07:59:58 +00002360 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002361 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002362 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2363 Instruction::SetNE, Op0,
2364 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002365
Chris Lattnerc992add2003-08-13 05:33:12 +00002366 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2367 // to be a signed value as appropriate.
2368 if (isSignBit(BOC)) {
2369 Value *X = BO->getOperand(0);
2370 // If 'X' is not signed, insert a cast now...
2371 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002372 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002373 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002374 }
2375 return new SetCondInst(isSetNE ? Instruction::SetLT :
2376 Instruction::SetGE, X,
2377 Constant::getNullValue(X->getType()));
2378 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002379
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002380 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002381 if (CI->isNullValue() && isHighOnes(BOC)) {
2382 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002383 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002384
2385 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002386 if (NegX->getType()->isSigned()) {
2387 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2388 X = InsertCastBefore(X, DestTy, I);
2389 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002390 }
2391
2392 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002393 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002394 }
2395
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002396 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002397 default: break;
2398 }
2399 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002400 } else { // Not a SetEQ/SetNE
2401 // If the LHS is a cast from an integral value of the same size,
2402 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2403 Value *CastOp = Cast->getOperand(0);
2404 const Type *SrcTy = CastOp->getType();
2405 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2406 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2407 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2408 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2409 "Source and destination signednesses should differ!");
2410 if (Cast->getType()->isSigned()) {
2411 // If this is a signed comparison, check for comparisons in the
2412 // vicinity of zero.
2413 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2414 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002415 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002416 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2417 else if (I.getOpcode() == Instruction::SetGT &&
2418 cast<ConstantSInt>(CI)->getValue() == -1)
2419 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002420 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002421 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2422 } else {
2423 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2424 if (I.getOpcode() == Instruction::SetLT &&
2425 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2426 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002427 return BinaryOperator::createSetGT(CastOp,
2428 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002429 else if (I.getOpcode() == Instruction::SetGT &&
2430 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2431 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002432 return BinaryOperator::createSetLT(CastOp,
2433 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002434 }
2435 }
2436 }
Chris Lattnere967b342003-06-04 05:10:11 +00002437 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002438 }
2439
Chris Lattner16930792003-11-03 04:25:02 +00002440 // Test to see if the operands of the setcc are casted versions of other
2441 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002442 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2443 Value *CastOp0 = CI->getOperand(0);
2444 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002445 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002446 (I.getOpcode() == Instruction::SetEQ ||
2447 I.getOpcode() == Instruction::SetNE)) {
2448 // We keep moving the cast from the left operand over to the right
2449 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002450 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002451
2452 // If operand #1 is a cast instruction, see if we can eliminate it as
2453 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002454 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2455 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002456 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002457 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002458
2459 // If Op1 is a constant, we can fold the cast into the constant.
2460 if (Op1->getType() != Op0->getType())
2461 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2462 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2463 } else {
2464 // Otherwise, cast the RHS right before the setcc
2465 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2466 InsertNewInstBefore(cast<Instruction>(Op1), I);
2467 }
2468 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2469 }
2470
Chris Lattner6444c372003-11-03 05:17:03 +00002471 // Handle the special case of: setcc (cast bool to X), <cst>
2472 // This comes up when you have code like
2473 // int X = A < B;
2474 // if (X) ...
2475 // For generality, we handle any zero-extension of any operand comparison
2476 // with a constant.
2477 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2478 const Type *SrcTy = CastOp0->getType();
2479 const Type *DestTy = Op0->getType();
2480 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2481 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2482 // Ok, we have an expansion of operand 0 into a new type. Get the
2483 // constant value, masink off bits which are not set in the RHS. These
2484 // could be set if the destination value is signed.
2485 uint64_t ConstVal = ConstantRHS->getRawValue();
2486 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2487
2488 // If the constant we are comparing it with has high bits set, which
2489 // don't exist in the original value, the values could never be equal,
2490 // because the source would be zero extended.
2491 unsigned SrcBits =
2492 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002493 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2494 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002495 switch (I.getOpcode()) {
2496 default: assert(0 && "Unknown comparison type!");
2497 case Instruction::SetEQ:
2498 return ReplaceInstUsesWith(I, ConstantBool::False);
2499 case Instruction::SetNE:
2500 return ReplaceInstUsesWith(I, ConstantBool::True);
2501 case Instruction::SetLT:
2502 case Instruction::SetLE:
2503 if (DestTy->isSigned() && HasSignBit)
2504 return ReplaceInstUsesWith(I, ConstantBool::False);
2505 return ReplaceInstUsesWith(I, ConstantBool::True);
2506 case Instruction::SetGT:
2507 case Instruction::SetGE:
2508 if (DestTy->isSigned() && HasSignBit)
2509 return ReplaceInstUsesWith(I, ConstantBool::True);
2510 return ReplaceInstUsesWith(I, ConstantBool::False);
2511 }
2512 }
2513
2514 // Otherwise, we can replace the setcc with a setcc of the smaller
2515 // operand value.
2516 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2517 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2518 }
2519 }
2520 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002521 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002522}
2523
2524
2525
Chris Lattnere8d6c602003-03-10 19:16:08 +00002526Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002527 assert(I.getOperand(1)->getType() == Type::UByteTy);
2528 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002529 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002530
2531 // shl X, 0 == X and shr X, 0 == X
2532 // shl 0, X == 0 and shr 0, X == 0
2533 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002534 Op0 == Constant::getNullValue(Op0->getType()))
2535 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002536
Chris Lattner81a7a232004-10-16 18:11:37 +00002537 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2538 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00002539 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00002540 else // undef << X -> 0 AND undef >>u X -> 0
2541 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2542 }
2543 if (isa<UndefValue>(Op1)) {
2544 if (isLeftShift || I.getType()->isUnsigned())
2545 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2546 else
2547 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2548 }
2549
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002550 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2551 if (!isLeftShift)
2552 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2553 if (CSI->isAllOnesValue())
2554 return ReplaceInstUsesWith(I, CSI);
2555
Chris Lattner183b3362004-04-09 19:05:30 +00002556 // Try to fold constant and into select arguments.
2557 if (isa<Constant>(Op0))
2558 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2559 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2560 return R;
2561
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002562 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002563 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2564 // of a signed value.
2565 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002566 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002567 if (CUI->getValue() >= TypeBits) {
2568 if (!Op0->getType()->isSigned() || isLeftShift)
2569 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2570 else {
2571 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2572 return &I;
2573 }
2574 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002575
Chris Lattnerede3fe02003-08-13 04:18:28 +00002576 // ((X*C1) << C2) == (X * (C1 << C2))
2577 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2578 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2579 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002580 return BinaryOperator::createMul(BO->getOperand(0),
2581 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002582
Chris Lattner183b3362004-04-09 19:05:30 +00002583 // Try to fold constant and into select arguments.
2584 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2585 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2586 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002587 if (isa<PHINode>(Op0))
2588 if (Instruction *NV = FoldOpIntoPhi(I))
2589 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002590
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002591 // If the operand is an bitwise operator with a constant RHS, and the
2592 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002593 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002594 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2595 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2596 bool isValid = true; // Valid only for And, Or, Xor
2597 bool highBitSet = false; // Transform if high bit of constant set?
2598
2599 switch (Op0BO->getOpcode()) {
2600 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002601 case Instruction::Add:
2602 isValid = isLeftShift;
2603 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002604 case Instruction::Or:
2605 case Instruction::Xor:
2606 highBitSet = false;
2607 break;
2608 case Instruction::And:
2609 highBitSet = true;
2610 break;
2611 }
2612
2613 // If this is a signed shift right, and the high bit is modified
2614 // by the logical operation, do not perform the transformation.
2615 // The highBitSet boolean indicates the value of the high bit of
2616 // the constant which would cause it to be modified for this
2617 // operation.
2618 //
2619 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2620 uint64_t Val = Op0C->getRawValue();
2621 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2622 }
2623
2624 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002625 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002626
2627 Instruction *NewShift =
2628 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2629 Op0BO->getName());
2630 Op0BO->setName("");
2631 InsertNewInstBefore(NewShift, I);
2632
2633 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2634 NewRHS);
2635 }
2636 }
2637
Chris Lattner3204d4e2003-07-24 17:52:58 +00002638 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002639 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002640 if (ConstantUInt *ShiftAmt1C =
2641 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002642 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2643 unsigned ShiftAmt2 = CUI->getValue();
2644
2645 // Check for (A << c1) << c2 and (A >> c1) >> c2
2646 if (I.getOpcode() == Op0SI->getOpcode()) {
2647 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002648 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2649 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002650 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2651 ConstantUInt::get(Type::UByteTy, Amt));
2652 }
2653
Chris Lattnerab780df2003-07-24 18:38:56 +00002654 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2655 // signed types, we can only support the (A >> c1) << c2 configuration,
2656 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002657 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002658 // Calculate bitmask for what gets shifted off the edge...
2659 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002660 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002661 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002662 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002663 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002664
2665 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002666 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2667 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002668 InsertNewInstBefore(Mask, I);
2669
2670 // Figure out what flavor of shift we should use...
2671 if (ShiftAmt1 == ShiftAmt2)
2672 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2673 else if (ShiftAmt1 < ShiftAmt2) {
2674 return new ShiftInst(I.getOpcode(), Mask,
2675 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2676 } else {
2677 return new ShiftInst(Op0SI->getOpcode(), Mask,
2678 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2679 }
2680 }
2681 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002682 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002683
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002684 return 0;
2685}
2686
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002687enum CastType {
2688 Noop = 0,
2689 Truncate = 1,
2690 Signext = 2,
2691 Zeroext = 3
2692};
2693
2694/// getCastType - In the future, we will split the cast instruction into these
2695/// various types. Until then, we have to do the analysis here.
2696static CastType getCastType(const Type *Src, const Type *Dest) {
2697 assert(Src->isIntegral() && Dest->isIntegral() &&
2698 "Only works on integral types!");
2699 unsigned SrcSize = Src->getPrimitiveSize()*8;
2700 if (Src == Type::BoolTy) SrcSize = 1;
2701 unsigned DestSize = Dest->getPrimitiveSize()*8;
2702 if (Dest == Type::BoolTy) DestSize = 1;
2703
2704 if (SrcSize == DestSize) return Noop;
2705 if (SrcSize > DestSize) return Truncate;
2706 if (Src->isSigned()) return Signext;
2707 return Zeroext;
2708}
2709
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002710
Chris Lattner48a44f72002-05-02 17:06:02 +00002711// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2712// instruction.
2713//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002714static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002715 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002716
Chris Lattner650b6da2002-08-02 20:00:25 +00002717 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2718 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002719 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002720 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002721 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002722
Chris Lattner4fbad962004-07-21 04:27:24 +00002723 // If we are casting between pointer and integer types, treat pointers as
2724 // integers of the appropriate size for the code below.
2725 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2726 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2727 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002728
Chris Lattner48a44f72002-05-02 17:06:02 +00002729 // Allow free casting and conversion of sizes as long as the sign doesn't
2730 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002731 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002732 CastType FirstCast = getCastType(SrcTy, MidTy);
2733 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002734
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002735 // Capture the effect of these two casts. If the result is a legal cast,
2736 // the CastType is stored here, otherwise a special code is used.
2737 static const unsigned CastResult[] = {
2738 // First cast is noop
2739 0, 1, 2, 3,
2740 // First cast is a truncate
2741 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2742 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002743 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002744 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002745 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002746 };
2747
2748 unsigned Result = CastResult[FirstCast*4+SecondCast];
2749 switch (Result) {
2750 default: assert(0 && "Illegal table value!");
2751 case 0:
2752 case 1:
2753 case 2:
2754 case 3:
2755 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2756 // truncates, we could eliminate more casts.
2757 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2758 case 4:
2759 return false; // Not possible to eliminate this here.
2760 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002761 // Sign or zero extend followed by truncate is always ok if the result
2762 // is a truncate or noop.
2763 CastType ResultCast = getCastType(SrcTy, DstTy);
2764 if (ResultCast == Noop || ResultCast == Truncate)
2765 return true;
2766 // Otherwise we are still growing the value, we are only safe if the
2767 // result will match the sign/zeroextendness of the result.
2768 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002769 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002770 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002771 return false;
2772}
2773
Chris Lattner11ffd592004-07-20 05:21:00 +00002774static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002775 if (V->getType() == Ty || isa<Constant>(V)) return false;
2776 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002777 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2778 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002779 return false;
2780 return true;
2781}
2782
2783/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2784/// InsertBefore instruction. This is specialized a bit to avoid inserting
2785/// casts that are known to not do anything...
2786///
2787Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2788 Instruction *InsertBefore) {
2789 if (V->getType() == DestTy) return V;
2790 if (Constant *C = dyn_cast<Constant>(V))
2791 return ConstantExpr::getCast(C, DestTy);
2792
2793 CastInst *CI = new CastInst(V, DestTy, V->getName());
2794 InsertNewInstBefore(CI, *InsertBefore);
2795 return CI;
2796}
Chris Lattner48a44f72002-05-02 17:06:02 +00002797
2798// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002799//
Chris Lattner113f4f42002-06-25 16:13:24 +00002800Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002801 Value *Src = CI.getOperand(0);
2802
Chris Lattner48a44f72002-05-02 17:06:02 +00002803 // If the user is casting a value to the same type, eliminate this cast
2804 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002805 if (CI.getType() == Src->getType())
2806 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002807
Chris Lattner81a7a232004-10-16 18:11:37 +00002808 if (isa<UndefValue>(Src)) // cast undef -> undef
2809 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2810
Chris Lattner48a44f72002-05-02 17:06:02 +00002811 // If casting the result of another cast instruction, try to eliminate this
2812 // one!
2813 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002814 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002815 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002816 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002817 // This instruction now refers directly to the cast's src operand. This
2818 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002819 CI.setOperand(0, CSrc->getOperand(0));
2820 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002821 }
2822
Chris Lattner650b6da2002-08-02 20:00:25 +00002823 // If this is an A->B->A cast, and we are dealing with integral types, try
2824 // to convert this into a logical 'and' instruction.
2825 //
2826 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002827 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002828 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2829 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2830 assert(CSrc->getType() != Type::ULongTy &&
2831 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002832 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002833 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002834 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002835 }
2836 }
2837
Chris Lattner03841652004-05-25 04:29:21 +00002838 // If this is a cast to bool, turn it into the appropriate setne instruction.
2839 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002840 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002841 Constant::getNullValue(CI.getOperand(0)->getType()));
2842
Chris Lattnerd0d51602003-06-21 23:12:02 +00002843 // If casting the result of a getelementptr instruction with no offset, turn
2844 // this into a cast of the original pointer!
2845 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002846 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002847 bool AllZeroOperands = true;
2848 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2849 if (!isa<Constant>(GEP->getOperand(i)) ||
2850 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2851 AllZeroOperands = false;
2852 break;
2853 }
2854 if (AllZeroOperands) {
2855 CI.setOperand(0, GEP->getOperand(0));
2856 return &CI;
2857 }
2858 }
2859
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002860 // If we are casting a malloc or alloca to a pointer to a type of the same
2861 // size, rewrite the allocation instruction to allocate the "right" type.
2862 //
2863 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002864 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002865 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2866 // Get the type really allocated and the type casted to...
2867 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002868 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002869 if (AllocElTy->isSized() && CastElTy->isSized()) {
2870 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2871 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002872
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002873 // If the allocation is for an even multiple of the cast type size
2874 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2875 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002876 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002877 std::string Name = AI->getName(); AI->setName("");
2878 AllocationInst *New;
2879 if (isa<MallocInst>(AI))
2880 New = new MallocInst(CastElTy, Amt, Name);
2881 else
2882 New = new AllocaInst(CastElTy, Amt, Name);
2883 InsertNewInstBefore(New, *AI);
2884 return ReplaceInstUsesWith(CI, New);
2885 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002886 }
2887 }
2888
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002889 if (isa<PHINode>(Src))
2890 if (Instruction *NV = FoldOpIntoPhi(CI))
2891 return NV;
2892
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002893 // If the source value is an instruction with only this use, we can attempt to
2894 // propagate the cast into the instruction. Also, only handle integral types
2895 // for now.
2896 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002897 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002898 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2899 const Type *DestTy = CI.getType();
2900 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2901 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2902
2903 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2904 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2905
2906 switch (SrcI->getOpcode()) {
2907 case Instruction::Add:
2908 case Instruction::Mul:
2909 case Instruction::And:
2910 case Instruction::Or:
2911 case Instruction::Xor:
2912 // If we are discarding information, or just changing the sign, rewrite.
2913 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2914 // Don't insert two casts if they cannot be eliminated. We allow two
2915 // casts to be inserted if the sizes are the same. This could only be
2916 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002917 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2918 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002919 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2920 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2921 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2922 ->getOpcode(), Op0c, Op1c);
2923 }
2924 }
2925 break;
2926 case Instruction::Shl:
2927 // Allow changing the sign of the source operand. Do not allow changing
2928 // the size of the shift, UNLESS the shift amount is a constant. We
2929 // mush not change variable sized shifts to a smaller size, because it
2930 // is undefined to shift more bits out than exist in the value.
2931 if (DestBitSize == SrcBitSize ||
2932 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2933 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2934 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2935 }
2936 break;
2937 }
2938 }
2939
Chris Lattner260ab202002-04-18 17:39:14 +00002940 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002941}
2942
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002943/// GetSelectFoldableOperands - We want to turn code that looks like this:
2944/// %C = or %A, %B
2945/// %D = select %cond, %C, %A
2946/// into:
2947/// %C = select %cond, %B, 0
2948/// %D = or %A, %C
2949///
2950/// Assuming that the specified instruction is an operand to the select, return
2951/// a bitmask indicating which operands of this instruction are foldable if they
2952/// equal the other incoming value of the select.
2953///
2954static unsigned GetSelectFoldableOperands(Instruction *I) {
2955 switch (I->getOpcode()) {
2956 case Instruction::Add:
2957 case Instruction::Mul:
2958 case Instruction::And:
2959 case Instruction::Or:
2960 case Instruction::Xor:
2961 return 3; // Can fold through either operand.
2962 case Instruction::Sub: // Can only fold on the amount subtracted.
2963 case Instruction::Shl: // Can only fold on the shift amount.
2964 case Instruction::Shr:
2965 return 1;
2966 default:
2967 return 0; // Cannot fold
2968 }
2969}
2970
2971/// GetSelectFoldableConstant - For the same transformation as the previous
2972/// function, return the identity constant that goes into the select.
2973static Constant *GetSelectFoldableConstant(Instruction *I) {
2974 switch (I->getOpcode()) {
2975 default: assert(0 && "This cannot happen!"); abort();
2976 case Instruction::Add:
2977 case Instruction::Sub:
2978 case Instruction::Or:
2979 case Instruction::Xor:
2980 return Constant::getNullValue(I->getType());
2981 case Instruction::Shl:
2982 case Instruction::Shr:
2983 return Constant::getNullValue(Type::UByteTy);
2984 case Instruction::And:
2985 return ConstantInt::getAllOnesValue(I->getType());
2986 case Instruction::Mul:
2987 return ConstantInt::get(I->getType(), 1);
2988 }
2989}
2990
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002991Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002992 Value *CondVal = SI.getCondition();
2993 Value *TrueVal = SI.getTrueValue();
2994 Value *FalseVal = SI.getFalseValue();
2995
2996 // select true, X, Y -> X
2997 // select false, X, Y -> Y
2998 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002999 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003000 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003001 else {
3002 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003003 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003004 }
Chris Lattner533bc492004-03-30 19:37:13 +00003005
3006 // select C, X, X -> X
3007 if (TrueVal == FalseVal)
3008 return ReplaceInstUsesWith(SI, TrueVal);
3009
Chris Lattner81a7a232004-10-16 18:11:37 +00003010 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3011 return ReplaceInstUsesWith(SI, FalseVal);
3012 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3013 return ReplaceInstUsesWith(SI, TrueVal);
3014 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3015 if (isa<Constant>(TrueVal))
3016 return ReplaceInstUsesWith(SI, TrueVal);
3017 else
3018 return ReplaceInstUsesWith(SI, FalseVal);
3019 }
3020
Chris Lattner1c631e82004-04-08 04:43:23 +00003021 if (SI.getType() == Type::BoolTy)
3022 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3023 if (C == ConstantBool::True) {
3024 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003025 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003026 } else {
3027 // Change: A = select B, false, C --> A = and !B, C
3028 Value *NotCond =
3029 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3030 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003031 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003032 }
3033 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3034 if (C == ConstantBool::False) {
3035 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003036 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003037 } else {
3038 // Change: A = select B, C, true --> A = or !B, C
3039 Value *NotCond =
3040 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3041 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003042 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003043 }
3044 }
3045
Chris Lattner183b3362004-04-09 19:05:30 +00003046 // Selecting between two integer constants?
3047 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3048 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3049 // select C, 1, 0 -> cast C to int
3050 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3051 return new CastInst(CondVal, SI.getType());
3052 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3053 // select C, 0, 1 -> cast !C to int
3054 Value *NotCond =
3055 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003056 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003057 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003058 }
Chris Lattner35167c32004-06-09 07:59:58 +00003059
3060 // If one of the constants is zero (we know they can't both be) and we
3061 // have a setcc instruction with zero, and we have an 'and' with the
3062 // non-constant value, eliminate this whole mess. This corresponds to
3063 // cases like this: ((X & 27) ? 27 : 0)
3064 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3065 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3066 if ((IC->getOpcode() == Instruction::SetEQ ||
3067 IC->getOpcode() == Instruction::SetNE) &&
3068 isa<ConstantInt>(IC->getOperand(1)) &&
3069 cast<Constant>(IC->getOperand(1))->isNullValue())
3070 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3071 if (ICA->getOpcode() == Instruction::And &&
3072 isa<ConstantInt>(ICA->getOperand(1)) &&
3073 (ICA->getOperand(1) == TrueValC ||
3074 ICA->getOperand(1) == FalseValC) &&
3075 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3076 // Okay, now we know that everything is set up, we just don't
3077 // know whether we have a setne or seteq and whether the true or
3078 // false val is the zero.
3079 bool ShouldNotVal = !TrueValC->isNullValue();
3080 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3081 Value *V = ICA;
3082 if (ShouldNotVal)
3083 V = InsertNewInstBefore(BinaryOperator::create(
3084 Instruction::Xor, V, ICA->getOperand(1)), SI);
3085 return ReplaceInstUsesWith(SI, V);
3086 }
Chris Lattner533bc492004-03-30 19:37:13 +00003087 }
Chris Lattner623fba12004-04-10 22:21:27 +00003088
3089 // See if we are selecting two values based on a comparison of the two values.
3090 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3091 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3092 // Transform (X == Y) ? X : Y -> Y
3093 if (SCI->getOpcode() == Instruction::SetEQ)
3094 return ReplaceInstUsesWith(SI, FalseVal);
3095 // Transform (X != Y) ? X : Y -> X
3096 if (SCI->getOpcode() == Instruction::SetNE)
3097 return ReplaceInstUsesWith(SI, TrueVal);
3098 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3099
3100 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3101 // Transform (X == Y) ? Y : X -> X
3102 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003103 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003104 // Transform (X != Y) ? Y : X -> Y
3105 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003106 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003107 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3108 }
3109 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003110
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003111 // See if we can fold the select into one of our operands.
3112 if (SI.getType()->isInteger()) {
3113 // See the comment above GetSelectFoldableOperands for a description of the
3114 // transformation we are doing here.
3115 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3116 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3117 !isa<Constant>(FalseVal))
3118 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3119 unsigned OpToFold = 0;
3120 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3121 OpToFold = 1;
3122 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3123 OpToFold = 2;
3124 }
3125
3126 if (OpToFold) {
3127 Constant *C = GetSelectFoldableConstant(TVI);
3128 std::string Name = TVI->getName(); TVI->setName("");
3129 Instruction *NewSel =
3130 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3131 Name);
3132 InsertNewInstBefore(NewSel, SI);
3133 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3134 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3135 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3136 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3137 else {
3138 assert(0 && "Unknown instruction!!");
3139 }
3140 }
3141 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003142
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003143 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3144 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3145 !isa<Constant>(TrueVal))
3146 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3147 unsigned OpToFold = 0;
3148 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3149 OpToFold = 1;
3150 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3151 OpToFold = 2;
3152 }
3153
3154 if (OpToFold) {
3155 Constant *C = GetSelectFoldableConstant(FVI);
3156 std::string Name = FVI->getName(); FVI->setName("");
3157 Instruction *NewSel =
3158 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3159 Name);
3160 InsertNewInstBefore(NewSel, SI);
3161 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3162 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3163 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3164 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3165 else {
3166 assert(0 && "Unknown instruction!!");
3167 }
3168 }
3169 }
3170 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003171 return 0;
3172}
3173
3174
Chris Lattner970c33a2003-06-19 17:00:31 +00003175// CallInst simplification
3176//
3177Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003178 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3179 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003180 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3181 bool Changed = false;
3182
3183 // memmove/cpy/set of zero bytes is a noop.
3184 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3185 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3186
3187 // FIXME: Increase alignment here.
3188
3189 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3190 if (CI->getRawValue() == 1) {
3191 // Replace the instruction with just byte operations. We would
3192 // transform other cases to loads/stores, but we don't know if
3193 // alignment is sufficient.
3194 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003195 }
3196
Chris Lattner00648e12004-10-12 04:52:52 +00003197 // If we have a memmove and the source operation is a constant global,
3198 // then the source and dest pointers can't alias, so we can change this
3199 // into a call to memcpy.
3200 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3201 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3202 if (GVSrc->isConstant()) {
3203 Module *M = CI.getParent()->getParent()->getParent();
3204 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3205 CI.getCalledFunction()->getFunctionType());
3206 CI.setOperand(0, MemCpy);
3207 Changed = true;
3208 }
3209
3210 if (Changed) return &CI;
3211 }
3212
Chris Lattneraec3d942003-10-07 22:32:43 +00003213 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003214}
3215
3216// InvokeInst simplification
3217//
3218Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003219 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003220}
3221
Chris Lattneraec3d942003-10-07 22:32:43 +00003222// visitCallSite - Improvements for call and invoke instructions.
3223//
3224Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003225 bool Changed = false;
3226
3227 // If the callee is a constexpr cast of a function, attempt to move the cast
3228 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003229 if (transformConstExprCastCall(CS)) return 0;
3230
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003231 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003232
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003233 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3234 // This instruction is not reachable, just remove it. We insert a store to
3235 // undef so that we know that this code is not reachable, despite the fact
3236 // that we can't modify the CFG here.
3237 new StoreInst(ConstantBool::True,
3238 UndefValue::get(PointerType::get(Type::BoolTy)),
3239 CS.getInstruction());
3240
3241 if (!CS.getInstruction()->use_empty())
3242 CS.getInstruction()->
3243 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3244
3245 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3246 // Don't break the CFG, insert a dummy cond branch.
3247 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3248 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003249 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003250 return EraseInstFromFunction(*CS.getInstruction());
3251 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003252
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003253 const PointerType *PTy = cast<PointerType>(Callee->getType());
3254 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3255 if (FTy->isVarArg()) {
3256 // See if we can optimize any arguments passed through the varargs area of
3257 // the call.
3258 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3259 E = CS.arg_end(); I != E; ++I)
3260 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3261 // If this cast does not effect the value passed through the varargs
3262 // area, we can eliminate the use of the cast.
3263 Value *Op = CI->getOperand(0);
3264 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3265 *I = Op;
3266 Changed = true;
3267 }
3268 }
3269 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003270
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003271 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003272}
3273
Chris Lattner970c33a2003-06-19 17:00:31 +00003274// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3275// attempt to move the cast to the arguments of the call/invoke.
3276//
3277bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3278 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3279 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003280 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003281 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003282 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003283 Instruction *Caller = CS.getInstruction();
3284
3285 // Okay, this is a cast from a function to a different type. Unless doing so
3286 // would cause a type conversion of one of our arguments, change this call to
3287 // be a direct call with arguments casted to the appropriate types.
3288 //
3289 const FunctionType *FT = Callee->getFunctionType();
3290 const Type *OldRetTy = Caller->getType();
3291
Chris Lattner1f7942f2004-01-14 06:06:08 +00003292 // Check to see if we are changing the return type...
3293 if (OldRetTy != FT->getReturnType()) {
3294 if (Callee->isExternal() &&
3295 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3296 !Caller->use_empty())
3297 return false; // Cannot transform this return value...
3298
3299 // If the callsite is an invoke instruction, and the return value is used by
3300 // a PHI node in a successor, we cannot change the return type of the call
3301 // because there is no place to put the cast instruction (without breaking
3302 // the critical edge). Bail out in this case.
3303 if (!Caller->use_empty())
3304 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3305 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3306 UI != E; ++UI)
3307 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3308 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003309 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003310 return false;
3311 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003312
3313 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3314 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3315
3316 CallSite::arg_iterator AI = CS.arg_begin();
3317 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3318 const Type *ParamTy = FT->getParamType(i);
3319 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3320 if (Callee->isExternal() && !isConvertible) return false;
3321 }
3322
3323 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3324 Callee->isExternal())
3325 return false; // Do not delete arguments unless we have a function body...
3326
3327 // Okay, we decided that this is a safe thing to do: go ahead and start
3328 // inserting cast instructions as necessary...
3329 std::vector<Value*> Args;
3330 Args.reserve(NumActualArgs);
3331
3332 AI = CS.arg_begin();
3333 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3334 const Type *ParamTy = FT->getParamType(i);
3335 if ((*AI)->getType() == ParamTy) {
3336 Args.push_back(*AI);
3337 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003338 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3339 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003340 }
3341 }
3342
3343 // If the function takes more arguments than the call was taking, add them
3344 // now...
3345 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3346 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3347
3348 // If we are removing arguments to the function, emit an obnoxious warning...
3349 if (FT->getNumParams() < NumActualArgs)
3350 if (!FT->isVarArg()) {
3351 std::cerr << "WARNING: While resolving call to function '"
3352 << Callee->getName() << "' arguments were dropped!\n";
3353 } else {
3354 // Add all of the arguments in their promoted form to the arg list...
3355 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3356 const Type *PTy = getPromotedType((*AI)->getType());
3357 if (PTy != (*AI)->getType()) {
3358 // Must promote to pass through va_arg area!
3359 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3360 InsertNewInstBefore(Cast, *Caller);
3361 Args.push_back(Cast);
3362 } else {
3363 Args.push_back(*AI);
3364 }
3365 }
3366 }
3367
3368 if (FT->getReturnType() == Type::VoidTy)
3369 Caller->setName(""); // Void type should not have a name...
3370
3371 Instruction *NC;
3372 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003373 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003374 Args, Caller->getName(), Caller);
3375 } else {
3376 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3377 }
3378
3379 // Insert a cast of the return type as necessary...
3380 Value *NV = NC;
3381 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3382 if (NV->getType() != Type::VoidTy) {
3383 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003384
3385 // If this is an invoke instruction, we should insert it after the first
3386 // non-phi, instruction in the normal successor block.
3387 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3388 BasicBlock::iterator I = II->getNormalDest()->begin();
3389 while (isa<PHINode>(I)) ++I;
3390 InsertNewInstBefore(NC, *I);
3391 } else {
3392 // Otherwise, it's a call, just insert cast right after the call instr
3393 InsertNewInstBefore(NC, *Caller);
3394 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003395 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003396 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00003397 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00003398 }
3399 }
3400
3401 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3402 Caller->replaceAllUsesWith(NV);
3403 Caller->getParent()->getInstList().erase(Caller);
3404 removeFromWorkList(Caller);
3405 return true;
3406}
3407
3408
Chris Lattner48a44f72002-05-02 17:06:02 +00003409
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003410// PHINode simplification
3411//
Chris Lattner113f4f42002-06-25 16:13:24 +00003412Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00003413 if (Value *V = hasConstantValue(&PN)) {
3414 // If V is an instruction, we have to be certain that it dominates PN.
3415 // However, because we don't have dom info, we can't do a perfect job.
3416 if (Instruction *I = dyn_cast<Instruction>(V)) {
3417 // We know that the instruction dominates the PHI if there are no undef
3418 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00003419 if (I->getParent() != &I->getParent()->getParent()->front() ||
3420 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00003421 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3422 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3423 V = 0;
3424 break;
3425 }
Chris Lattnere29d6342004-10-17 21:22:38 +00003426 }
3427
3428 if (V)
3429 return ReplaceInstUsesWith(PN, V);
3430 }
Chris Lattner4db2d222004-02-16 05:07:08 +00003431
3432 // If the only user of this instruction is a cast instruction, and all of the
3433 // incoming values are constants, change this PHI to merge together the casted
3434 // constants.
3435 if (PN.hasOneUse())
3436 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3437 if (CI->getType() != PN.getType()) { // noop casts will be folded
3438 bool AllConstant = true;
3439 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3440 if (!isa<Constant>(PN.getIncomingValue(i))) {
3441 AllConstant = false;
3442 break;
3443 }
3444 if (AllConstant) {
3445 // Make a new PHI with all casted values.
3446 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3447 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3448 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3449 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3450 PN.getIncomingBlock(i));
3451 }
3452
3453 // Update the cast instruction.
3454 CI->setOperand(0, New);
3455 WorkList.push_back(CI); // revisit the cast instruction to fold.
3456 WorkList.push_back(New); // Make sure to revisit the new Phi
3457 return &PN; // PN is now dead!
3458 }
3459 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003460 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003461}
3462
Chris Lattner69193f92004-04-05 01:30:19 +00003463static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3464 Instruction *InsertPoint,
3465 InstCombiner *IC) {
3466 unsigned PS = IC->getTargetData().getPointerSize();
3467 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00003468 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3469 // We must insert a cast to ensure we sign-extend.
3470 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3471 V->getName()), *InsertPoint);
3472 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3473 *InsertPoint);
3474}
3475
Chris Lattner48a44f72002-05-02 17:06:02 +00003476
Chris Lattner113f4f42002-06-25 16:13:24 +00003477Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003478 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003479 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003480 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003481 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003482 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003483
Chris Lattner81a7a232004-10-16 18:11:37 +00003484 if (isa<UndefValue>(GEP.getOperand(0)))
3485 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3486
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003487 bool HasZeroPointerIndex = false;
3488 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3489 HasZeroPointerIndex = C->isNullValue();
3490
3491 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003492 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003493
Chris Lattner69193f92004-04-05 01:30:19 +00003494 // Eliminate unneeded casts for indices.
3495 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003496 gep_type_iterator GTI = gep_type_begin(GEP);
3497 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3498 if (isa<SequentialType>(*GTI)) {
3499 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3500 Value *Src = CI->getOperand(0);
3501 const Type *SrcTy = Src->getType();
3502 const Type *DestTy = CI->getType();
3503 if (Src->getType()->isInteger()) {
3504 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3505 // We can always eliminate a cast from ulong or long to the other.
3506 // We can always eliminate a cast from uint to int or the other on
3507 // 32-bit pointer platforms.
3508 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3509 MadeChange = true;
3510 GEP.setOperand(i, Src);
3511 }
3512 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3513 SrcTy->getPrimitiveSize() == 4) {
3514 // We can always eliminate a cast from int to [u]long. We can
3515 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3516 // pointer target.
3517 if (SrcTy->isSigned() ||
3518 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3519 MadeChange = true;
3520 GEP.setOperand(i, Src);
3521 }
Chris Lattner69193f92004-04-05 01:30:19 +00003522 }
3523 }
3524 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003525 // If we are using a wider index than needed for this platform, shrink it
3526 // to what we need. If the incoming value needs a cast instruction,
3527 // insert it. This explicit cast can make subsequent optimizations more
3528 // obvious.
3529 Value *Op = GEP.getOperand(i);
3530 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003531 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003532 GEP.setOperand(i, ConstantExpr::getCast(C,
3533 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003534 MadeChange = true;
3535 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003536 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3537 Op->getName()), GEP);
3538 GEP.setOperand(i, Op);
3539 MadeChange = true;
3540 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003541
3542 // If this is a constant idx, make sure to canonicalize it to be a signed
3543 // operand, otherwise CSE and other optimizations are pessimized.
3544 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3545 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3546 CUI->getType()->getSignedVersion()));
3547 MadeChange = true;
3548 }
Chris Lattner69193f92004-04-05 01:30:19 +00003549 }
3550 if (MadeChange) return &GEP;
3551
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003552 // Combine Indices - If the source pointer to this getelementptr instruction
3553 // is a getelementptr instruction, combine the indices of the two
3554 // getelementptr instructions into a single instruction.
3555 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003556 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003557 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003558 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003559 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003560 if (CE->getOpcode() == Instruction::GetElementPtr)
3561 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3562 }
3563
3564 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003565 // Note that if our source is a gep chain itself that we wait for that
3566 // chain to be resolved before we perform this transformation. This
3567 // avoids us creating a TON of code in some cases.
3568 //
3569 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3570 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3571 return 0; // Wait until our source is folded to completion.
3572
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003573 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003574
3575 // Find out whether the last index in the source GEP is a sequential idx.
3576 bool EndsWithSequential = false;
3577 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3578 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003579 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003580
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003581 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003582 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003583 // Replace: gep (gep %P, long B), long A, ...
3584 // With: T = long A+B; gep %P, T, ...
3585 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003586 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003587 if (SO1 == Constant::getNullValue(SO1->getType())) {
3588 Sum = GO1;
3589 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3590 Sum = SO1;
3591 } else {
3592 // If they aren't the same type, convert both to an integer of the
3593 // target's pointer size.
3594 if (SO1->getType() != GO1->getType()) {
3595 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3596 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3597 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3598 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3599 } else {
3600 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00003601 if (SO1->getType()->getPrimitiveSize() == PS) {
3602 // Convert GO1 to SO1's type.
3603 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3604
3605 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3606 // Convert SO1 to GO1's type.
3607 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3608 } else {
3609 const Type *PT = TD->getIntPtrType();
3610 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3611 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3612 }
3613 }
3614 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003615 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3616 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3617 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003618 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3619 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003620 }
Chris Lattner69193f92004-04-05 01:30:19 +00003621 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003622
3623 // Recycle the GEP we already have if possible.
3624 if (SrcGEPOperands.size() == 2) {
3625 GEP.setOperand(0, SrcGEPOperands[0]);
3626 GEP.setOperand(1, Sum);
3627 return &GEP;
3628 } else {
3629 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3630 SrcGEPOperands.end()-1);
3631 Indices.push_back(Sum);
3632 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3633 }
Chris Lattner69193f92004-04-05 01:30:19 +00003634 } else if (isa<Constant>(*GEP.idx_begin()) &&
3635 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003636 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003637 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003638 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3639 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003640 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3641 }
3642
3643 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003644 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003645
Chris Lattner5f667a62004-05-07 22:09:22 +00003646 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003647 // GEP of global variable. If all of the indices for this GEP are
3648 // constants, we can promote this to a constexpr instead of an instruction.
3649
3650 // Scan for nonconstants...
3651 std::vector<Constant*> Indices;
3652 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3653 for (; I != E && isa<Constant>(*I); ++I)
3654 Indices.push_back(cast<Constant>(*I));
3655
3656 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003657 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003658
3659 // Replace all uses of the GEP with the new constexpr...
3660 return ReplaceInstUsesWith(GEP, CE);
3661 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003662 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003663 if (CE->getOpcode() == Instruction::Cast) {
3664 if (HasZeroPointerIndex) {
3665 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3666 // into : GEP [10 x ubyte]* X, long 0, ...
3667 //
3668 // This occurs when the program declares an array extern like "int X[];"
3669 //
3670 Constant *X = CE->getOperand(0);
3671 const PointerType *CPTy = cast<PointerType>(CE->getType());
3672 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3673 if (const ArrayType *XATy =
3674 dyn_cast<ArrayType>(XTy->getElementType()))
3675 if (const ArrayType *CATy =
3676 dyn_cast<ArrayType>(CPTy->getElementType()))
3677 if (CATy->getElementType() == XATy->getElementType()) {
3678 // At this point, we know that the cast source type is a pointer
3679 // to an array of the same type as the destination pointer
3680 // array. Because the array type is never stepped over (there
3681 // is a leading zero) we can fold the cast into this GEP.
3682 GEP.setOperand(0, X);
3683 return &GEP;
3684 }
3685 }
3686 }
Chris Lattnerca081252001-12-14 16:52:21 +00003687 }
3688
Chris Lattnerca081252001-12-14 16:52:21 +00003689 return 0;
3690}
3691
Chris Lattner1085bdf2002-11-04 16:18:53 +00003692Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3693 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3694 if (AI.isArrayAllocation()) // Check C != 1
3695 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3696 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003697 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003698
3699 // Create and insert the replacement instruction...
3700 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003701 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003702 else {
3703 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003704 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003705 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003706
3707 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003708
3709 // Scan to the end of the allocation instructions, to skip over a block of
3710 // allocas if possible...
3711 //
3712 BasicBlock::iterator It = New;
3713 while (isa<AllocationInst>(*It)) ++It;
3714
3715 // Now that I is pointing to the first non-allocation-inst in the block,
3716 // insert our getelementptr instruction...
3717 //
Chris Lattner69193f92004-04-05 01:30:19 +00003718 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003719 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3720
3721 // Now make everything use the getelementptr instead of the original
3722 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003723 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00003724 } else if (isa<UndefValue>(AI.getArraySize())) {
3725 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003726 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003727
3728 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3729 // Note that we only do this for alloca's, because malloc should allocate and
3730 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003731 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3732 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003733 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3734
Chris Lattner1085bdf2002-11-04 16:18:53 +00003735 return 0;
3736}
3737
Chris Lattner8427bff2003-12-07 01:24:23 +00003738Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3739 Value *Op = FI.getOperand(0);
3740
3741 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3742 if (CastInst *CI = dyn_cast<CastInst>(Op))
3743 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3744 FI.setOperand(0, CI->getOperand(0));
3745 return &FI;
3746 }
3747
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003748 // free undef -> unreachable.
3749 if (isa<UndefValue>(Op)) {
3750 // Insert a new store to null because we cannot modify the CFG here.
3751 new StoreInst(ConstantBool::True,
3752 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3753 return EraseInstFromFunction(FI);
3754 }
3755
Chris Lattnerf3a36602004-02-28 04:57:37 +00003756 // If we have 'free null' delete the instruction. This can happen in stl code
3757 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003758 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00003759 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003760
Chris Lattner8427bff2003-12-07 01:24:23 +00003761 return 0;
3762}
3763
3764
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003765/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3766/// constantexpr, return the constant value being addressed by the constant
3767/// expression, or null if something is funny.
3768///
3769static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003770 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003771 return 0; // Do not allow stepping over the value!
3772
3773 // Loop over all of the operands, tracking down which value we are
3774 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003775 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3776 for (++I; I != E; ++I)
3777 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3778 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3779 assert(CU->getValue() < STy->getNumElements() &&
3780 "Struct index out of range!");
3781 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003782 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003783 } else if (isa<ConstantAggregateZero>(C)) {
3784 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003785 } else if (isa<UndefValue>(C)) {
3786 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnered79d8a2004-05-27 17:30:27 +00003787 } else {
3788 return 0;
3789 }
3790 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3791 const ArrayType *ATy = cast<ArrayType>(*I);
3792 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3793 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003794 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003795 else if (isa<ConstantAggregateZero>(C))
3796 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00003797 else if (isa<UndefValue>(C))
3798 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003799 else
3800 return 0;
3801 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003802 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003803 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003804 return C;
3805}
3806
Chris Lattner35e24772004-07-13 01:49:43 +00003807static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3808 User *CI = cast<User>(LI.getOperand(0));
3809
3810 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3811 if (const PointerType *SrcTy =
3812 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3813 const Type *SrcPTy = SrcTy->getElementType();
3814 if (SrcPTy->isSized() && DestPTy->isSized() &&
3815 IC.getTargetData().getTypeSize(SrcPTy) ==
3816 IC.getTargetData().getTypeSize(DestPTy) &&
3817 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3818 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3819 // Okay, we are casting from one integer or pointer type to another of
3820 // the same size. Instead of casting the pointer before the load, cast
3821 // the result of the loaded value.
3822 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003823 CI->getName(),
3824 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003825 // Now cast the result of the load.
3826 return new CastInst(NewLoad, LI.getType());
3827 }
3828 }
3829 return 0;
3830}
3831
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003832/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003833/// from this value cannot trap. If it is not obviously safe to load from the
3834/// specified pointer, we do a quick local scan of the basic block containing
3835/// ScanFrom, to determine if the address is already accessed.
3836static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3837 // If it is an alloca or global variable, it is always safe to load from.
3838 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3839
3840 // Otherwise, be a little bit agressive by scanning the local block where we
3841 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003842 // from/to. If so, the previous load or store would have already trapped,
3843 // so there is no harm doing an extra load (also, CSE will later eliminate
3844 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003845 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3846
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003847 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003848 --BBI;
3849
3850 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3851 if (LI->getOperand(0) == V) return true;
3852 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3853 if (SI->getOperand(1) == V) return true;
3854
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003855 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003856 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003857}
3858
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003859Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3860 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003861
Chris Lattner81a7a232004-10-16 18:11:37 +00003862 if (Constant *C = dyn_cast<Constant>(Op)) {
3863 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003864 !LI.isVolatile()) { // load null/undef -> undef
3865 // Insert a new store to null instruction before the load to indicate that
3866 // this code is not reachable. We do this instead of inserting an
3867 // unreachable instruction directly because we cannot modify the CFG.
3868 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00003869 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003870 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003871
Chris Lattner81a7a232004-10-16 18:11:37 +00003872 // Instcombine load (constant global) into the value loaded.
3873 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3874 if (GV->isConstant() && !GV->isExternal())
3875 return ReplaceInstUsesWith(LI, GV->getInitializer());
3876
3877 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
3878 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3879 if (CE->getOpcode() == Instruction::GetElementPtr) {
3880 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3881 if (GV->isConstant() && !GV->isExternal())
3882 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3883 return ReplaceInstUsesWith(LI, V);
3884 } else if (CE->getOpcode() == Instruction::Cast) {
3885 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3886 return Res;
3887 }
3888 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003889
3890 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003891 if (CastInst *CI = dyn_cast<CastInst>(Op))
3892 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3893 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003894
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003895 if (!LI.isVolatile() && Op->hasOneUse()) {
3896 // Change select and PHI nodes to select values instead of addresses: this
3897 // helps alias analysis out a lot, allows many others simplifications, and
3898 // exposes redundancy in the code.
3899 //
3900 // Note that we cannot do the transformation unless we know that the
3901 // introduced loads cannot trap! Something like this is valid as long as
3902 // the condition is always false: load (select bool %C, int* null, int* %G),
3903 // but it would not be valid if we transformed it to load from null
3904 // unconditionally.
3905 //
3906 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3907 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003908 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3909 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003910 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003911 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003912 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003913 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003914 return new SelectInst(SI->getCondition(), V1, V2);
3915 }
3916
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003917 // load (select (cond, null, P)) -> load P
3918 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3919 if (C->isNullValue()) {
3920 LI.setOperand(0, SI->getOperand(2));
3921 return &LI;
3922 }
3923
3924 // load (select (cond, P, null)) -> load P
3925 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3926 if (C->isNullValue()) {
3927 LI.setOperand(0, SI->getOperand(1));
3928 return &LI;
3929 }
3930
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003931 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3932 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003933 bool Safe = PN->getParent() == LI.getParent();
3934
3935 // Scan all of the instructions between the PHI and the load to make
3936 // sure there are no instructions that might possibly alter the value
3937 // loaded from the PHI.
3938 if (Safe) {
3939 BasicBlock::iterator I = &LI;
3940 for (--I; !isa<PHINode>(I); --I)
3941 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3942 Safe = false;
3943 break;
3944 }
3945 }
3946
3947 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003948 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003949 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003950 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003951
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003952 if (Safe) {
3953 // Create the PHI.
3954 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3955 InsertNewInstBefore(NewPN, *PN);
3956 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3957
3958 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3959 BasicBlock *BB = PN->getIncomingBlock(i);
3960 Value *&TheLoad = LoadMap[BB];
3961 if (TheLoad == 0) {
3962 Value *InVal = PN->getIncomingValue(i);
3963 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3964 InVal->getName()+".val"),
3965 *BB->getTerminator());
3966 }
3967 NewPN->addIncoming(TheLoad, BB);
3968 }
3969 return ReplaceInstUsesWith(LI, NewPN);
3970 }
3971 }
3972 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003973 return 0;
3974}
3975
Chris Lattner9eef8a72003-06-04 04:46:00 +00003976Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3977 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003978 Value *X;
3979 BasicBlock *TrueDest;
3980 BasicBlock *FalseDest;
3981 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3982 !isa<Constant>(X)) {
3983 // Swap Destinations and condition...
3984 BI.setCondition(X);
3985 BI.setSuccessor(0, FalseDest);
3986 BI.setSuccessor(1, TrueDest);
3987 return &BI;
3988 }
3989
3990 // Cannonicalize setne -> seteq
3991 Instruction::BinaryOps Op; Value *Y;
3992 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3993 TrueDest, FalseDest)))
3994 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3995 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3996 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3997 std::string Name = I->getName(); I->setName("");
3998 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3999 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004000 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004001 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004002 BI.setSuccessor(0, FalseDest);
4003 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004004 removeFromWorkList(I);
4005 I->getParent()->getInstList().erase(I);
4006 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004007 return &BI;
4008 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004009
Chris Lattner9eef8a72003-06-04 04:46:00 +00004010 return 0;
4011}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004012
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004013Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4014 Value *Cond = SI.getCondition();
4015 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4016 if (I->getOpcode() == Instruction::Add)
4017 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4018 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4019 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004020 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004021 AddRHS));
4022 SI.setOperand(0, I->getOperand(0));
4023 WorkList.push_back(I);
4024 return &SI;
4025 }
4026 }
4027 return 0;
4028}
4029
Chris Lattnerca081252001-12-14 16:52:21 +00004030
Chris Lattner99f48c62002-09-02 04:59:56 +00004031void InstCombiner::removeFromWorkList(Instruction *I) {
4032 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4033 WorkList.end());
4034}
4035
Chris Lattner113f4f42002-06-25 16:13:24 +00004036bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004037 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004038 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004039
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004040 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4041 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004042
Chris Lattnerca081252001-12-14 16:52:21 +00004043
4044 while (!WorkList.empty()) {
4045 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4046 WorkList.pop_back();
4047
Misha Brukman632df282002-10-29 23:06:16 +00004048 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004049 // Check to see if we can DIE the instruction...
4050 if (isInstructionTriviallyDead(I)) {
4051 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004052 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004053 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004054 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004055
4056 I->getParent()->getInstList().erase(I);
4057 removeFromWorkList(I);
4058 continue;
4059 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004060
Misha Brukman632df282002-10-29 23:06:16 +00004061 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004062 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner6580e092004-10-16 19:44:59 +00004063 if (isa<GetElementPtrInst>(I) &&
4064 cast<Constant>(I->getOperand(0))->isNullValue() &&
4065 !isa<ConstantPointerNull>(C)) {
4066 // If this is a constant expr gep that is effectively computing an
4067 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4068 bool isFoldableGEP = true;
4069 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4070 if (!isa<ConstantInt>(I->getOperand(i)))
4071 isFoldableGEP = false;
4072 if (isFoldableGEP) {
4073 uint64_t Offset = TD->getIndexedOffset(I->getOperand(0)->getType(),
4074 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4075 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004076 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004077 C = ConstantExpr::getCast(C, I->getType());
4078 }
4079 }
4080
Chris Lattner99f48c62002-09-02 04:59:56 +00004081 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004082 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004083 ReplaceInstUsesWith(*I, C);
4084
Chris Lattner99f48c62002-09-02 04:59:56 +00004085 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004086 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004087 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004088 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004089 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004090
Chris Lattnerca081252001-12-14 16:52:21 +00004091 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004092 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004093 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004094 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004095 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004096 DEBUG(std::cerr << "IC: Old = " << *I
4097 << " New = " << *Result);
4098
Chris Lattner396dbfe2004-06-09 05:08:07 +00004099 // Everything uses the new instruction now.
4100 I->replaceAllUsesWith(Result);
4101
4102 // Push the new instruction and any users onto the worklist.
4103 WorkList.push_back(Result);
4104 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004105
4106 // Move the name to the new instruction first...
4107 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004108 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004109
4110 // Insert the new instruction into the basic block...
4111 BasicBlock *InstParent = I->getParent();
4112 InstParent->getInstList().insert(I, Result);
4113
Chris Lattner63d75af2004-05-01 23:27:23 +00004114 // Make sure that we reprocess all operands now that we reduced their
4115 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004116 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4117 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4118 WorkList.push_back(OpI);
4119
Chris Lattner396dbfe2004-06-09 05:08:07 +00004120 // Instructions can end up on the worklist more than once. Make sure
4121 // we do not process an instruction that has been deleted.
4122 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004123
4124 // Erase the old instruction.
4125 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004126 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004127 DEBUG(std::cerr << "IC: MOD = " << *I);
4128
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004129 // If the instruction was modified, it's possible that it is now dead.
4130 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004131 if (isInstructionTriviallyDead(I)) {
4132 // Make sure we process all operands now that we are reducing their
4133 // use counts.
4134 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4135 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4136 WorkList.push_back(OpI);
4137
4138 // Instructions may end up in the worklist more than once. Erase all
4139 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004140 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004141 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004142 } else {
4143 WorkList.push_back(Result);
4144 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004145 }
Chris Lattner053c0932002-05-14 15:24:07 +00004146 }
Chris Lattner260ab202002-04-18 17:39:14 +00004147 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004148 }
4149 }
4150
Chris Lattner260ab202002-04-18 17:39:14 +00004151 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004152}
4153
Brian Gaeke38b79e82004-07-27 17:43:21 +00004154FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00004155 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00004156}
Brian Gaeke960707c2003-11-11 22:41:34 +00004157