blob: 72bc34074ccb4da34380e4197152c3d3ff8a5242 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// 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.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
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 Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
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"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattner22d00a82005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattner4ed40f72005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000062 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000063
Chris Lattnerc8e66542002-04-27 06:56:12 +000064 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000065 public InstVisitor<InstCombiner, Instruction*> {
66 // Worklist of all of the instructions that need to be simplified.
67 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000068 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000069
Chris Lattner51ea1272004-02-28 05:22:00 +000070 /// AddUsersToWorkList - When an instruction is simplified, add all users of
71 /// the instruction to the work lists because they might get more simplified
72 /// now.
73 ///
74 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000075 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000076 UI != UE; ++UI)
77 WorkList.push_back(cast<Instruction>(*UI));
78 }
79
Chris Lattner51ea1272004-02-28 05:22:00 +000080 /// AddUsesToWorkList - When an instruction is simplified, add operands to
81 /// the work lists because they might get more simplified now.
82 ///
83 void AddUsesToWorkList(Instruction &I) {
84 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
85 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
86 WorkList.push_back(Op);
87 }
88
Chris Lattner99f48c62002-09-02 04:59:56 +000089 // removeFromWorkList - remove all instances of I from the worklist.
90 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000091 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000092 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000093
Chris Lattnerf12cc842002-04-28 21:27:06 +000094 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000095 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000096 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000097 }
98
Chris Lattner69193f92004-04-05 01:30:19 +000099 TargetData &getTargetData() const { return *TD; }
100
Chris Lattner260ab202002-04-18 17:39:14 +0000101 // Visitation implementation - Implement instruction combining for different
102 // instruction types. The semantics are as follows:
103 // Return Value:
104 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000105 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000106 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000107 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000108 Instruction *visitAdd(BinaryOperator &I);
109 Instruction *visitSub(BinaryOperator &I);
110 Instruction *visitMul(BinaryOperator &I);
111 Instruction *visitDiv(BinaryOperator &I);
112 Instruction *visitRem(BinaryOperator &I);
113 Instruction *visitAnd(BinaryOperator &I);
114 Instruction *visitOr (BinaryOperator &I);
115 Instruction *visitXor(BinaryOperator &I);
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000116 Instruction *visitSetCondInst(SetCondInst &I);
117 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
118
Chris Lattner0798af32005-01-13 20:14:25 +0000119 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000121 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000122 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000123 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000125 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000126 Instruction *visitCallInst(CallInst &CI);
127 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitPHINode(PHINode &PN);
129 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000130 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000131 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000132 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000133 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000134 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000135 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000136
137 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000138 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000139
Chris Lattner970c33a2003-06-19 17:00:31 +0000140 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000141 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000142 bool transformConstExprCastCall(CallSite CS);
143
Chris Lattner69193f92004-04-05 01:30:19 +0000144 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145 // InsertNewInstBefore - insert an instruction New before instruction Old
146 // in the program. Add the new instruction to the worklist.
147 //
Chris Lattner623826c2004-09-28 21:48:02 +0000148 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000149 assert(New && New->getParent() == 0 &&
150 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000151 BasicBlock *BB = Old.getParent();
152 BB->getInstList().insert(&Old, New); // Insert inst
153 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000154 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000155 }
156
Chris Lattner7e794272004-09-24 15:21:34 +0000157 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
158 /// This also adds the cast to the worklist. Finally, this returns the
159 /// cast.
160 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
161 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162
Chris Lattner7e794272004-09-24 15:21:34 +0000163 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
164 WorkList.push_back(C);
165 return C;
166 }
167
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000168 // ReplaceInstUsesWith - This method is to be used when an instruction is
169 // found to be dead, replacable with another preexisting expression. Here
170 // we add all uses of I to the worklist, replace all uses of I with the new
171 // value, then return I, so that the inst combiner will know that I was
172 // modified.
173 //
174 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000175 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000176 if (&I != V) {
177 I.replaceAllUsesWith(V);
178 return &I;
179 } else {
180 // If we are replacing the instruction with itself, this must be in a
181 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000182 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000183 return &I;
184 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000185 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000186
187 // EraseInstFromFunction - When dealing with an instruction that has side
188 // effects or produces a void value, we can't rely on DCE to delete the
189 // instruction. Instead, visit methods should return the value returned by
190 // this function.
191 Instruction *EraseInstFromFunction(Instruction &I) {
192 assert(I.use_empty() && "Cannot erase instruction that is used!");
193 AddUsesToWorkList(I);
194 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000195 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000196 return 0; // Don't do anything with FI
197 }
198
199
Chris Lattner3ac7c262003-08-13 20:16:26 +0000200 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000201 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
202 /// InsertBefore instruction. This is specialized a bit to avoid inserting
203 /// casts that are known to not do anything...
204 ///
205 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
206 Instruction *InsertBefore);
207
Chris Lattner7fb29e12003-03-11 00:12:48 +0000208 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000209 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000210 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000211
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000212
213 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
214 // PHI node as operand #0, see if we can fold the instruction into the PHI
215 // (which is only possible if all operands to the PHI are constants).
216 Instruction *FoldOpIntoPhi(Instruction &I);
217
Chris Lattner7515cab2004-11-14 19:13:23 +0000218 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
219 // operator and they all are only used by the PHI, PHI together their
220 // inputs, and do the operation once, to the result of the PHI.
221 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
222
Chris Lattnerba1cb382003-09-19 17:17:26 +0000223 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
224 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000225
226 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
227 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000228 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000229
Chris Lattnerc8b70922002-07-26 21:12:46 +0000230 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000231}
232
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000233// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000234// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000235static unsigned getComplexity(Value *V) {
236 if (isa<Instruction>(V)) {
237 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000238 return 3;
239 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000240 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000241 if (isa<Argument>(V)) return 3;
242 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000243}
Chris Lattner260ab202002-04-18 17:39:14 +0000244
Chris Lattner7fb29e12003-03-11 00:12:48 +0000245// isOnlyUse - Return true if this instruction will be deleted if we stop using
246// it.
247static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000248 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000249}
250
Chris Lattnere79e8542004-02-23 06:38:22 +0000251// getPromotedType - Return the specified type promoted as it would be to pass
252// though a va_arg area...
253static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000254 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000255 case Type::SByteTyID:
256 case Type::ShortTyID: return Type::IntTy;
257 case Type::UByteTyID:
258 case Type::UShortTyID: return Type::UIntTy;
259 case Type::FloatTyID: return Type::DoubleTy;
260 default: return Ty;
261 }
262}
263
Chris Lattner567b81f2005-09-13 00:40:14 +0000264/// isCast - If the specified operand is a CastInst or a constant expr cast,
265/// return the operand value, otherwise return null.
266static Value *isCast(Value *V) {
267 if (CastInst *I = dyn_cast<CastInst>(V))
268 return I->getOperand(0);
269 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
270 if (CE->getOpcode() == Instruction::Cast)
271 return CE->getOperand(0);
272 return 0;
273}
274
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000275// SimplifyCommutative - This performs a few simplifications for commutative
276// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000277//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000278// 1. Order operands such that they are listed from right (least complex) to
279// left (most complex). This puts constants before unary operators before
280// binary operators.
281//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000282// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
283// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000284//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000285bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000286 bool Changed = false;
287 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
288 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000289
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000290 if (!I.isAssociative()) return Changed;
291 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000292 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
293 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
294 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000295 Constant *Folded = ConstantExpr::get(I.getOpcode(),
296 cast<Constant>(I.getOperand(1)),
297 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000298 I.setOperand(0, Op->getOperand(0));
299 I.setOperand(1, Folded);
300 return true;
301 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
302 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
303 isOnlyUse(Op) && isOnlyUse(Op1)) {
304 Constant *C1 = cast<Constant>(Op->getOperand(1));
305 Constant *C2 = cast<Constant>(Op1->getOperand(1));
306
307 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000308 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000309 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
310 Op1->getOperand(0),
311 Op1->getName(), &I);
312 WorkList.push_back(New);
313 I.setOperand(0, New);
314 I.setOperand(1, Folded);
315 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000316 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000317 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000318 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000319}
Chris Lattnerca081252001-12-14 16:52:21 +0000320
Chris Lattnerbb74e222003-03-10 23:06:50 +0000321// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
322// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000323//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000324static inline Value *dyn_castNegVal(Value *V) {
325 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000326 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000327
Chris Lattner9ad0d552004-12-14 20:08:06 +0000328 // Constants can be considered to be negated values if they can be folded.
329 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
330 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000331 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000332}
333
Chris Lattnerbb74e222003-03-10 23:06:50 +0000334static inline Value *dyn_castNotVal(Value *V) {
335 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000336 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000337
338 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000339 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000340 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000341 return 0;
342}
343
Chris Lattner7fb29e12003-03-11 00:12:48 +0000344// dyn_castFoldableMul - If this value is a multiply that can be folded into
345// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000346// non-constant operand of the multiply, and set CST to point to the multiplier.
347// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000348//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000349static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000350 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000351 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000352 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000353 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000354 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000355 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000356 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000357 // The multiplier is really 1 << CST.
358 Constant *One = ConstantInt::get(V->getType(), 1);
359 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
360 return I->getOperand(0);
361 }
362 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000363 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000364}
Chris Lattner31ae8632002-08-14 17:51:49 +0000365
Chris Lattner0798af32005-01-13 20:14:25 +0000366/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
367/// expression, return it.
368static User *dyn_castGetElementPtr(Value *V) {
369 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
370 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
371 if (CE->getOpcode() == Instruction::GetElementPtr)
372 return cast<User>(V);
373 return false;
374}
375
Chris Lattner623826c2004-09-28 21:48:02 +0000376// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000377static ConstantInt *AddOne(ConstantInt *C) {
378 return cast<ConstantInt>(ConstantExpr::getAdd(C,
379 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000380}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000381static ConstantInt *SubOne(ConstantInt *C) {
382 return cast<ConstantInt>(ConstantExpr::getSub(C,
383 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000384}
385
386// isTrueWhenEqual - Return true if the specified setcondinst instruction is
387// true when both operands are equal...
388//
389static bool isTrueWhenEqual(Instruction &I) {
390 return I.getOpcode() == Instruction::SetEQ ||
391 I.getOpcode() == Instruction::SetGE ||
392 I.getOpcode() == Instruction::SetLE;
393}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000394
395/// AssociativeOpt - Perform an optimization on an associative operator. This
396/// function is designed to check a chain of associative operators for a
397/// potential to apply a certain optimization. Since the optimization may be
398/// applicable if the expression was reassociated, this checks the chain, then
399/// reassociates the expression as necessary to expose the optimization
400/// opportunity. This makes use of a special Functor, which must define
401/// 'shouldApply' and 'apply' methods.
402///
403template<typename Functor>
404Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
405 unsigned Opcode = Root.getOpcode();
406 Value *LHS = Root.getOperand(0);
407
408 // Quick check, see if the immediate LHS matches...
409 if (F.shouldApply(LHS))
410 return F.apply(Root);
411
412 // Otherwise, if the LHS is not of the same opcode as the root, return.
413 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000414 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000415 // Should we apply this transform to the RHS?
416 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
417
418 // If not to the RHS, check to see if we should apply to the LHS...
419 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
420 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
421 ShouldApply = true;
422 }
423
424 // If the functor wants to apply the optimization to the RHS of LHSI,
425 // reassociate the expression from ((? op A) op B) to (? op (A op B))
426 if (ShouldApply) {
427 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000428
Chris Lattnerb8b97502003-08-13 19:01:45 +0000429 // Now all of the instructions are in the current basic block, go ahead
430 // and perform the reassociation.
431 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
432
433 // First move the selected RHS to the LHS of the root...
434 Root.setOperand(0, LHSI->getOperand(1));
435
436 // Make what used to be the LHS of the root be the user of the root...
437 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000438 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000439 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
440 return 0;
441 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000442 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000443 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000444 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
445 BasicBlock::iterator ARI = &Root; ++ARI;
446 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
447 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000448
449 // Now propagate the ExtraOperand down the chain of instructions until we
450 // get to LHSI.
451 while (TmpLHSI != LHSI) {
452 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000453 // Move the instruction to immediately before the chain we are
454 // constructing to avoid breaking dominance properties.
455 NextLHSI->getParent()->getInstList().remove(NextLHSI);
456 BB->getInstList().insert(ARI, NextLHSI);
457 ARI = NextLHSI;
458
Chris Lattnerb8b97502003-08-13 19:01:45 +0000459 Value *NextOp = NextLHSI->getOperand(1);
460 NextLHSI->setOperand(1, ExtraOperand);
461 TmpLHSI = NextLHSI;
462 ExtraOperand = NextOp;
463 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000464
Chris Lattnerb8b97502003-08-13 19:01:45 +0000465 // Now that the instructions are reassociated, have the functor perform
466 // the transformation...
467 return F.apply(Root);
468 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000469
Chris Lattnerb8b97502003-08-13 19:01:45 +0000470 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
471 }
472 return 0;
473}
474
475
476// AddRHS - Implements: X + X --> X << 1
477struct AddRHS {
478 Value *RHS;
479 AddRHS(Value *rhs) : RHS(rhs) {}
480 bool shouldApply(Value *LHS) const { return LHS == RHS; }
481 Instruction *apply(BinaryOperator &Add) const {
482 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
483 ConstantInt::get(Type::UByteTy, 1));
484 }
485};
486
487// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
488// iff C1&C2 == 0
489struct AddMaskingAnd {
490 Constant *C2;
491 AddMaskingAnd(Constant *c) : C2(c) {}
492 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000493 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000494 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000495 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000496 }
497 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000498 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000499 }
500};
501
Chris Lattner86102b82005-01-01 16:22:27 +0000502static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000503 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000504 if (isa<CastInst>(I)) {
505 if (Constant *SOC = dyn_cast<Constant>(SO))
506 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000507
Chris Lattner86102b82005-01-01 16:22:27 +0000508 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
509 SO->getName() + ".cast"), I);
510 }
511
Chris Lattner183b3362004-04-09 19:05:30 +0000512 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000513 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
514 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000515
Chris Lattner183b3362004-04-09 19:05:30 +0000516 if (Constant *SOC = dyn_cast<Constant>(SO)) {
517 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000518 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
519 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000520 }
521
522 Value *Op0 = SO, *Op1 = ConstOperand;
523 if (!ConstIsRHS)
524 std::swap(Op0, Op1);
525 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000526 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
527 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
528 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
529 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000530 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000531 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000532 abort();
533 }
Chris Lattner86102b82005-01-01 16:22:27 +0000534 return IC->InsertNewInstBefore(New, I);
535}
536
537// FoldOpIntoSelect - Given an instruction with a select as one operand and a
538// constant as the other operand, try to fold the binary operator into the
539// select arguments. This also works for Cast instructions, which obviously do
540// not have a second operand.
541static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
542 InstCombiner *IC) {
543 // Don't modify shared select instructions
544 if (!SI->hasOneUse()) return 0;
545 Value *TV = SI->getOperand(1);
546 Value *FV = SI->getOperand(2);
547
548 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000549 // Bool selects with constant operands can be folded to logical ops.
550 if (SI->getType() == Type::BoolTy) return 0;
551
Chris Lattner86102b82005-01-01 16:22:27 +0000552 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
553 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
554
555 return new SelectInst(SI->getCondition(), SelectTrueVal,
556 SelectFalseVal);
557 }
558 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000559}
560
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000561
562/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
563/// node as operand #0, see if we can fold the instruction into the PHI (which
564/// is only possible if all operands to the PHI are constants).
565Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
566 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000567 unsigned NumPHIValues = PN->getNumIncomingValues();
568 if (!PN->hasOneUse() || NumPHIValues == 0 ||
569 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000570
571 // Check to see if all of the operands of the PHI are constants. If not, we
572 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000573 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000574 if (!isa<Constant>(PN->getIncomingValue(i)))
575 return 0;
576
577 // Okay, we can do the transformation: create the new PHI node.
578 PHINode *NewPN = new PHINode(I.getType(), I.getName());
579 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000580 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000581 InsertNewInstBefore(NewPN, *PN);
582
583 // Next, add all of the operands to the PHI.
584 if (I.getNumOperands() == 2) {
585 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000586 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000587 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
588 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
589 PN->getIncomingBlock(i));
590 }
591 } else {
592 assert(isa<CastInst>(I) && "Unary op should be a cast!");
593 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000594 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000595 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
596 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
597 PN->getIncomingBlock(i));
598 }
599 }
600 return ReplaceInstUsesWith(I, NewPN);
601}
602
Chris Lattner113f4f42002-06-25 16:13:24 +0000603Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000604 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000605 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000606
Chris Lattnercf4a9962004-04-10 22:01:55 +0000607 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000608 // X + undef -> undef
609 if (isa<UndefValue>(RHS))
610 return ReplaceInstUsesWith(I, RHS);
611
Chris Lattnercf4a9962004-04-10 22:01:55 +0000612 // X + 0 --> X
613 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
614 RHSC->isNullValue())
615 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000616
Chris Lattnercf4a9962004-04-10 22:01:55 +0000617 // X + (signbit) --> X ^ signbit
618 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000619 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnercf4a9962004-04-10 22:01:55 +0000620 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000621 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000622 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000623 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000624
625 if (isa<PHINode>(LHS))
626 if (Instruction *NV = FoldOpIntoPhi(I))
627 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000628 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000629
Chris Lattnerb8b97502003-08-13 19:01:45 +0000630 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000631 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000632 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000633
634 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
635 if (RHSI->getOpcode() == Instruction::Sub)
636 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
637 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
638 }
639 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
640 if (LHSI->getOpcode() == Instruction::Sub)
641 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
642 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
643 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000644 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000645
Chris Lattner147e9752002-05-08 22:46:53 +0000646 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000647 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000648 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000649
650 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000651 if (!isa<Constant>(RHS))
652 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000653 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000654
Misha Brukmanb1c93172005-04-21 23:48:37 +0000655
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000656 ConstantInt *C2;
657 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
658 if (X == RHS) // X*C + X --> X * (C+1)
659 return BinaryOperator::createMul(RHS, AddOne(C2));
660
661 // X*C1 + X*C2 --> X * (C1+C2)
662 ConstantInt *C1;
663 if (X == dyn_castFoldableMul(RHS, C1))
664 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000665 }
666
667 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000668 if (dyn_castFoldableMul(RHS, C2) == LHS)
669 return BinaryOperator::createMul(LHS, AddOne(C2));
670
Chris Lattner57c8d992003-02-18 19:57:07 +0000671
Chris Lattnerb8b97502003-08-13 19:01:45 +0000672 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000673 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000674 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000675
Chris Lattnerb9cde762003-10-02 15:11:26 +0000676 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000677 Value *X;
678 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
679 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
680 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000681 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000682
Chris Lattnerbff91d92004-10-08 05:07:56 +0000683 // (X & FF00) + xx00 -> (X+xx00) & FF00
684 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
685 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
686 if (Anded == CRHS) {
687 // See if all bits from the first bit set in the Add RHS up are included
688 // in the mask. First, get the rightmost bit.
689 uint64_t AddRHSV = CRHS->getRawValue();
690
691 // Form a mask of all bits from the lowest bit added through the top.
692 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner2f1457f2005-04-24 17:46:05 +0000693 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerbff91d92004-10-08 05:07:56 +0000694
695 // See if the and mask includes all of these bits.
696 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000697
Chris Lattnerbff91d92004-10-08 05:07:56 +0000698 if (AddRHSHighBits == AddRHSHighBitsAnd) {
699 // Okay, the xform is safe. Insert the new add pronto.
700 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
701 LHS->getName()), I);
702 return BinaryOperator::createAnd(NewAdd, C2);
703 }
704 }
705 }
706
Chris Lattnerd4252a72004-07-30 07:50:03 +0000707 // Try to fold constant add into select arguments.
708 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000709 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000710 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000711 }
712
Chris Lattner113f4f42002-06-25 16:13:24 +0000713 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000714}
715
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000716// isSignBit - Return true if the value represented by the constant only has the
717// highest order bit set.
718static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000719 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000720 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000721}
722
Chris Lattner022167f2004-03-13 00:11:49 +0000723/// RemoveNoopCast - Strip off nonconverting casts from the value.
724///
725static Value *RemoveNoopCast(Value *V) {
726 if (CastInst *CI = dyn_cast<CastInst>(V)) {
727 const Type *CTy = CI->getType();
728 const Type *OpTy = CI->getOperand(0)->getType();
729 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000730 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000731 return RemoveNoopCast(CI->getOperand(0));
732 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
733 return RemoveNoopCast(CI->getOperand(0));
734 }
735 return V;
736}
737
Chris Lattner113f4f42002-06-25 16:13:24 +0000738Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000739 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000740
Chris Lattnere6794492002-08-12 21:17:25 +0000741 if (Op0 == Op1) // sub X, X -> 0
742 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000743
Chris Lattnere6794492002-08-12 21:17:25 +0000744 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000745 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000746 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000747
Chris Lattner81a7a232004-10-16 18:11:37 +0000748 if (isa<UndefValue>(Op0))
749 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
750 if (isa<UndefValue>(Op1))
751 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
752
Chris Lattner8f2f5982003-11-05 01:06:05 +0000753 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
754 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000755 if (C->isAllOnesValue())
756 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000757
Chris Lattner8f2f5982003-11-05 01:06:05 +0000758 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000759 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000760 if (match(Op1, m_Not(m_Value(X))))
761 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000762 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000763 // -((uint)X >> 31) -> ((int)X >> 31)
764 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000765 if (C->isNullValue()) {
766 Value *NoopCastedRHS = RemoveNoopCast(Op1);
767 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000768 if (SI->getOpcode() == Instruction::Shr)
769 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
770 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000771 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000772 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000773 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000774 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000775 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000776 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000777 // Ok, the transformation is safe. Insert a cast of the incoming
778 // value, then the new shift, then the new cast.
779 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
780 SI->getOperand(0)->getName());
781 Value *InV = InsertNewInstBefore(FirstCast, I);
782 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
783 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000784 if (NewShift->getType() == I.getType())
785 return NewShift;
786 else {
787 InV = InsertNewInstBefore(NewShift, I);
788 return new CastInst(NewShift, I.getType());
789 }
Chris Lattner92295c52004-03-12 23:53:13 +0000790 }
791 }
Chris Lattner022167f2004-03-13 00:11:49 +0000792 }
Chris Lattner183b3362004-04-09 19:05:30 +0000793
794 // Try to fold constant sub into select arguments.
795 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000796 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000797 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000798
799 if (isa<PHINode>(Op0))
800 if (Instruction *NV = FoldOpIntoPhi(I))
801 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000802 }
803
Chris Lattnera9be4492005-04-07 16:15:25 +0000804 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
805 if (Op1I->getOpcode() == Instruction::Add &&
806 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000807 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000808 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000809 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000810 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000811 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
812 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
813 // C1-(X+C2) --> (C1-C2)-X
814 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
815 Op1I->getOperand(0));
816 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000817 }
818
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000819 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000820 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
821 // is not used by anyone else...
822 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000823 if (Op1I->getOpcode() == Instruction::Sub &&
824 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000825 // Swap the two operands of the subexpr...
826 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
827 Op1I->setOperand(0, IIOp1);
828 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000829
Chris Lattner3082c5a2003-02-18 19:28:33 +0000830 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000831 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000832 }
833
834 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
835 //
836 if (Op1I->getOpcode() == Instruction::And &&
837 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
838 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
839
Chris Lattner396dbfe2004-06-09 05:08:07 +0000840 Value *NewNot =
841 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000842 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000843 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000844
Chris Lattner0aee4b72004-10-06 15:08:25 +0000845 // -(X sdiv C) -> (X sdiv -C)
846 if (Op1I->getOpcode() == Instruction::Div)
847 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000848 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000849 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000850 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000851 ConstantExpr::getNeg(DivRHS));
852
Chris Lattner57c8d992003-02-18 19:57:07 +0000853 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000854 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000855 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000856 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000857 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000858 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000859 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000860 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000861 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000862
Chris Lattner47060462005-04-07 17:14:51 +0000863 if (!Op0->getType()->isFloatingPoint())
864 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
865 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +0000866 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
867 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
868 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
869 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +0000870 } else if (Op0I->getOpcode() == Instruction::Sub) {
871 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
872 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +0000873 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000874
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000875 ConstantInt *C1;
876 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
877 if (X == Op1) { // X*C - X --> X * (C-1)
878 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
879 return BinaryOperator::createMul(Op1, CP1);
880 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000881
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000882 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
883 if (X == dyn_castFoldableMul(Op1, C2))
884 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
885 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000886 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000887}
888
Chris Lattnere79e8542004-02-23 06:38:22 +0000889/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
890/// really just returns true if the most significant (sign) bit is set.
891static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
892 if (RHS->getType()->isSigned()) {
893 // True if source is LHS < 0 or LHS <= -1
894 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
895 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
896 } else {
897 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
898 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
899 // the size of the integer type.
900 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000901 return RHSC->getValue() ==
902 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000903 if (Opcode == Instruction::SetGT)
904 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000905 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +0000906 }
907 return false;
908}
909
Chris Lattner113f4f42002-06-25 16:13:24 +0000910Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000911 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000912 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000913
Chris Lattner81a7a232004-10-16 18:11:37 +0000914 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
915 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
916
Chris Lattnere6794492002-08-12 21:17:25 +0000917 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000918 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
919 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000920
921 // ((X << C1)*C2) == (X * (C2 << C1))
922 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
923 if (SI->getOpcode() == Instruction::Shl)
924 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000925 return BinaryOperator::createMul(SI->getOperand(0),
926 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000927
Chris Lattnercce81be2003-09-11 22:24:54 +0000928 if (CI->isNullValue())
929 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
930 if (CI->equalsInt(1)) // X * 1 == X
931 return ReplaceInstUsesWith(I, Op0);
932 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000933 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000934
Chris Lattnercce81be2003-09-11 22:24:54 +0000935 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +0000936 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
937 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000938 return new ShiftInst(Instruction::Shl, Op0,
939 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +0000940 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000941 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000942 if (Op1F->isNullValue())
943 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000944
Chris Lattner3082c5a2003-02-18 19:28:33 +0000945 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
946 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
947 if (Op1F->getValue() == 1.0)
948 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
949 }
Chris Lattner183b3362004-04-09 19:05:30 +0000950
951 // Try to fold constant mul into select arguments.
952 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000953 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000954 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000955
956 if (isa<PHINode>(Op0))
957 if (Instruction *NV = FoldOpIntoPhi(I))
958 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000959 }
960
Chris Lattner934a64cf2003-03-10 23:23:04 +0000961 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
962 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000963 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000964
Chris Lattner2635b522004-02-23 05:39:21 +0000965 // If one of the operands of the multiply is a cast from a boolean value, then
966 // we know the bool is either zero or one, so this is a 'masking' multiply.
967 // See if we can simplify things based on how the boolean was originally
968 // formed.
969 CastInst *BoolCast = 0;
970 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
971 if (CI->getOperand(0)->getType() == Type::BoolTy)
972 BoolCast = CI;
973 if (!BoolCast)
974 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
975 if (CI->getOperand(0)->getType() == Type::BoolTy)
976 BoolCast = CI;
977 if (BoolCast) {
978 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
979 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
980 const Type *SCOpTy = SCIOp0->getType();
981
Chris Lattnere79e8542004-02-23 06:38:22 +0000982 // If the setcc is true iff the sign bit of X is set, then convert this
983 // multiply into a shift/and combination.
984 if (isa<ConstantInt>(SCIOp1) &&
985 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000986 // Shift the X value right to turn it into "all signbits".
987 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000988 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000989 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000990 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000991 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
992 SCIOp0->getName()), I);
993 }
994
995 Value *V =
996 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
997 BoolCast->getOperand(0)->getName()+
998 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000999
1000 // If the multiply type is not the same as the source type, sign extend
1001 // or truncate to the multiply type.
1002 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001003 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001004
Chris Lattner2635b522004-02-23 05:39:21 +00001005 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001006 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001007 }
1008 }
1009 }
1010
Chris Lattner113f4f42002-06-25 16:13:24 +00001011 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001012}
1013
Chris Lattner113f4f42002-06-25 16:13:24 +00001014Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001015 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001016
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001017 if (isa<UndefValue>(Op0)) // undef / X -> 0
1018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1019 if (isa<UndefValue>(Op1))
1020 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1021
1022 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001023 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001024 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001025 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001026
Chris Lattnere20c3342004-04-26 14:01:59 +00001027 // div X, -1 == -X
1028 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001029 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001030
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001031 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001032 if (LHS->getOpcode() == Instruction::Div)
1033 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001034 // (X / C1) / C2 -> X / (C1*C2)
1035 return BinaryOperator::createDiv(LHS->getOperand(0),
1036 ConstantExpr::getMul(RHS, LHSRHS));
1037 }
1038
Chris Lattner3082c5a2003-02-18 19:28:33 +00001039 // Check to see if this is an unsigned division with an exact power of 2,
1040 // if so, convert to a right shift.
1041 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1042 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001043 if (isPowerOf2_64(Val)) {
1044 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001045 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001046 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001047 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001048
Chris Lattner4ad08352004-10-09 02:50:40 +00001049 // -X/C -> X/-C
1050 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001051 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001052 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1053
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001054 if (!RHS->isNullValue()) {
1055 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001056 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001057 return R;
1058 if (isa<PHINode>(Op0))
1059 if (Instruction *NV = FoldOpIntoPhi(I))
1060 return NV;
1061 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001062 }
1063
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001064 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1065 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1066 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1067 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1068 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1069 if (STO->getValue() == 0) { // Couldn't be this argument.
1070 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001071 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001072 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001073 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001074 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001075 }
1076
Chris Lattner42362612005-04-08 04:03:26 +00001077 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001078 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1079 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001080 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1081 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1082 TC, SI->getName()+".t");
1083 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001084
Chris Lattner42362612005-04-08 04:03:26 +00001085 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1086 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1087 FC, SI->getName()+".f");
1088 FSI = InsertNewInstBefore(FSI, I);
1089 return new SelectInst(SI->getOperand(0), TSI, FSI);
1090 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001091 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001092
Chris Lattner3082c5a2003-02-18 19:28:33 +00001093 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001094 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001095 if (LHS->equalsInt(0))
1096 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1097
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001098 return 0;
1099}
1100
1101
Chris Lattner113f4f42002-06-25 16:13:24 +00001102Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001103 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001104 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001105 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001106 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001107 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001108 // X % -Y -> X % Y
1109 AddUsesToWorkList(I);
1110 I.setOperand(1, RHSNeg);
1111 return &I;
1112 }
1113
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001114 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001115 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001116 if (isa<UndefValue>(Op1))
1117 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001118
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001119 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001120 if (RHS->equalsInt(1)) // X % 1 == 0
1121 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1122
1123 // Check to see if this is an unsigned remainder with an exact power of 2,
1124 // if so, convert to a bitwise and.
1125 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1126 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001127 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001128 return BinaryOperator::createAnd(Op0,
1129 ConstantUInt::get(I.getType(), Val-1));
1130
1131 if (!RHS->isNullValue()) {
1132 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001133 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001134 return R;
1135 if (isa<PHINode>(Op0))
1136 if (Instruction *NV = FoldOpIntoPhi(I))
1137 return NV;
1138 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001139 }
1140
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001141 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1142 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1143 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1144 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1145 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1146 if (STO->getValue() == 0) { // Couldn't be this argument.
1147 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001148 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001149 } else if (SFO->getValue() == 0) {
1150 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001151 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001152 }
1153
1154 if (!(STO->getValue() & (STO->getValue()-1)) &&
1155 !(SFO->getValue() & (SFO->getValue()-1))) {
1156 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1157 SubOne(STO), SI->getName()+".t"), I);
1158 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1159 SubOne(SFO), SI->getName()+".f"), I);
1160 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1161 }
1162 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001163
Chris Lattner3082c5a2003-02-18 19:28:33 +00001164 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001165 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001166 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001167 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1168
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001169 return 0;
1170}
1171
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001172// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001173static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001174 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1175 // Calculate -1 casted to the right type...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001176 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001177 uint64_t Val = ~0ULL; // All ones
1178 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1179 return CU->getValue() == Val-1;
1180 }
1181
1182 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001183
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001184 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001185 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001186 int64_t Val = INT64_MAX; // All ones
1187 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1188 return CS->getValue() == Val-1;
1189}
1190
1191// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001192static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001193 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1194 return CU->getValue() == 1;
1195
1196 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001197
1198 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001199 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001200 int64_t Val = -1; // All ones
1201 Val <<= TypeBits-1; // Shift over to the right spot
1202 return CS->getValue() == Val+1;
1203}
1204
Chris Lattner35167c32004-06-09 07:59:58 +00001205// isOneBitSet - Return true if there is exactly one bit set in the specified
1206// constant.
1207static bool isOneBitSet(const ConstantInt *CI) {
1208 uint64_t V = CI->getRawValue();
1209 return V && (V & (V-1)) == 0;
1210}
1211
Chris Lattner8fc5af42004-09-23 21:46:38 +00001212#if 0 // Currently unused
1213// isLowOnes - Return true if the constant is of the form 0+1+.
1214static bool isLowOnes(const ConstantInt *CI) {
1215 uint64_t V = CI->getRawValue();
1216
1217 // There won't be bits set in parts that the type doesn't contain.
1218 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1219
1220 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1221 return U && V && (U & V) == 0;
1222}
1223#endif
1224
1225// isHighOnes - Return true if the constant is of the form 1+0+.
1226// This is the same as lowones(~X).
1227static bool isHighOnes(const ConstantInt *CI) {
1228 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001229 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001230
1231 // There won't be bits set in parts that the type doesn't contain.
1232 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1233
1234 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1235 return U && V && (U & V) == 0;
1236}
1237
1238
Chris Lattner3ac7c262003-08-13 20:16:26 +00001239/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1240/// are carefully arranged to allow folding of expressions such as:
1241///
1242/// (A < B) | (A > B) --> (A != B)
1243///
1244/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1245/// represents that the comparison is true if A == B, and bit value '1' is true
1246/// if A < B.
1247///
1248static unsigned getSetCondCode(const SetCondInst *SCI) {
1249 switch (SCI->getOpcode()) {
1250 // False -> 0
1251 case Instruction::SetGT: return 1;
1252 case Instruction::SetEQ: return 2;
1253 case Instruction::SetGE: return 3;
1254 case Instruction::SetLT: return 4;
1255 case Instruction::SetNE: return 5;
1256 case Instruction::SetLE: return 6;
1257 // True -> 7
1258 default:
1259 assert(0 && "Invalid SetCC opcode!");
1260 return 0;
1261 }
1262}
1263
1264/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1265/// opcode and two operands into either a constant true or false, or a brand new
1266/// SetCC instruction.
1267static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1268 switch (Opcode) {
1269 case 0: return ConstantBool::False;
1270 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1271 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1272 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1273 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1274 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1275 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1276 case 7: return ConstantBool::True;
1277 default: assert(0 && "Illegal SetCCCode!"); return 0;
1278 }
1279}
1280
1281// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1282struct FoldSetCCLogical {
1283 InstCombiner &IC;
1284 Value *LHS, *RHS;
1285 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1286 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1287 bool shouldApply(Value *V) const {
1288 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1289 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1290 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1291 return false;
1292 }
1293 Instruction *apply(BinaryOperator &Log) const {
1294 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1295 if (SCI->getOperand(0) != LHS) {
1296 assert(SCI->getOperand(1) == LHS);
1297 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1298 }
1299
1300 unsigned LHSCode = getSetCondCode(SCI);
1301 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1302 unsigned Code;
1303 switch (Log.getOpcode()) {
1304 case Instruction::And: Code = LHSCode & RHSCode; break;
1305 case Instruction::Or: Code = LHSCode | RHSCode; break;
1306 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001307 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001308 }
1309
1310 Value *RV = getSetCCValue(Code, LHS, RHS);
1311 if (Instruction *I = dyn_cast<Instruction>(RV))
1312 return I;
1313 // Otherwise, it's a constant boolean value...
1314 return IC.ReplaceInstUsesWith(Log, RV);
1315 }
1316};
1317
1318
Chris Lattner86102b82005-01-01 16:22:27 +00001319/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1320/// this predicate to simplify operations downstream. V and Mask are known to
1321/// be the same type.
1322static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00001323 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
1324 // we cannot optimize based on the assumption that it is zero without changing
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001325 // to to an explicit zero. If we don't change it to zero, other code could
Chris Lattner18aa4d82005-07-20 18:49:28 +00001326 // optimized based on the contradictory assumption that it is non-zero.
1327 // Because instcombine aggressively folds operations with undef args anyway,
1328 // this won't lose us code quality.
1329 if (Mask->isNullValue())
Chris Lattner86102b82005-01-01 16:22:27 +00001330 return true;
1331 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1332 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001333
Chris Lattner86102b82005-01-01 16:22:27 +00001334 if (Instruction *I = dyn_cast<Instruction>(V)) {
1335 switch (I->getOpcode()) {
1336 case Instruction::And:
1337 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1338 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1339 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1340 return true;
1341 break;
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001342 case Instruction::Or:
1343 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001344 return MaskedValueIsZero(I->getOperand(1), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001345 MaskedValueIsZero(I->getOperand(0), Mask);
1346 case Instruction::Select:
1347 // If the T and F values are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001348 return MaskedValueIsZero(I->getOperand(2), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001349 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner86102b82005-01-01 16:22:27 +00001350 case Instruction::Cast: {
1351 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner4c2d3782005-05-06 01:53:19 +00001352 if (SrcTy == Type::BoolTy)
1353 return (Mask->getRawValue() & 1) == 0;
1354
1355 if (SrcTy->isInteger()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001356 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1357 if (SrcTy->isUnsigned() && // Only handle zero ext.
1358 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1359 return true;
1360
1361 // If this is a noop cast, recurse.
Chris Lattner4c2d3782005-05-06 01:53:19 +00001362 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
1363 SrcTy->getSignedVersion() == I->getType()) {
1364 Constant *NewMask =
1365 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1366 return MaskedValueIsZero(I->getOperand(0),
1367 cast<ConstantIntegral>(NewMask));
1368 }
Chris Lattner86102b82005-01-01 16:22:27 +00001369 }
1370 break;
1371 }
1372 case Instruction::Shl:
Chris Lattneref298a32005-05-06 04:53:20 +00001373 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
1374 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1375 return MaskedValueIsZero(I->getOperand(0),
1376 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)));
Chris Lattner86102b82005-01-01 16:22:27 +00001377 break;
1378 case Instruction::Shr:
1379 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1380 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1381 if (I->getType()->isUnsigned()) {
1382 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1383 C1 = ConstantExpr::getShr(C1, SA);
1384 C1 = ConstantExpr::getAnd(C1, Mask);
1385 if (C1->isNullValue())
1386 return true;
1387 }
1388 break;
1389 }
1390 }
1391
1392 return false;
1393}
1394
Chris Lattnerba1cb382003-09-19 17:17:26 +00001395// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1396// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1397// guaranteed to be either a shift instruction or a binary operator.
1398Instruction *InstCombiner::OptAndOp(Instruction *Op,
1399 ConstantIntegral *OpRHS,
1400 ConstantIntegral *AndRHS,
1401 BinaryOperator &TheAnd) {
1402 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001403 Constant *Together = 0;
1404 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001405 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001406
Chris Lattnerba1cb382003-09-19 17:17:26 +00001407 switch (Op->getOpcode()) {
1408 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001409 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001410 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1411 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001412 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001413 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001414 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001415 }
1416 break;
1417 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001418 if (Together == AndRHS) // (X | C) & C --> C
1419 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001420
Chris Lattner86102b82005-01-01 16:22:27 +00001421 if (Op->hasOneUse() && Together != OpRHS) {
1422 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1423 std::string Op0Name = Op->getName(); Op->setName("");
1424 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1425 InsertNewInstBefore(Or, TheAnd);
1426 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001427 }
1428 break;
1429 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001430 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001431 // Adding a one to a single bit bit-field should be turned into an XOR
1432 // of the bit. First thing to check is to see if this AND is with a
1433 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001434 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001435
1436 // Clear bits that are not part of the constant.
Chris Lattner2f1457f2005-04-24 17:46:05 +00001437 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerba1cb382003-09-19 17:17:26 +00001438
1439 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001440 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001441 // Ok, at this point, we know that we are masking the result of the
1442 // ADD down to exactly one bit. If the constant we are adding has
1443 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001444 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001445
Chris Lattnerba1cb382003-09-19 17:17:26 +00001446 // Check to see if any bits below the one bit set in AndRHSV are set.
1447 if ((AddRHS & (AndRHSV-1)) == 0) {
1448 // If not, the only thing that can effect the output of the AND is
1449 // the bit specified by AndRHSV. If that bit is set, the effect of
1450 // the XOR is to toggle the bit. If it is clear, then the ADD has
1451 // no effect.
1452 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1453 TheAnd.setOperand(0, X);
1454 return &TheAnd;
1455 } else {
1456 std::string Name = Op->getName(); Op->setName("");
1457 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001458 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001459 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001460 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001461 }
1462 }
1463 }
1464 }
1465 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001466
1467 case Instruction::Shl: {
1468 // We know that the AND will not produce any of the bits shifted in, so if
1469 // the anded constant includes them, clear them now!
1470 //
1471 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001472 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1473 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001474
Chris Lattner7e794272004-09-24 15:21:34 +00001475 if (CI == ShlMask) { // Masking out bits that the shift already masks
1476 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1477 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001478 TheAnd.setOperand(1, CI);
1479 return &TheAnd;
1480 }
1481 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001482 }
Chris Lattner2da29172003-09-19 19:05:02 +00001483 case Instruction::Shr:
1484 // We know that the AND will not produce any of the bits shifted in, so if
1485 // the anded constant includes them, clear them now! This only applies to
1486 // unsigned shifts, because a signed shr may bring in set bits!
1487 //
1488 if (AndRHS->getType()->isUnsigned()) {
1489 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001490 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1491 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1492
1493 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1494 return ReplaceInstUsesWith(TheAnd, Op);
1495 } else if (CI != AndRHS) {
1496 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001497 return &TheAnd;
1498 }
Chris Lattner7e794272004-09-24 15:21:34 +00001499 } else { // Signed shr.
1500 // See if this is shifting in some sign extension, then masking it out
1501 // with an and.
1502 if (Op->hasOneUse()) {
1503 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1504 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1505 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001506 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001507 // Make the argument unsigned.
1508 Value *ShVal = Op->getOperand(0);
1509 ShVal = InsertCastBefore(ShVal,
1510 ShVal->getType()->getUnsignedVersion(),
1511 TheAnd);
1512 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1513 OpRHS, Op->getName()),
1514 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001515 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1516 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1517 TheAnd.getName()),
1518 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001519 return new CastInst(ShVal, Op->getType());
1520 }
1521 }
Chris Lattner2da29172003-09-19 19:05:02 +00001522 }
1523 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001524 }
1525 return 0;
1526}
1527
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001528
Chris Lattner6862fbd2004-09-29 17:40:11 +00001529/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1530/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1531/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1532/// insert new instructions.
1533Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1534 bool Inside, Instruction &IB) {
1535 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1536 "Lo is not <= Hi in range emission code!");
1537 if (Inside) {
1538 if (Lo == Hi) // Trivially false.
1539 return new SetCondInst(Instruction::SetNE, V, V);
1540 if (cast<ConstantIntegral>(Lo)->isMinValue())
1541 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001542
Chris Lattner6862fbd2004-09-29 17:40:11 +00001543 Constant *AddCST = ConstantExpr::getNeg(Lo);
1544 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1545 InsertNewInstBefore(Add, IB);
1546 // Convert to unsigned for the comparison.
1547 const Type *UnsType = Add->getType()->getUnsignedVersion();
1548 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1549 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1550 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1551 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1552 }
1553
1554 if (Lo == Hi) // Trivially true.
1555 return new SetCondInst(Instruction::SetEQ, V, V);
1556
1557 Hi = SubOne(cast<ConstantInt>(Hi));
1558 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1559 return new SetCondInst(Instruction::SetGT, V, Hi);
1560
1561 // Emit X-Lo > Hi-Lo-1
1562 Constant *AddCST = ConstantExpr::getNeg(Lo);
1563 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1564 InsertNewInstBefore(Add, IB);
1565 // Convert to unsigned for the comparison.
1566 const Type *UnsType = Add->getType()->getUnsignedVersion();
1567 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1568 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1569 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1570 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1571}
1572
1573
Chris Lattner113f4f42002-06-25 16:13:24 +00001574Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001575 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001577
Chris Lattner81a7a232004-10-16 18:11:37 +00001578 if (isa<UndefValue>(Op1)) // X & undef -> 0
1579 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1580
Chris Lattner86102b82005-01-01 16:22:27 +00001581 // and X, X = X
1582 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001583 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001584
Chris Lattner86102b82005-01-01 16:22:27 +00001585 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001586 // and X, -1 == X
1587 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001588 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001589
Chris Lattner86102b82005-01-01 16:22:27 +00001590 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1591 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1592
1593 // If the mask is not masking out any bits, there is no reason to do the
1594 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001595 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001596 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001597 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001598 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001599
Chris Lattnerba1cb382003-09-19 17:17:26 +00001600 // Optimize a variety of ((val OP C1) & C2) combinations...
1601 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1602 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001603 Value *Op0LHS = Op0I->getOperand(0);
1604 Value *Op0RHS = Op0I->getOperand(1);
1605 switch (Op0I->getOpcode()) {
1606 case Instruction::Xor:
1607 case Instruction::Or:
1608 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1609 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1610 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001611 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001612 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001613 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001614
1615 // If the mask is only needed on one incoming arm, push it up.
1616 if (Op0I->hasOneUse()) {
1617 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1618 // Not masking anything out for the LHS, move to RHS.
1619 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1620 Op0RHS->getName()+".masked");
1621 InsertNewInstBefore(NewRHS, I);
1622 return BinaryOperator::create(
1623 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001624 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001625 if (!isa<Constant>(NotAndRHS) &&
1626 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1627 // Not masking anything out for the RHS, move to LHS.
1628 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1629 Op0LHS->getName()+".masked");
1630 InsertNewInstBefore(NewLHS, I);
1631 return BinaryOperator::create(
1632 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1633 }
1634 }
1635
Chris Lattner86102b82005-01-01 16:22:27 +00001636 break;
1637 case Instruction::And:
1638 // (X & V) & C2 --> 0 iff (V & C2) == 0
1639 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1640 MaskedValueIsZero(Op0RHS, AndRHS))
1641 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1642 break;
1643 }
1644
Chris Lattner16464b32003-07-23 19:25:52 +00001645 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001646 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001647 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001648 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1649 const Type *SrcTy = CI->getOperand(0)->getType();
1650
Chris Lattner2c14cf72005-08-07 07:03:10 +00001651 // If this is an integer truncation or change from signed-to-unsigned, and
1652 // if the source is an and/or with immediate, transform it. This
1653 // frequently occurs for bitfield accesses.
1654 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1655 if (SrcTy->getPrimitiveSizeInBits() >=
1656 I.getType()->getPrimitiveSizeInBits() &&
1657 CastOp->getNumOperands() == 2)
1658 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1659 if (CastOp->getOpcode() == Instruction::And) {
1660 // Change: and (cast (and X, C1) to T), C2
1661 // into : and (cast X to T), trunc(C1)&C2
1662 // This will folds the two ands together, which may allow other
1663 // simplifications.
1664 Instruction *NewCast =
1665 new CastInst(CastOp->getOperand(0), I.getType(),
1666 CastOp->getName()+".shrunk");
1667 NewCast = InsertNewInstBefore(NewCast, I);
1668
1669 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1670 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1671 return BinaryOperator::createAnd(NewCast, C3);
1672 } else if (CastOp->getOpcode() == Instruction::Or) {
1673 // Change: and (cast (or X, C1) to T), C2
1674 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1675 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1676 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1677 return ReplaceInstUsesWith(I, AndRHS);
1678 }
1679 }
1680
1681
Chris Lattner86102b82005-01-01 16:22:27 +00001682 // If this is an integer sign or zero extension instruction.
1683 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001684 SrcTy->getPrimitiveSizeInBits() <
1685 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001686
1687 if (SrcTy->isUnsigned()) {
1688 // See if this and is clearing out bits that are known to be zero
1689 // anyway (due to the zero extension).
1690 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1691 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1692 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1693 if (Result == Mask) // The "and" isn't doing anything, remove it.
1694 return ReplaceInstUsesWith(I, CI);
1695 if (Result != AndRHS) { // Reduce the and RHS constant.
1696 I.setOperand(1, Result);
1697 return &I;
1698 }
1699
1700 } else {
1701 if (CI->hasOneUse() && SrcTy->isInteger()) {
1702 // We can only do this if all of the sign bits brought in are masked
1703 // out. Compute this by first getting 0000011111, then inverting
1704 // it.
1705 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1706 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1707 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1708 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1709 // If the and is clearing all of the sign bits, change this to a
1710 // zero extension cast. To do this, cast the cast input to
1711 // unsigned, then to the requested size.
1712 Value *CastOp = CI->getOperand(0);
1713 Instruction *NC =
1714 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1715 CI->getName()+".uns");
1716 NC = InsertNewInstBefore(NC, I);
1717 // Finally, insert a replacement for CI.
1718 NC = new CastInst(NC, CI->getType(), CI->getName());
1719 CI->setName("");
1720 NC = InsertNewInstBefore(NC, I);
1721 WorkList.push_back(CI); // Delete CI later.
1722 I.setOperand(0, NC);
1723 return &I; // The AND operand was modified.
1724 }
1725 }
1726 }
1727 }
Chris Lattner33217db2003-07-23 19:36:21 +00001728 }
Chris Lattner183b3362004-04-09 19:05:30 +00001729
1730 // Try to fold constant and into select arguments.
1731 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001732 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001733 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001734 if (isa<PHINode>(Op0))
1735 if (Instruction *NV = FoldOpIntoPhi(I))
1736 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001737 }
1738
Chris Lattnerbb74e222003-03-10 23:06:50 +00001739 Value *Op0NotVal = dyn_castNotVal(Op0);
1740 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001741
Chris Lattner023a4832004-06-18 06:07:51 +00001742 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1743 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1744
Misha Brukman9c003d82004-07-30 12:50:08 +00001745 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001746 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001747 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1748 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001749 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001750 return BinaryOperator::createNot(Or);
1751 }
1752
Chris Lattner623826c2004-09-28 21:48:02 +00001753 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1754 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001755 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1756 return R;
1757
Chris Lattner623826c2004-09-28 21:48:02 +00001758 Value *LHSVal, *RHSVal;
1759 ConstantInt *LHSCst, *RHSCst;
1760 Instruction::BinaryOps LHSCC, RHSCC;
1761 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1762 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1763 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1764 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001765 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001766 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1767 // Ensure that the larger constant is on the RHS.
1768 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1769 SetCondInst *LHS = cast<SetCondInst>(Op0);
1770 if (cast<ConstantBool>(Cmp)->getValue()) {
1771 std::swap(LHS, RHS);
1772 std::swap(LHSCst, RHSCst);
1773 std::swap(LHSCC, RHSCC);
1774 }
1775
1776 // At this point, we know we have have two setcc instructions
1777 // comparing a value against two constants and and'ing the result
1778 // together. Because of the above check, we know that we only have
1779 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1780 // FoldSetCCLogical check above), that the two constants are not
1781 // equal.
1782 assert(LHSCst != RHSCst && "Compares not folded above?");
1783
1784 switch (LHSCC) {
1785 default: assert(0 && "Unknown integer condition code!");
1786 case Instruction::SetEQ:
1787 switch (RHSCC) {
1788 default: assert(0 && "Unknown integer condition code!");
1789 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1790 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1791 return ReplaceInstUsesWith(I, ConstantBool::False);
1792 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1793 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1794 return ReplaceInstUsesWith(I, LHS);
1795 }
1796 case Instruction::SetNE:
1797 switch (RHSCC) {
1798 default: assert(0 && "Unknown integer condition code!");
1799 case Instruction::SetLT:
1800 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1801 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1802 break; // (X != 13 & X < 15) -> no change
1803 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1804 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1805 return ReplaceInstUsesWith(I, RHS);
1806 case Instruction::SetNE:
1807 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1808 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1809 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1810 LHSVal->getName()+".off");
1811 InsertNewInstBefore(Add, I);
1812 const Type *UnsType = Add->getType()->getUnsignedVersion();
1813 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1814 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1815 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1816 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1817 }
1818 break; // (X != 13 & X != 15) -> no change
1819 }
1820 break;
1821 case Instruction::SetLT:
1822 switch (RHSCC) {
1823 default: assert(0 && "Unknown integer condition code!");
1824 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1825 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1826 return ReplaceInstUsesWith(I, ConstantBool::False);
1827 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1828 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1829 return ReplaceInstUsesWith(I, LHS);
1830 }
1831 case Instruction::SetGT:
1832 switch (RHSCC) {
1833 default: assert(0 && "Unknown integer condition code!");
1834 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1835 return ReplaceInstUsesWith(I, LHS);
1836 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1837 return ReplaceInstUsesWith(I, RHS);
1838 case Instruction::SetNE:
1839 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1840 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1841 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001842 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1843 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001844 }
1845 }
1846 }
1847 }
1848
Chris Lattner113f4f42002-06-25 16:13:24 +00001849 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001850}
1851
Chris Lattner113f4f42002-06-25 16:13:24 +00001852Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001853 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001854 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001855
Chris Lattner81a7a232004-10-16 18:11:37 +00001856 if (isa<UndefValue>(Op1))
1857 return ReplaceInstUsesWith(I, // X | undef -> -1
1858 ConstantIntegral::getAllOnesValue(I.getType()));
1859
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001860 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001861 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1862 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001863
1864 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001865 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001866 // If X is known to only contain bits that already exist in RHS, just
1867 // replace this instruction with RHS directly.
1868 if (MaskedValueIsZero(Op0,
1869 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1870 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001871
Chris Lattnerd4252a72004-07-30 07:50:03 +00001872 ConstantInt *C1; Value *X;
1873 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1874 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00001875 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
1876 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00001877 InsertNewInstBefore(Or, I);
1878 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1879 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001880
Chris Lattnerd4252a72004-07-30 07:50:03 +00001881 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1882 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1883 std::string Op0Name = Op0->getName(); Op0->setName("");
1884 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1885 InsertNewInstBefore(Or, I);
1886 return BinaryOperator::createXor(Or,
1887 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001888 }
Chris Lattner183b3362004-04-09 19:05:30 +00001889
1890 // Try to fold constant and into select arguments.
1891 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001892 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001893 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001894 if (isa<PHINode>(Op0))
1895 if (Instruction *NV = FoldOpIntoPhi(I))
1896 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001897 }
1898
Chris Lattnerd4252a72004-07-30 07:50:03 +00001899 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattner4294cec2005-05-07 23:49:08 +00001900
1901 if (match(Op0, m_And(m_Value(A), m_Value(B))))
1902 if (A == Op1 || B == Op1) // (A & ?) | A --> A
1903 return ReplaceInstUsesWith(I, Op1);
1904 if (match(Op1, m_And(m_Value(A), m_Value(B))))
1905 if (A == Op0 || B == Op0) // A | (A & ?) --> A
1906 return ReplaceInstUsesWith(I, Op0);
1907
Chris Lattnerb62f5082005-05-09 04:58:36 +00001908 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
1909 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1910 MaskedValueIsZero(Op1, C1)) {
1911 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
1912 Op0->setName("");
1913 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
1914 }
1915
1916 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
1917 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
1918 MaskedValueIsZero(Op0, C1)) {
1919 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
1920 Op0->setName("");
1921 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
1922 }
1923
Chris Lattner15212982005-09-18 03:42:07 +00001924 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001925 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00001926 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
1927
1928 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
1929 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
1930
1931
1932 // if A == (add B, C3) or B == (add A, C4)
1933 ConstantInt *C3 = 0;
1934 Value *V = 0;
1935 if ((match(A, m_Add(m_Value(V), m_ConstantInt(C3))) && V == B ||
1936 match(B, m_Add(m_Value(V), m_ConstantInt(C3))) && V == A)) {
1937 if (V == A) std::swap(C1, C2);
1938 // We have: ((V + C3) & C1) | (V & C2)
1939 // if C2 = ~C1 and (C3 & C2) == 0 and C2 is 0+1+
1940 if (C1 == ConstantExpr::getNot(C2) &&
1941 ConstantExpr::getAnd(C3, C2)->isNullValue() &&
1942 (C2->getRawValue() & (C2->getRawValue()+1)) == 0) {
1943 // Return V+C3.
1944 std::cerr << "Simpl: " << *A << "Simpl2: " << *B << "Simpl3: " << I;
1945 return ReplaceInstUsesWith(I, V == A ? B : A);
1946 }
1947 }
1948 }
Chris Lattner812aab72003-08-12 19:11:07 +00001949
Chris Lattnerd4252a72004-07-30 07:50:03 +00001950 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1951 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00001952 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00001953 ConstantIntegral::getAllOnesValue(I.getType()));
1954 } else {
1955 A = 0;
1956 }
Chris Lattner4294cec2005-05-07 23:49:08 +00001957 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00001958 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1959 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00001960 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00001961 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001962
Misha Brukman9c003d82004-07-30 12:50:08 +00001963 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001964 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1965 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1966 I.getName()+".demorgan"), I);
1967 return BinaryOperator::createNot(And);
1968 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001969 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001970
Chris Lattner3ac7c262003-08-13 20:16:26 +00001971 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001972 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001973 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1974 return R;
1975
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001976 Value *LHSVal, *RHSVal;
1977 ConstantInt *LHSCst, *RHSCst;
1978 Instruction::BinaryOps LHSCC, RHSCC;
1979 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1980 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1981 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1982 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001983 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001984 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1985 // Ensure that the larger constant is on the RHS.
1986 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1987 SetCondInst *LHS = cast<SetCondInst>(Op0);
1988 if (cast<ConstantBool>(Cmp)->getValue()) {
1989 std::swap(LHS, RHS);
1990 std::swap(LHSCst, RHSCst);
1991 std::swap(LHSCC, RHSCC);
1992 }
1993
1994 // At this point, we know we have have two setcc instructions
1995 // comparing a value against two constants and or'ing the result
1996 // together. Because of the above check, we know that we only have
1997 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1998 // FoldSetCCLogical check above), that the two constants are not
1999 // equal.
2000 assert(LHSCst != RHSCst && "Compares not folded above?");
2001
2002 switch (LHSCC) {
2003 default: assert(0 && "Unknown integer condition code!");
2004 case Instruction::SetEQ:
2005 switch (RHSCC) {
2006 default: assert(0 && "Unknown integer condition code!");
2007 case Instruction::SetEQ:
2008 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2009 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2010 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2011 LHSVal->getName()+".off");
2012 InsertNewInstBefore(Add, I);
2013 const Type *UnsType = Add->getType()->getUnsignedVersion();
2014 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2015 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2016 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2017 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2018 }
2019 break; // (X == 13 | X == 15) -> no change
2020
Chris Lattner5c219462005-04-19 06:04:18 +00002021 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2022 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002023 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2024 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2025 return ReplaceInstUsesWith(I, RHS);
2026 }
2027 break;
2028 case Instruction::SetNE:
2029 switch (RHSCC) {
2030 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002031 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2032 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2033 return ReplaceInstUsesWith(I, LHS);
2034 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002035 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002036 return ReplaceInstUsesWith(I, ConstantBool::True);
2037 }
2038 break;
2039 case Instruction::SetLT:
2040 switch (RHSCC) {
2041 default: assert(0 && "Unknown integer condition code!");
2042 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2043 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002044 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2045 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002046 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2047 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2048 return ReplaceInstUsesWith(I, RHS);
2049 }
2050 break;
2051 case Instruction::SetGT:
2052 switch (RHSCC) {
2053 default: assert(0 && "Unknown integer condition code!");
2054 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2055 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2056 return ReplaceInstUsesWith(I, LHS);
2057 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2058 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2059 return ReplaceInstUsesWith(I, ConstantBool::True);
2060 }
2061 }
2062 }
2063 }
Chris Lattner15212982005-09-18 03:42:07 +00002064
Chris Lattner113f4f42002-06-25 16:13:24 +00002065 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002066}
2067
Chris Lattnerc2076352004-02-16 01:20:27 +00002068// XorSelf - Implements: X ^ X --> 0
2069struct XorSelf {
2070 Value *RHS;
2071 XorSelf(Value *rhs) : RHS(rhs) {}
2072 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2073 Instruction *apply(BinaryOperator &Xor) const {
2074 return &Xor;
2075 }
2076};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002077
2078
Chris Lattner113f4f42002-06-25 16:13:24 +00002079Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002080 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002081 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002082
Chris Lattner81a7a232004-10-16 18:11:37 +00002083 if (isa<UndefValue>(Op1))
2084 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2085
Chris Lattnerc2076352004-02-16 01:20:27 +00002086 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2087 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2088 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002089 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002090 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002091
Chris Lattner97638592003-07-23 21:37:07 +00002092 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002093 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002094 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002095 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002096
Chris Lattner97638592003-07-23 21:37:07 +00002097 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002098 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002099 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002100 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002101 return new SetCondInst(SCI->getInverseCondition(),
2102 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002103
Chris Lattner8f2f5982003-11-05 01:06:05 +00002104 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002105 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2106 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002107 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2108 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002109 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002110 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002111 }
Chris Lattner023a4832004-06-18 06:07:51 +00002112
2113 // ~(~X & Y) --> (X | ~Y)
2114 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2115 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2116 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2117 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002118 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002119 Op0I->getOperand(1)->getName()+".not");
2120 InsertNewInstBefore(NotY, I);
2121 return BinaryOperator::createOr(Op0NotVal, NotY);
2122 }
2123 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002124
Chris Lattner97638592003-07-23 21:37:07 +00002125 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002126 switch (Op0I->getOpcode()) {
2127 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002128 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002129 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002130 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2131 return BinaryOperator::createSub(
2132 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002133 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002134 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002135 }
Chris Lattnere5806662003-11-04 23:50:51 +00002136 break;
2137 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002138 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002139 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2140 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002141 break;
2142 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002143 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002144 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002145 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002146 break;
2147 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002148 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002149 }
Chris Lattner183b3362004-04-09 19:05:30 +00002150
2151 // Try to fold constant and into select arguments.
2152 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002153 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002154 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002155 if (isa<PHINode>(Op0))
2156 if (Instruction *NV = FoldOpIntoPhi(I))
2157 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002158 }
2159
Chris Lattnerbb74e222003-03-10 23:06:50 +00002160 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002161 if (X == Op1)
2162 return ReplaceInstUsesWith(I,
2163 ConstantIntegral::getAllOnesValue(I.getType()));
2164
Chris Lattnerbb74e222003-03-10 23:06:50 +00002165 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002166 if (X == Op0)
2167 return ReplaceInstUsesWith(I,
2168 ConstantIntegral::getAllOnesValue(I.getType()));
2169
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002170 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002171 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002172 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2173 cast<BinaryOperator>(Op1I)->swapOperands();
2174 I.swapOperands();
2175 std::swap(Op0, Op1);
2176 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2177 I.swapOperands();
2178 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002179 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002180 } else if (Op1I->getOpcode() == Instruction::Xor) {
2181 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2182 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2183 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2184 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2185 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002186
2187 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002188 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002189 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2190 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002191 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002192 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2193 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002194 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002195 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002196 } else if (Op0I->getOpcode() == Instruction::Xor) {
2197 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2198 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2199 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2200 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002201 }
2202
Chris Lattner7aa2d472004-08-01 19:42:59 +00002203 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002204 Value *A, *B; ConstantInt *C1, *C2;
2205 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2206 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002207 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002208 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002209
Chris Lattner3ac7c262003-08-13 20:16:26 +00002210 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2211 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2212 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2213 return R;
2214
Chris Lattner113f4f42002-06-25 16:13:24 +00002215 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002216}
2217
Chris Lattner6862fbd2004-09-29 17:40:11 +00002218/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2219/// overflowed for this type.
2220static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2221 ConstantInt *In2) {
2222 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2223 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2224}
2225
2226static bool isPositive(ConstantInt *C) {
2227 return cast<ConstantSInt>(C)->getValue() >= 0;
2228}
2229
2230/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2231/// overflowed for this type.
2232static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2233 ConstantInt *In2) {
2234 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2235
2236 if (In1->getType()->isUnsigned())
2237 return cast<ConstantUInt>(Result)->getValue() <
2238 cast<ConstantUInt>(In1)->getValue();
2239 if (isPositive(In1) != isPositive(In2))
2240 return false;
2241 if (isPositive(In1))
2242 return cast<ConstantSInt>(Result)->getValue() <
2243 cast<ConstantSInt>(In1)->getValue();
2244 return cast<ConstantSInt>(Result)->getValue() >
2245 cast<ConstantSInt>(In1)->getValue();
2246}
2247
Chris Lattner0798af32005-01-13 20:14:25 +00002248/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2249/// code necessary to compute the offset from the base pointer (without adding
2250/// in the base pointer). Return the result as a signed integer of intptr size.
2251static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2252 TargetData &TD = IC.getTargetData();
2253 gep_type_iterator GTI = gep_type_begin(GEP);
2254 const Type *UIntPtrTy = TD.getIntPtrType();
2255 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2256 Value *Result = Constant::getNullValue(SIntPtrTy);
2257
2258 // Build a mask for high order bits.
2259 uint64_t PtrSizeMask = ~0ULL;
2260 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2261
Chris Lattner0798af32005-01-13 20:14:25 +00002262 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2263 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002264 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002265 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2266 SIntPtrTy);
2267 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2268 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002269 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002270 Scale = ConstantExpr::getMul(OpC, Scale);
2271 if (Constant *RC = dyn_cast<Constant>(Result))
2272 Result = ConstantExpr::getAdd(RC, Scale);
2273 else {
2274 // Emit an add instruction.
2275 Result = IC.InsertNewInstBefore(
2276 BinaryOperator::createAdd(Result, Scale,
2277 GEP->getName()+".offs"), I);
2278 }
2279 }
2280 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002281 // Convert to correct type.
2282 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2283 Op->getName()+".c"), I);
2284 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002285 // We'll let instcombine(mul) convert this to a shl if possible.
2286 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2287 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002288
2289 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002290 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002291 GEP->getName()+".offs"), I);
2292 }
2293 }
2294 return Result;
2295}
2296
2297/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2298/// else. At this point we know that the GEP is on the LHS of the comparison.
2299Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2300 Instruction::BinaryOps Cond,
2301 Instruction &I) {
2302 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002303
2304 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2305 if (isa<PointerType>(CI->getOperand(0)->getType()))
2306 RHS = CI->getOperand(0);
2307
Chris Lattner0798af32005-01-13 20:14:25 +00002308 Value *PtrBase = GEPLHS->getOperand(0);
2309 if (PtrBase == RHS) {
2310 // As an optimization, we don't actually have to compute the actual value of
2311 // OFFSET if this is a seteq or setne comparison, just return whether each
2312 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002313 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2314 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002315 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2316 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002317 bool EmitIt = true;
2318 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2319 if (isa<UndefValue>(C)) // undef index -> undef.
2320 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2321 if (C->isNullValue())
2322 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002323 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2324 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002325 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002326 return ReplaceInstUsesWith(I, // No comparison is needed here.
2327 ConstantBool::get(Cond == Instruction::SetNE));
2328 }
2329
2330 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002331 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002332 new SetCondInst(Cond, GEPLHS->getOperand(i),
2333 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2334 if (InVal == 0)
2335 InVal = Comp;
2336 else {
2337 InVal = InsertNewInstBefore(InVal, I);
2338 InsertNewInstBefore(Comp, I);
2339 if (Cond == Instruction::SetNE) // True if any are unequal
2340 InVal = BinaryOperator::createOr(InVal, Comp);
2341 else // True if all are equal
2342 InVal = BinaryOperator::createAnd(InVal, Comp);
2343 }
2344 }
2345 }
2346
2347 if (InVal)
2348 return InVal;
2349 else
2350 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2351 ConstantBool::get(Cond == Instruction::SetEQ));
2352 }
Chris Lattner0798af32005-01-13 20:14:25 +00002353
2354 // Only lower this if the setcc is the only user of the GEP or if we expect
2355 // the result to fold to a constant!
2356 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2357 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2358 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2359 return new SetCondInst(Cond, Offset,
2360 Constant::getNullValue(Offset->getType()));
2361 }
2362 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002363 // If the base pointers are different, but the indices are the same, just
2364 // compare the base pointer.
2365 if (PtrBase != GEPRHS->getOperand(0)) {
2366 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002367 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002368 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002369 if (IndicesTheSame)
2370 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2371 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2372 IndicesTheSame = false;
2373 break;
2374 }
2375
2376 // If all indices are the same, just compare the base pointers.
2377 if (IndicesTheSame)
2378 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2379 GEPRHS->getOperand(0));
2380
2381 // Otherwise, the base pointers are different and the indices are
2382 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002383 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002384 }
Chris Lattner0798af32005-01-13 20:14:25 +00002385
Chris Lattner81e84172005-01-13 22:25:21 +00002386 // If one of the GEPs has all zero indices, recurse.
2387 bool AllZeros = true;
2388 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2389 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2390 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2391 AllZeros = false;
2392 break;
2393 }
2394 if (AllZeros)
2395 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2396 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002397
2398 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002399 AllZeros = true;
2400 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2401 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2402 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2403 AllZeros = false;
2404 break;
2405 }
2406 if (AllZeros)
2407 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2408
Chris Lattner4fa89822005-01-14 00:20:05 +00002409 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2410 // If the GEPs only differ by one index, compare it.
2411 unsigned NumDifferences = 0; // Keep track of # differences.
2412 unsigned DiffOperand = 0; // The operand that differs.
2413 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2414 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002415 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2416 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002417 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002418 NumDifferences = 2;
2419 break;
2420 } else {
2421 if (NumDifferences++) break;
2422 DiffOperand = i;
2423 }
2424 }
2425
2426 if (NumDifferences == 0) // SAME GEP?
2427 return ReplaceInstUsesWith(I, // No comparison is needed here.
2428 ConstantBool::get(Cond == Instruction::SetEQ));
2429 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002430 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2431 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002432
2433 // Convert the operands to signed values to make sure to perform a
2434 // signed comparison.
2435 const Type *NewTy = LHSV->getType()->getSignedVersion();
2436 if (LHSV->getType() != NewTy)
2437 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2438 LHSV->getName()), I);
2439 if (RHSV->getType() != NewTy)
2440 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2441 RHSV->getName()), I);
2442 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002443 }
2444 }
2445
Chris Lattner0798af32005-01-13 20:14:25 +00002446 // Only lower this if the setcc is the only user of the GEP or if we expect
2447 // the result to fold to a constant!
2448 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2449 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2450 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2451 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2452 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2453 return new SetCondInst(Cond, L, R);
2454 }
2455 }
2456 return 0;
2457}
2458
2459
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002460Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002461 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002462 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2463 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002464
2465 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002466 if (Op0 == Op1)
2467 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002468
Chris Lattner81a7a232004-10-16 18:11:37 +00002469 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2470 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2471
Chris Lattner15ff1e12004-11-14 07:33:16 +00002472 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2473 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002474 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2475 isa<ConstantPointerNull>(Op0)) &&
2476 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002477 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002478 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2479
2480 // setcc's with boolean values can always be turned into bitwise operations
2481 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002482 switch (I.getOpcode()) {
2483 default: assert(0 && "Invalid setcc instruction!");
2484 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002485 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002486 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002487 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002488 }
Chris Lattner4456da62004-08-11 00:50:51 +00002489 case Instruction::SetNE:
2490 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002491
Chris Lattner4456da62004-08-11 00:50:51 +00002492 case Instruction::SetGT:
2493 std::swap(Op0, Op1); // Change setgt -> setlt
2494 // FALL THROUGH
2495 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2496 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2497 InsertNewInstBefore(Not, I);
2498 return BinaryOperator::createAnd(Not, Op1);
2499 }
2500 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002501 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002502 // FALL THROUGH
2503 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2504 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2505 InsertNewInstBefore(Not, I);
2506 return BinaryOperator::createOr(Not, Op1);
2507 }
2508 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002509 }
2510
Chris Lattner2dd01742004-06-09 04:24:29 +00002511 // See if we are doing a comparison between a constant and an instruction that
2512 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002513 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002514 // Check to see if we are comparing against the minimum or maximum value...
2515 if (CI->isMinValue()) {
2516 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2517 return ReplaceInstUsesWith(I, ConstantBool::False);
2518 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2519 return ReplaceInstUsesWith(I, ConstantBool::True);
2520 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2521 return BinaryOperator::createSetEQ(Op0, Op1);
2522 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2523 return BinaryOperator::createSetNE(Op0, Op1);
2524
2525 } else if (CI->isMaxValue()) {
2526 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2527 return ReplaceInstUsesWith(I, ConstantBool::False);
2528 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2529 return ReplaceInstUsesWith(I, ConstantBool::True);
2530 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2531 return BinaryOperator::createSetEQ(Op0, Op1);
2532 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2533 return BinaryOperator::createSetNE(Op0, Op1);
2534
2535 // Comparing against a value really close to min or max?
2536 } else if (isMinValuePlusOne(CI)) {
2537 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2538 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2539 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2540 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2541
2542 } else if (isMaxValueMinusOne(CI)) {
2543 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2544 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2545 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2546 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2547 }
2548
2549 // If we still have a setle or setge instruction, turn it into the
2550 // appropriate setlt or setgt instruction. Since the border cases have
2551 // already been handled above, this requires little checking.
2552 //
2553 if (I.getOpcode() == Instruction::SetLE)
2554 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2555 if (I.getOpcode() == Instruction::SetGE)
2556 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2557
Chris Lattnere1e10e12004-05-25 06:32:08 +00002558 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002559 switch (LHSI->getOpcode()) {
2560 case Instruction::And:
2561 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2562 LHSI->getOperand(0)->hasOneUse()) {
2563 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2564 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2565 // happens a LOT in code produced by the C front-end, for bitfield
2566 // access.
2567 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2568 ConstantUInt *ShAmt;
2569 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2570 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2571 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002572
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002573 // We can fold this as long as we can't shift unknown bits
2574 // into the mask. This can only happen with signed shift
2575 // rights, as they sign-extend.
2576 if (ShAmt) {
2577 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002578 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002579 if (!CanFold) {
2580 // To test for the bad case of the signed shr, see if any
2581 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002582 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2583 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2584
2585 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002586 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002587 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2588 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2589 CanFold = true;
2590 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002591
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002592 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002593 Constant *NewCst;
2594 if (Shift->getOpcode() == Instruction::Shl)
2595 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2596 else
2597 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002598
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002599 // Check to see if we are shifting out any of the bits being
2600 // compared.
2601 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2602 // If we shifted bits out, the fold is not going to work out.
2603 // As a special case, check to see if this means that the
2604 // result is always true or false now.
2605 if (I.getOpcode() == Instruction::SetEQ)
2606 return ReplaceInstUsesWith(I, ConstantBool::False);
2607 if (I.getOpcode() == Instruction::SetNE)
2608 return ReplaceInstUsesWith(I, ConstantBool::True);
2609 } else {
2610 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002611 Constant *NewAndCST;
2612 if (Shift->getOpcode() == Instruction::Shl)
2613 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2614 else
2615 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2616 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002617 LHSI->setOperand(0, Shift->getOperand(0));
2618 WorkList.push_back(Shift); // Shift is dead.
2619 AddUsesToWorkList(I);
2620 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002621 }
2622 }
Chris Lattner35167c32004-06-09 07:59:58 +00002623 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002624 }
2625 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002626
Chris Lattner272d5ca2004-09-28 18:22:15 +00002627 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2628 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2629 switch (I.getOpcode()) {
2630 default: break;
2631 case Instruction::SetEQ:
2632 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002633 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2634
2635 // Check that the shift amount is in range. If not, don't perform
2636 // undefined shifts. When the shift is visited it will be
2637 // simplified.
2638 if (ShAmt->getValue() >= TypeBits)
2639 break;
2640
Chris Lattner272d5ca2004-09-28 18:22:15 +00002641 // If we are comparing against bits always shifted out, the
2642 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002643 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002644 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2645 if (Comp != CI) {// Comparing against a bit that we know is zero.
2646 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2647 Constant *Cst = ConstantBool::get(IsSetNE);
2648 return ReplaceInstUsesWith(I, Cst);
2649 }
2650
2651 if (LHSI->hasOneUse()) {
2652 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002653 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002654 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2655
2656 Constant *Mask;
2657 if (CI->getType()->isUnsigned()) {
2658 Mask = ConstantUInt::get(CI->getType(), Val);
2659 } else if (ShAmtVal != 0) {
2660 Mask = ConstantSInt::get(CI->getType(), Val);
2661 } else {
2662 Mask = ConstantInt::getAllOnesValue(CI->getType());
2663 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002664
Chris Lattner272d5ca2004-09-28 18:22:15 +00002665 Instruction *AndI =
2666 BinaryOperator::createAnd(LHSI->getOperand(0),
2667 Mask, LHSI->getName()+".mask");
2668 Value *And = InsertNewInstBefore(AndI, I);
2669 return new SetCondInst(I.getOpcode(), And,
2670 ConstantExpr::getUShr(CI, ShAmt));
2671 }
2672 }
2673 }
2674 }
2675 break;
2676
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002677 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002678 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002679 switch (I.getOpcode()) {
2680 default: break;
2681 case Instruction::SetEQ:
2682 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002683
2684 // Check that the shift amount is in range. If not, don't perform
2685 // undefined shifts. When the shift is visited it will be
2686 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002687 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002688 if (ShAmt->getValue() >= TypeBits)
2689 break;
2690
Chris Lattner1023b872004-09-27 16:18:50 +00002691 // If we are comparing against bits always shifted out, the
2692 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002693 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002694 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002695
Chris Lattner1023b872004-09-27 16:18:50 +00002696 if (Comp != CI) {// Comparing against a bit that we know is zero.
2697 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2698 Constant *Cst = ConstantBool::get(IsSetNE);
2699 return ReplaceInstUsesWith(I, Cst);
2700 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002701
Chris Lattner1023b872004-09-27 16:18:50 +00002702 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002703 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002704
Chris Lattner1023b872004-09-27 16:18:50 +00002705 // Otherwise strength reduce the shift into an and.
2706 uint64_t Val = ~0ULL; // All ones.
2707 Val <<= ShAmtVal; // Shift over to the right spot.
2708
2709 Constant *Mask;
2710 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002711 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002712 Mask = ConstantUInt::get(CI->getType(), Val);
2713 } else {
2714 Mask = ConstantSInt::get(CI->getType(), Val);
2715 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002716
Chris Lattner1023b872004-09-27 16:18:50 +00002717 Instruction *AndI =
2718 BinaryOperator::createAnd(LHSI->getOperand(0),
2719 Mask, LHSI->getName()+".mask");
2720 Value *And = InsertNewInstBefore(AndI, I);
2721 return new SetCondInst(I.getOpcode(), And,
2722 ConstantExpr::getShl(CI, ShAmt));
2723 }
2724 break;
2725 }
2726 }
2727 }
2728 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002729
Chris Lattner6862fbd2004-09-29 17:40:11 +00002730 case Instruction::Div:
2731 // Fold: (div X, C1) op C2 -> range check
2732 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2733 // Fold this div into the comparison, producing a range check.
2734 // Determine, based on the divide type, what the range is being
2735 // checked. If there is an overflow on the low or high side, remember
2736 // it, otherwise compute the range [low, hi) bounding the new value.
2737 bool LoOverflow = false, HiOverflow = 0;
2738 ConstantInt *LoBound = 0, *HiBound = 0;
2739
2740 ConstantInt *Prod;
2741 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2742
Chris Lattnera92af962004-10-11 19:40:04 +00002743 Instruction::BinaryOps Opcode = I.getOpcode();
2744
Chris Lattner6862fbd2004-09-29 17:40:11 +00002745 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2746 } else if (LHSI->getType()->isUnsigned()) { // udiv
2747 LoBound = Prod;
2748 LoOverflow = ProdOV;
2749 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2750 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2751 if (CI->isNullValue()) { // (X / pos) op 0
2752 // Can't overflow.
2753 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2754 HiBound = DivRHS;
2755 } else if (isPositive(CI)) { // (X / pos) op pos
2756 LoBound = Prod;
2757 LoOverflow = ProdOV;
2758 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2759 } else { // (X / pos) op neg
2760 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2761 LoOverflow = AddWithOverflow(LoBound, Prod,
2762 cast<ConstantInt>(DivRHSH));
2763 HiBound = Prod;
2764 HiOverflow = ProdOV;
2765 }
2766 } else { // Divisor is < 0.
2767 if (CI->isNullValue()) { // (X / neg) op 0
2768 LoBound = AddOne(DivRHS);
2769 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002770 if (HiBound == DivRHS)
2771 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002772 } else if (isPositive(CI)) { // (X / neg) op pos
2773 HiOverflow = LoOverflow = ProdOV;
2774 if (!LoOverflow)
2775 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2776 HiBound = AddOne(Prod);
2777 } else { // (X / neg) op neg
2778 LoBound = Prod;
2779 LoOverflow = HiOverflow = ProdOV;
2780 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2781 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002782
Chris Lattnera92af962004-10-11 19:40:04 +00002783 // Dividing by a negate swaps the condition.
2784 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002785 }
2786
2787 if (LoBound) {
2788 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002789 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002790 default: assert(0 && "Unhandled setcc opcode!");
2791 case Instruction::SetEQ:
2792 if (LoOverflow && HiOverflow)
2793 return ReplaceInstUsesWith(I, ConstantBool::False);
2794 else if (HiOverflow)
2795 return new SetCondInst(Instruction::SetGE, X, LoBound);
2796 else if (LoOverflow)
2797 return new SetCondInst(Instruction::SetLT, X, HiBound);
2798 else
2799 return InsertRangeTest(X, LoBound, HiBound, true, I);
2800 case Instruction::SetNE:
2801 if (LoOverflow && HiOverflow)
2802 return ReplaceInstUsesWith(I, ConstantBool::True);
2803 else if (HiOverflow)
2804 return new SetCondInst(Instruction::SetLT, X, LoBound);
2805 else if (LoOverflow)
2806 return new SetCondInst(Instruction::SetGE, X, HiBound);
2807 else
2808 return InsertRangeTest(X, LoBound, HiBound, false, I);
2809 case Instruction::SetLT:
2810 if (LoOverflow)
2811 return ReplaceInstUsesWith(I, ConstantBool::False);
2812 return new SetCondInst(Instruction::SetLT, X, LoBound);
2813 case Instruction::SetGT:
2814 if (HiOverflow)
2815 return ReplaceInstUsesWith(I, ConstantBool::False);
2816 return new SetCondInst(Instruction::SetGE, X, HiBound);
2817 }
2818 }
2819 }
2820 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002821 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002822
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002823 // Simplify seteq and setne instructions...
2824 if (I.getOpcode() == Instruction::SetEQ ||
2825 I.getOpcode() == Instruction::SetNE) {
2826 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2827
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002828 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002829 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002830 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2831 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002832 case Instruction::Rem:
2833 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2834 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2835 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00002836 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
2837 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
2838 if (isPowerOf2_64(V)) {
2839 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00002840 const Type *UTy = BO->getType()->getUnsignedVersion();
2841 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2842 UTy, "tmp"), I);
2843 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2844 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2845 RHSCst, BO->getName()), I);
2846 return BinaryOperator::create(I.getOpcode(), NewRem,
2847 Constant::getNullValue(UTy));
2848 }
Chris Lattner22d00a82005-08-02 19:16:58 +00002849 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002850 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00002851
Chris Lattnerc992add2003-08-13 05:33:12 +00002852 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002853 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2854 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002855 if (BO->hasOneUse())
2856 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2857 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002858 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002859 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2860 // efficiently invertible, or if the add has just this one use.
2861 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002862
Chris Lattnerc992add2003-08-13 05:33:12 +00002863 if (Value *NegVal = dyn_castNegVal(BOp1))
2864 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2865 else if (Value *NegVal = dyn_castNegVal(BOp0))
2866 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002867 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002868 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2869 BO->setName("");
2870 InsertNewInstBefore(Neg, I);
2871 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2872 }
2873 }
2874 break;
2875 case Instruction::Xor:
2876 // For the xor case, we can xor two constants together, eliminating
2877 // the explicit xor.
2878 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2879 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002880 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002881
2882 // FALLTHROUGH
2883 case Instruction::Sub:
2884 // Replace (([sub|xor] A, B) != 0) with (A != B)
2885 if (CI->isNullValue())
2886 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2887 BO->getOperand(1));
2888 break;
2889
2890 case Instruction::Or:
2891 // If bits are being or'd in that are not present in the constant we
2892 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002893 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002894 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002895 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002896 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002897 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002898 break;
2899
2900 case Instruction::And:
2901 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002902 // If bits are being compared against that are and'd out, then the
2903 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002904 if (!ConstantExpr::getAnd(CI,
2905 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002906 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002907
Chris Lattner35167c32004-06-09 07:59:58 +00002908 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002909 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002910 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2911 Instruction::SetNE, Op0,
2912 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002913
Chris Lattnerc992add2003-08-13 05:33:12 +00002914 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2915 // to be a signed value as appropriate.
2916 if (isSignBit(BOC)) {
2917 Value *X = BO->getOperand(0);
2918 // If 'X' is not signed, insert a cast now...
2919 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002920 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002921 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002922 }
2923 return new SetCondInst(isSetNE ? Instruction::SetLT :
2924 Instruction::SetGE, X,
2925 Constant::getNullValue(X->getType()));
2926 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002927
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002928 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002929 if (CI->isNullValue() && isHighOnes(BOC)) {
2930 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002931 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002932
2933 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002934 if (NegX->getType()->isSigned()) {
2935 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2936 X = InsertCastBefore(X, DestTy, I);
2937 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002938 }
2939
2940 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002941 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002942 }
2943
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002944 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002945 default: break;
2946 }
2947 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002948 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00002949 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002950 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2951 Value *CastOp = Cast->getOperand(0);
2952 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002953 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00002954 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002955 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002956 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00002957 "Source and destination signednesses should differ!");
2958 if (Cast->getType()->isSigned()) {
2959 // If this is a signed comparison, check for comparisons in the
2960 // vicinity of zero.
2961 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2962 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002963 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002964 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002965 else if (I.getOpcode() == Instruction::SetGT &&
2966 cast<ConstantSInt>(CI)->getValue() == -1)
2967 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002968 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002969 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002970 } else {
2971 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2972 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002973 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00002974 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002975 return BinaryOperator::createSetGT(CastOp,
2976 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002977 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002978 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00002979 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002980 return BinaryOperator::createSetLT(CastOp,
2981 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002982 }
2983 }
2984 }
Chris Lattnere967b342003-06-04 05:10:11 +00002985 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002986 }
2987
Chris Lattner77c32c32005-04-23 15:31:55 +00002988 // Handle setcc with constant RHS's that can be integer, FP or pointer.
2989 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
2990 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2991 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00002992 case Instruction::GetElementPtr:
2993 if (RHSC->isNullValue()) {
2994 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
2995 bool isAllZeros = true;
2996 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
2997 if (!isa<Constant>(LHSI->getOperand(i)) ||
2998 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
2999 isAllZeros = false;
3000 break;
3001 }
3002 if (isAllZeros)
3003 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3004 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3005 }
3006 break;
3007
Chris Lattner77c32c32005-04-23 15:31:55 +00003008 case Instruction::PHI:
3009 if (Instruction *NV = FoldOpIntoPhi(I))
3010 return NV;
3011 break;
3012 case Instruction::Select:
3013 // If either operand of the select is a constant, we can fold the
3014 // comparison into the select arms, which will cause one to be
3015 // constant folded and the select turned into a bitwise or.
3016 Value *Op1 = 0, *Op2 = 0;
3017 if (LHSI->hasOneUse()) {
3018 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3019 // Fold the known value into the constant operand.
3020 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3021 // Insert a new SetCC of the other select operand.
3022 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3023 LHSI->getOperand(2), RHSC,
3024 I.getName()), I);
3025 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3026 // Fold the known value into the constant operand.
3027 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3028 // Insert a new SetCC of the other select operand.
3029 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3030 LHSI->getOperand(1), RHSC,
3031 I.getName()), I);
3032 }
3033 }
Jeff Cohen82639852005-04-23 21:38:35 +00003034
Chris Lattner77c32c32005-04-23 15:31:55 +00003035 if (Op1)
3036 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3037 break;
3038 }
3039 }
3040
Chris Lattner0798af32005-01-13 20:14:25 +00003041 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3042 if (User *GEP = dyn_castGetElementPtr(Op0))
3043 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3044 return NI;
3045 if (User *GEP = dyn_castGetElementPtr(Op1))
3046 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3047 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3048 return NI;
3049
Chris Lattner16930792003-11-03 04:25:02 +00003050 // Test to see if the operands of the setcc are casted versions of other
3051 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003052 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3053 Value *CastOp0 = CI->getOperand(0);
3054 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003055 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003056 (I.getOpcode() == Instruction::SetEQ ||
3057 I.getOpcode() == Instruction::SetNE)) {
3058 // We keep moving the cast from the left operand over to the right
3059 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003060 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003061
Chris Lattner16930792003-11-03 04:25:02 +00003062 // If operand #1 is a cast instruction, see if we can eliminate it as
3063 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003064 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3065 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003066 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003067 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003068
Chris Lattner16930792003-11-03 04:25:02 +00003069 // If Op1 is a constant, we can fold the cast into the constant.
3070 if (Op1->getType() != Op0->getType())
3071 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3072 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3073 } else {
3074 // Otherwise, cast the RHS right before the setcc
3075 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3076 InsertNewInstBefore(cast<Instruction>(Op1), I);
3077 }
3078 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3079 }
3080
Chris Lattner6444c372003-11-03 05:17:03 +00003081 // Handle the special case of: setcc (cast bool to X), <cst>
3082 // This comes up when you have code like
3083 // int X = A < B;
3084 // if (X) ...
3085 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003086 // with a constant or another cast from the same type.
3087 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3088 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3089 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003090 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003091 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003092}
3093
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003094// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3095// We only handle extending casts so far.
3096//
3097Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3098 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3099 const Type *SrcTy = LHSCIOp->getType();
3100 const Type *DestTy = SCI.getOperand(0)->getType();
3101 Value *RHSCIOp;
3102
3103 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003104 return 0;
3105
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003106 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3107 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3108 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3109
3110 // Is this a sign or zero extension?
3111 bool isSignSrc = SrcTy->isSigned();
3112 bool isSignDest = DestTy->isSigned();
3113
3114 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3115 // Not an extension from the same type?
3116 RHSCIOp = CI->getOperand(0);
3117 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3118 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3119 // Compute the constant that would happen if we truncated to SrcTy then
3120 // reextended to DestTy.
3121 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3122
3123 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3124 RHSCIOp = Res;
3125 } else {
3126 // If the value cannot be represented in the shorter type, we cannot emit
3127 // a simple comparison.
3128 if (SCI.getOpcode() == Instruction::SetEQ)
3129 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3130 if (SCI.getOpcode() == Instruction::SetNE)
3131 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3132
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003133 // Evaluate the comparison for LT.
3134 Value *Result;
3135 if (DestTy->isSigned()) {
3136 // We're performing a signed comparison.
3137 if (isSignSrc) {
3138 // Signed extend and signed comparison.
3139 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3140 Result = ConstantBool::False;
3141 else
3142 Result = ConstantBool::True; // X < (large) --> true
3143 } else {
3144 // Unsigned extend and signed comparison.
3145 if (cast<ConstantSInt>(CI)->getValue() < 0)
3146 Result = ConstantBool::False;
3147 else
3148 Result = ConstantBool::True;
3149 }
3150 } else {
3151 // We're performing an unsigned comparison.
3152 if (!isSignSrc) {
3153 // Unsigned extend & compare -> always true.
3154 Result = ConstantBool::True;
3155 } else {
3156 // We're performing an unsigned comp with a sign extended value.
3157 // This is true if the input is >= 0. [aka >s -1]
3158 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3159 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3160 NegOne, SCI.getName()), SCI);
3161 }
Reid Spencer279fa252004-11-28 21:31:15 +00003162 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003163
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003164 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003165 if (SCI.getOpcode() == Instruction::SetLT) {
3166 return ReplaceInstUsesWith(SCI, Result);
3167 } else {
3168 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3169 if (Constant *CI = dyn_cast<Constant>(Result))
3170 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3171 else
3172 return BinaryOperator::createNot(Result);
3173 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003174 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003175 } else {
3176 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003177 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003178
Chris Lattner252a8452005-06-16 03:00:08 +00003179 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003180 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3181}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003182
Chris Lattnere8d6c602003-03-10 19:16:08 +00003183Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003184 assert(I.getOperand(1)->getType() == Type::UByteTy);
3185 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003186 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003187
3188 // shl X, 0 == X and shr X, 0 == X
3189 // shl 0, X == 0 and shr 0, X == 0
3190 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003191 Op0 == Constant::getNullValue(Op0->getType()))
3192 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003193
Chris Lattner81a7a232004-10-16 18:11:37 +00003194 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3195 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003196 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003197 else // undef << X -> 0 AND undef >>u X -> 0
3198 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3199 }
3200 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003201 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003202 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3203 else
3204 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3205 }
3206
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003207 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3208 if (!isLeftShift)
3209 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3210 if (CSI->isAllOnesValue())
3211 return ReplaceInstUsesWith(I, CSI);
3212
Chris Lattner183b3362004-04-09 19:05:30 +00003213 // Try to fold constant and into select arguments.
3214 if (isa<Constant>(Op0))
3215 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003216 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003217 return R;
3218
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003219 // See if we can turn a signed shr into an unsigned shr.
3220 if (!isLeftShift && I.getType()->isSigned()) {
3221 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3222 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3223 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3224 I.getName()), I);
3225 return new CastInst(V, I.getType());
3226 }
3227 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003228
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003229 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003230 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3231 // of a signed value.
3232 //
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003233 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003234 if (CUI->getValue() >= TypeBits) {
3235 if (!Op0->getType()->isSigned() || isLeftShift)
3236 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3237 else {
3238 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3239 return &I;
3240 }
3241 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003242
Chris Lattnerede3fe02003-08-13 04:18:28 +00003243 // ((X*C1) << C2) == (X * (C1 << C2))
3244 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3245 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3246 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003247 return BinaryOperator::createMul(BO->getOperand(0),
3248 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanb1c93172005-04-21 23:48:37 +00003249
Chris Lattner183b3362004-04-09 19:05:30 +00003250 // Try to fold constant and into select arguments.
3251 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003252 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003253 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003254 if (isa<PHINode>(Op0))
3255 if (Instruction *NV = FoldOpIntoPhi(I))
3256 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003257
Chris Lattner86102b82005-01-01 16:22:27 +00003258 if (Op0->hasOneUse()) {
3259 // If this is a SHL of a sign-extending cast, see if we can turn the input
3260 // into a zero extending cast (a simple strength reduction).
3261 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3262 const Type *SrcTy = CI->getOperand(0)->getType();
3263 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003264 SrcTy->getPrimitiveSizeInBits() <
3265 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00003266 // We can change it to a zero extension if we are shifting out all of
3267 // the sign extended bits. To check this, form a mask of all of the
3268 // sign extend bits, then shift them left and see if we have anything
3269 // left.
3270 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3271 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3272 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3273 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3274 // If the shift is nuking all of the sign bits, change this to a
3275 // zero extension cast. To do this, cast the cast input to
3276 // unsigned, then to the requested size.
3277 Value *CastOp = CI->getOperand(0);
3278 Instruction *NC =
3279 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3280 CI->getName()+".uns");
3281 NC = InsertNewInstBefore(NC, I);
3282 // Finally, insert a replacement for CI.
3283 NC = new CastInst(NC, CI->getType(), CI->getName());
3284 CI->setName("");
3285 NC = InsertNewInstBefore(NC, I);
3286 WorkList.push_back(CI); // Delete CI later.
3287 I.setOperand(0, NC);
3288 return &I; // The SHL operand was modified.
3289 }
3290 }
3291 }
3292
3293 // If the operand is an bitwise operator with a constant RHS, and the
3294 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003295 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3296 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3297 bool isValid = true; // Valid only for And, Or, Xor
3298 bool highBitSet = false; // Transform if high bit of constant set?
3299
3300 switch (Op0BO->getOpcode()) {
3301 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003302 case Instruction::Add:
3303 isValid = isLeftShift;
3304 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003305 case Instruction::Or:
3306 case Instruction::Xor:
3307 highBitSet = false;
3308 break;
3309 case Instruction::And:
3310 highBitSet = true;
3311 break;
3312 }
3313
3314 // If this is a signed shift right, and the high bit is modified
3315 // by the logical operation, do not perform the transformation.
3316 // The highBitSet boolean indicates the value of the high bit of
3317 // the constant which would cause it to be modified for this
3318 // operation.
3319 //
3320 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3321 uint64_t Val = Op0C->getRawValue();
3322 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3323 }
3324
3325 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003326 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003327
3328 Instruction *NewShift =
3329 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3330 Op0BO->getName());
3331 Op0BO->setName("");
3332 InsertNewInstBefore(NewShift, I);
3333
3334 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3335 NewRHS);
3336 }
3337 }
Chris Lattner86102b82005-01-01 16:22:27 +00003338 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003339
Chris Lattner3204d4e2003-07-24 17:52:58 +00003340 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003341 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003342 if (ConstantUInt *ShiftAmt1C =
3343 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003344 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3345 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003346
Chris Lattner3204d4e2003-07-24 17:52:58 +00003347 // Check for (A << c1) << c2 and (A >> c1) >> c2
3348 if (I.getOpcode() == Op0SI->getOpcode()) {
3349 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003350 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3351 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003352 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3353 ConstantUInt::get(Type::UByteTy, Amt));
3354 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003355
Chris Lattnerab780df2003-07-24 18:38:56 +00003356 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3357 // signed types, we can only support the (A >> c1) << c2 configuration,
3358 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003359 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003360 // Calculate bitmask for what gets shifted off the edge...
3361 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003362 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003363 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003364 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003365 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003366
Chris Lattner3204d4e2003-07-24 17:52:58 +00003367 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003368 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3369 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003370 InsertNewInstBefore(Mask, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003371
Chris Lattner3204d4e2003-07-24 17:52:58 +00003372 // Figure out what flavor of shift we should use...
3373 if (ShiftAmt1 == ShiftAmt2)
3374 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3375 else if (ShiftAmt1 < ShiftAmt2) {
3376 return new ShiftInst(I.getOpcode(), Mask,
3377 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3378 } else {
3379 return new ShiftInst(Op0SI->getOpcode(), Mask,
3380 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3381 }
3382 }
3383 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003384 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003385
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003386 return 0;
3387}
3388
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003389enum CastType {
3390 Noop = 0,
3391 Truncate = 1,
3392 Signext = 2,
3393 Zeroext = 3
3394};
3395
3396/// getCastType - In the future, we will split the cast instruction into these
3397/// various types. Until then, we have to do the analysis here.
3398static CastType getCastType(const Type *Src, const Type *Dest) {
3399 assert(Src->isIntegral() && Dest->isIntegral() &&
3400 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003401 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3402 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003403
3404 if (SrcSize == DestSize) return Noop;
3405 if (SrcSize > DestSize) return Truncate;
3406 if (Src->isSigned()) return Signext;
3407 return Zeroext;
3408}
3409
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003410
Chris Lattner48a44f72002-05-02 17:06:02 +00003411// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3412// instruction.
3413//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003414static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003415 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003416
Chris Lattner650b6da2002-08-02 20:00:25 +00003417 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003418 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003419 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003420 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003421 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003422
Chris Lattner4fbad962004-07-21 04:27:24 +00003423 // If we are casting between pointer and integer types, treat pointers as
3424 // integers of the appropriate size for the code below.
3425 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3426 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3427 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003428
Chris Lattner48a44f72002-05-02 17:06:02 +00003429 // Allow free casting and conversion of sizes as long as the sign doesn't
3430 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003431 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003432 CastType FirstCast = getCastType(SrcTy, MidTy);
3433 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003434
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003435 // Capture the effect of these two casts. If the result is a legal cast,
3436 // the CastType is stored here, otherwise a special code is used.
3437 static const unsigned CastResult[] = {
3438 // First cast is noop
3439 0, 1, 2, 3,
3440 // First cast is a truncate
3441 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3442 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003443 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003444 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003445 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003446 };
3447
3448 unsigned Result = CastResult[FirstCast*4+SecondCast];
3449 switch (Result) {
3450 default: assert(0 && "Illegal table value!");
3451 case 0:
3452 case 1:
3453 case 2:
3454 case 3:
3455 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3456 // truncates, we could eliminate more casts.
3457 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3458 case 4:
3459 return false; // Not possible to eliminate this here.
3460 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003461 // Sign or zero extend followed by truncate is always ok if the result
3462 // is a truncate or noop.
3463 CastType ResultCast = getCastType(SrcTy, DstTy);
3464 if (ResultCast == Noop || ResultCast == Truncate)
3465 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003466 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003467 // result will match the sign/zeroextendness of the result.
3468 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003469 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003470 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003471 return false;
3472}
3473
Chris Lattner11ffd592004-07-20 05:21:00 +00003474static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003475 if (V->getType() == Ty || isa<Constant>(V)) return false;
3476 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003477 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3478 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003479 return false;
3480 return true;
3481}
3482
3483/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3484/// InsertBefore instruction. This is specialized a bit to avoid inserting
3485/// casts that are known to not do anything...
3486///
3487Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3488 Instruction *InsertBefore) {
3489 if (V->getType() == DestTy) return V;
3490 if (Constant *C = dyn_cast<Constant>(V))
3491 return ConstantExpr::getCast(C, DestTy);
3492
3493 CastInst *CI = new CastInst(V, DestTy, V->getName());
3494 InsertNewInstBefore(CI, *InsertBefore);
3495 return CI;
3496}
Chris Lattner48a44f72002-05-02 17:06:02 +00003497
3498// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003499//
Chris Lattner113f4f42002-06-25 16:13:24 +00003500Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003501 Value *Src = CI.getOperand(0);
3502
Chris Lattner48a44f72002-05-02 17:06:02 +00003503 // If the user is casting a value to the same type, eliminate this cast
3504 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003505 if (CI.getType() == Src->getType())
3506 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003507
Chris Lattner81a7a232004-10-16 18:11:37 +00003508 if (isa<UndefValue>(Src)) // cast undef -> undef
3509 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3510
Chris Lattner48a44f72002-05-02 17:06:02 +00003511 // If casting the result of another cast instruction, try to eliminate this
3512 // one!
3513 //
Chris Lattner86102b82005-01-01 16:22:27 +00003514 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3515 Value *A = CSrc->getOperand(0);
3516 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3517 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003518 // This instruction now refers directly to the cast's src operand. This
3519 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003520 CI.setOperand(0, CSrc->getOperand(0));
3521 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003522 }
3523
Chris Lattner650b6da2002-08-02 20:00:25 +00003524 // If this is an A->B->A cast, and we are dealing with integral types, try
3525 // to convert this into a logical 'and' instruction.
3526 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003527 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003528 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003529 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003530 CSrc->getType()->getPrimitiveSizeInBits() <
3531 CI.getType()->getPrimitiveSizeInBits()&&
3532 A->getType()->getPrimitiveSizeInBits() ==
3533 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003534 assert(CSrc->getType() != Type::ULongTy &&
3535 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00003536 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00003537 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3538 AndValue);
3539 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3540 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3541 if (And->getType() != CI.getType()) {
3542 And->setName(CSrc->getName()+".mask");
3543 InsertNewInstBefore(And, CI);
3544 And = new CastInst(And, CI.getType());
3545 }
3546 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003547 }
3548 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003549
Chris Lattner03841652004-05-25 04:29:21 +00003550 // If this is a cast to bool, turn it into the appropriate setne instruction.
3551 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003552 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003553 Constant::getNullValue(CI.getOperand(0)->getType()));
3554
Chris Lattnerd0d51602003-06-21 23:12:02 +00003555 // If casting the result of a getelementptr instruction with no offset, turn
3556 // this into a cast of the original pointer!
3557 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003558 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003559 bool AllZeroOperands = true;
3560 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3561 if (!isa<Constant>(GEP->getOperand(i)) ||
3562 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3563 AllZeroOperands = false;
3564 break;
3565 }
3566 if (AllZeroOperands) {
3567 CI.setOperand(0, GEP->getOperand(0));
3568 return &CI;
3569 }
3570 }
3571
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003572 // If we are casting a malloc or alloca to a pointer to a type of the same
3573 // size, rewrite the allocation instruction to allocate the "right" type.
3574 //
3575 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003576 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003577 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3578 // Get the type really allocated and the type casted to...
3579 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003580 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003581 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003582 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3583 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003584
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003585 // If the allocation is for an even multiple of the cast type size
3586 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003587 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003588 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003589 std::string Name = AI->getName(); AI->setName("");
3590 AllocationInst *New;
3591 if (isa<MallocInst>(AI))
3592 New = new MallocInst(CastElTy, Amt, Name);
3593 else
3594 New = new AllocaInst(CastElTy, Amt, Name);
3595 InsertNewInstBefore(New, *AI);
3596 return ReplaceInstUsesWith(CI, New);
3597 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003598 }
3599 }
3600
Chris Lattner86102b82005-01-01 16:22:27 +00003601 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3602 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3603 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003604 if (isa<PHINode>(Src))
3605 if (Instruction *NV = FoldOpIntoPhi(CI))
3606 return NV;
3607
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003608 // If the source value is an instruction with only this use, we can attempt to
3609 // propagate the cast into the instruction. Also, only handle integral types
3610 // for now.
3611 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003612 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003613 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3614 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003615 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
3616 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003617
3618 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3619 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3620
3621 switch (SrcI->getOpcode()) {
3622 case Instruction::Add:
3623 case Instruction::Mul:
3624 case Instruction::And:
3625 case Instruction::Or:
3626 case Instruction::Xor:
3627 // If we are discarding information, or just changing the sign, rewrite.
3628 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3629 // Don't insert two casts if they cannot be eliminated. We allow two
3630 // casts to be inserted if the sizes are the same. This could only be
3631 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003632 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3633 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003634 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3635 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3636 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3637 ->getOpcode(), Op0c, Op1c);
3638 }
3639 }
Chris Lattner72086162005-05-06 02:07:39 +00003640
3641 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
3642 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
3643 Op1 == ConstantBool::True &&
3644 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
3645 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
3646 return BinaryOperator::createXor(New,
3647 ConstantInt::get(CI.getType(), 1));
3648 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003649 break;
3650 case Instruction::Shl:
3651 // Allow changing the sign of the source operand. Do not allow changing
3652 // the size of the shift, UNLESS the shift amount is a constant. We
3653 // mush not change variable sized shifts to a smaller size, because it
3654 // is undefined to shift more bits out than exist in the value.
3655 if (DestBitSize == SrcBitSize ||
3656 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3657 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3658 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3659 }
3660 break;
Chris Lattner87380412005-05-06 04:18:52 +00003661 case Instruction::Shr:
3662 // If this is a signed shr, and if all bits shifted in are about to be
3663 // truncated off, turn it into an unsigned shr to allow greater
3664 // simplifications.
3665 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
3666 isa<ConstantInt>(Op1)) {
3667 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
3668 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
3669 // Convert to unsigned.
3670 Value *N1 = InsertOperandCastBefore(Op0,
3671 Op0->getType()->getUnsignedVersion(), &CI);
3672 // Insert the new shift, which is now unsigned.
3673 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
3674 Op1, Src->getName()), CI);
3675 return new CastInst(N1, CI.getType());
3676 }
3677 }
3678 break;
3679
Chris Lattner809dfac2005-05-04 19:10:26 +00003680 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00003681 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00003682 if (Op1C->getRawValue() == 0) {
3683 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003684 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00003685 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00003686 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00003687 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3688 if (CI.getType() == Op0->getType())
3689 return ReplaceInstUsesWith(CI, Op0);
3690 else
3691 return new CastInst(Op0, CI.getType());
3692 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00003693
3694 // If the input is an and with a single bit, shift then simplify.
3695 ConstantInt *AndRHS;
3696 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
3697 if (AndRHS->getRawValue() &&
3698 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00003699 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00003700 // Perform an unsigned shr by shiftamt. Convert input to
3701 // unsigned if it is signed.
3702 Value *In = Op0;
3703 if (In->getType()->isSigned())
3704 In = InsertNewInstBefore(new CastInst(In,
3705 In->getType()->getUnsignedVersion(), In->getName()),CI);
3706 // Insert the shift to put the result in the low bit.
3707 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
3708 ConstantInt::get(Type::UByteTy, ShiftAmt),
3709 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00003710 if (CI.getType() == In->getType())
3711 return ReplaceInstUsesWith(CI, In);
3712 else
3713 return new CastInst(In, CI.getType());
3714 }
3715 }
3716 }
3717 break;
3718 case Instruction::SetEQ:
3719 // We if we are just checking for a seteq of a single bit and casting it
3720 // to an integer. If so, shift the bit to the appropriate place then
3721 // cast to integer to avoid the comparison.
3722 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
3723 // Is Op1C a power of two or zero?
3724 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
3725 // cast (X == 1) to int -> X iff X has only the low bit set.
3726 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003727 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00003728 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
3729 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3730 if (CI.getType() == Op0->getType())
3731 return ReplaceInstUsesWith(CI, Op0);
3732 else
3733 return new CastInst(Op0, CI.getType());
3734 }
3735 }
Chris Lattner809dfac2005-05-04 19:10:26 +00003736 }
3737 }
3738 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003739 }
3740 }
Chris Lattner260ab202002-04-18 17:39:14 +00003741 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003742}
3743
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003744/// GetSelectFoldableOperands - We want to turn code that looks like this:
3745/// %C = or %A, %B
3746/// %D = select %cond, %C, %A
3747/// into:
3748/// %C = select %cond, %B, 0
3749/// %D = or %A, %C
3750///
3751/// Assuming that the specified instruction is an operand to the select, return
3752/// a bitmask indicating which operands of this instruction are foldable if they
3753/// equal the other incoming value of the select.
3754///
3755static unsigned GetSelectFoldableOperands(Instruction *I) {
3756 switch (I->getOpcode()) {
3757 case Instruction::Add:
3758 case Instruction::Mul:
3759 case Instruction::And:
3760 case Instruction::Or:
3761 case Instruction::Xor:
3762 return 3; // Can fold through either operand.
3763 case Instruction::Sub: // Can only fold on the amount subtracted.
3764 case Instruction::Shl: // Can only fold on the shift amount.
3765 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00003766 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003767 default:
3768 return 0; // Cannot fold
3769 }
3770}
3771
3772/// GetSelectFoldableConstant - For the same transformation as the previous
3773/// function, return the identity constant that goes into the select.
3774static Constant *GetSelectFoldableConstant(Instruction *I) {
3775 switch (I->getOpcode()) {
3776 default: assert(0 && "This cannot happen!"); abort();
3777 case Instruction::Add:
3778 case Instruction::Sub:
3779 case Instruction::Or:
3780 case Instruction::Xor:
3781 return Constant::getNullValue(I->getType());
3782 case Instruction::Shl:
3783 case Instruction::Shr:
3784 return Constant::getNullValue(Type::UByteTy);
3785 case Instruction::And:
3786 return ConstantInt::getAllOnesValue(I->getType());
3787 case Instruction::Mul:
3788 return ConstantInt::get(I->getType(), 1);
3789 }
3790}
3791
Chris Lattner411336f2005-01-19 21:50:18 +00003792/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3793/// have the same opcode and only one use each. Try to simplify this.
3794Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3795 Instruction *FI) {
3796 if (TI->getNumOperands() == 1) {
3797 // If this is a non-volatile load or a cast from the same type,
3798 // merge.
3799 if (TI->getOpcode() == Instruction::Cast) {
3800 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3801 return 0;
3802 } else {
3803 return 0; // unknown unary op.
3804 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003805
Chris Lattner411336f2005-01-19 21:50:18 +00003806 // Fold this by inserting a select from the input values.
3807 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3808 FI->getOperand(0), SI.getName()+".v");
3809 InsertNewInstBefore(NewSI, SI);
3810 return new CastInst(NewSI, TI->getType());
3811 }
3812
3813 // Only handle binary operators here.
3814 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3815 return 0;
3816
3817 // Figure out if the operations have any operands in common.
3818 Value *MatchOp, *OtherOpT, *OtherOpF;
3819 bool MatchIsOpZero;
3820 if (TI->getOperand(0) == FI->getOperand(0)) {
3821 MatchOp = TI->getOperand(0);
3822 OtherOpT = TI->getOperand(1);
3823 OtherOpF = FI->getOperand(1);
3824 MatchIsOpZero = true;
3825 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3826 MatchOp = TI->getOperand(1);
3827 OtherOpT = TI->getOperand(0);
3828 OtherOpF = FI->getOperand(0);
3829 MatchIsOpZero = false;
3830 } else if (!TI->isCommutative()) {
3831 return 0;
3832 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3833 MatchOp = TI->getOperand(0);
3834 OtherOpT = TI->getOperand(1);
3835 OtherOpF = FI->getOperand(0);
3836 MatchIsOpZero = true;
3837 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3838 MatchOp = TI->getOperand(1);
3839 OtherOpT = TI->getOperand(0);
3840 OtherOpF = FI->getOperand(1);
3841 MatchIsOpZero = true;
3842 } else {
3843 return 0;
3844 }
3845
3846 // If we reach here, they do have operations in common.
3847 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3848 OtherOpF, SI.getName()+".v");
3849 InsertNewInstBefore(NewSI, SI);
3850
3851 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3852 if (MatchIsOpZero)
3853 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3854 else
3855 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3856 } else {
3857 if (MatchIsOpZero)
3858 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3859 else
3860 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3861 }
3862}
3863
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003864Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003865 Value *CondVal = SI.getCondition();
3866 Value *TrueVal = SI.getTrueValue();
3867 Value *FalseVal = SI.getFalseValue();
3868
3869 // select true, X, Y -> X
3870 // select false, X, Y -> Y
3871 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003872 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003873 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003874 else {
3875 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003876 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003877 }
Chris Lattner533bc492004-03-30 19:37:13 +00003878
3879 // select C, X, X -> X
3880 if (TrueVal == FalseVal)
3881 return ReplaceInstUsesWith(SI, TrueVal);
3882
Chris Lattner81a7a232004-10-16 18:11:37 +00003883 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3884 return ReplaceInstUsesWith(SI, FalseVal);
3885 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3886 return ReplaceInstUsesWith(SI, TrueVal);
3887 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3888 if (isa<Constant>(TrueVal))
3889 return ReplaceInstUsesWith(SI, TrueVal);
3890 else
3891 return ReplaceInstUsesWith(SI, FalseVal);
3892 }
3893
Chris Lattner1c631e82004-04-08 04:43:23 +00003894 if (SI.getType() == Type::BoolTy)
3895 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3896 if (C == ConstantBool::True) {
3897 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003898 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003899 } else {
3900 // Change: A = select B, false, C --> A = and !B, C
3901 Value *NotCond =
3902 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3903 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003904 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003905 }
3906 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3907 if (C == ConstantBool::False) {
3908 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003909 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003910 } else {
3911 // Change: A = select B, C, true --> A = or !B, C
3912 Value *NotCond =
3913 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3914 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003915 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003916 }
3917 }
3918
Chris Lattner183b3362004-04-09 19:05:30 +00003919 // Selecting between two integer constants?
3920 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3921 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3922 // select C, 1, 0 -> cast C to int
3923 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3924 return new CastInst(CondVal, SI.getType());
3925 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3926 // select C, 0, 1 -> cast !C to int
3927 Value *NotCond =
3928 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003929 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003930 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003931 }
Chris Lattner35167c32004-06-09 07:59:58 +00003932
3933 // If one of the constants is zero (we know they can't both be) and we
3934 // have a setcc instruction with zero, and we have an 'and' with the
3935 // non-constant value, eliminate this whole mess. This corresponds to
3936 // cases like this: ((X & 27) ? 27 : 0)
3937 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3938 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3939 if ((IC->getOpcode() == Instruction::SetEQ ||
3940 IC->getOpcode() == Instruction::SetNE) &&
3941 isa<ConstantInt>(IC->getOperand(1)) &&
3942 cast<Constant>(IC->getOperand(1))->isNullValue())
3943 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3944 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00003945 isa<ConstantInt>(ICA->getOperand(1)) &&
3946 (ICA->getOperand(1) == TrueValC ||
3947 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00003948 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3949 // Okay, now we know that everything is set up, we just don't
3950 // know whether we have a setne or seteq and whether the true or
3951 // false val is the zero.
3952 bool ShouldNotVal = !TrueValC->isNullValue();
3953 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3954 Value *V = ICA;
3955 if (ShouldNotVal)
3956 V = InsertNewInstBefore(BinaryOperator::create(
3957 Instruction::Xor, V, ICA->getOperand(1)), SI);
3958 return ReplaceInstUsesWith(SI, V);
3959 }
Chris Lattner533bc492004-03-30 19:37:13 +00003960 }
Chris Lattner623fba12004-04-10 22:21:27 +00003961
3962 // See if we are selecting two values based on a comparison of the two values.
3963 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3964 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3965 // Transform (X == Y) ? X : Y -> Y
3966 if (SCI->getOpcode() == Instruction::SetEQ)
3967 return ReplaceInstUsesWith(SI, FalseVal);
3968 // Transform (X != Y) ? X : Y -> X
3969 if (SCI->getOpcode() == Instruction::SetNE)
3970 return ReplaceInstUsesWith(SI, TrueVal);
3971 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3972
3973 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3974 // Transform (X == Y) ? Y : X -> X
3975 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003976 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003977 // Transform (X != Y) ? Y : X -> Y
3978 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003979 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003980 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3981 }
3982 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003983
Chris Lattnera04c9042005-01-13 22:52:24 +00003984 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3985 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3986 if (TI->hasOneUse() && FI->hasOneUse()) {
3987 bool isInverse = false;
3988 Instruction *AddOp = 0, *SubOp = 0;
3989
Chris Lattner411336f2005-01-19 21:50:18 +00003990 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3991 if (TI->getOpcode() == FI->getOpcode())
3992 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3993 return IV;
3994
3995 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3996 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00003997 if (TI->getOpcode() == Instruction::Sub &&
3998 FI->getOpcode() == Instruction::Add) {
3999 AddOp = FI; SubOp = TI;
4000 } else if (FI->getOpcode() == Instruction::Sub &&
4001 TI->getOpcode() == Instruction::Add) {
4002 AddOp = TI; SubOp = FI;
4003 }
4004
4005 if (AddOp) {
4006 Value *OtherAddOp = 0;
4007 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4008 OtherAddOp = AddOp->getOperand(1);
4009 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4010 OtherAddOp = AddOp->getOperand(0);
4011 }
4012
4013 if (OtherAddOp) {
4014 // So at this point we know we have:
4015 // select C, (add X, Y), (sub X, ?)
4016 // We can do the transform profitably if either 'Y' = '?' or '?' is
4017 // a constant.
4018 if (SubOp->getOperand(1) == AddOp ||
4019 isa<Constant>(SubOp->getOperand(1))) {
4020 Value *NegVal;
4021 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4022 NegVal = ConstantExpr::getNeg(C);
4023 } else {
4024 NegVal = InsertNewInstBefore(
4025 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4026 }
4027
Chris Lattner51726c42005-01-14 17:35:12 +00004028 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004029 Value *NewFalseOp = NegVal;
4030 if (AddOp != TI)
4031 std::swap(NewTrueOp, NewFalseOp);
4032 Instruction *NewSel =
4033 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004034
Chris Lattnera04c9042005-01-13 22:52:24 +00004035 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004036 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004037 }
4038 }
4039 }
4040 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004041
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004042 // See if we can fold the select into one of our operands.
4043 if (SI.getType()->isInteger()) {
4044 // See the comment above GetSelectFoldableOperands for a description of the
4045 // transformation we are doing here.
4046 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4047 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4048 !isa<Constant>(FalseVal))
4049 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4050 unsigned OpToFold = 0;
4051 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4052 OpToFold = 1;
4053 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4054 OpToFold = 2;
4055 }
4056
4057 if (OpToFold) {
4058 Constant *C = GetSelectFoldableConstant(TVI);
4059 std::string Name = TVI->getName(); TVI->setName("");
4060 Instruction *NewSel =
4061 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4062 Name);
4063 InsertNewInstBefore(NewSel, SI);
4064 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4065 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4066 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4067 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4068 else {
4069 assert(0 && "Unknown instruction!!");
4070 }
4071 }
4072 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004073
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004074 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4075 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4076 !isa<Constant>(TrueVal))
4077 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4078 unsigned OpToFold = 0;
4079 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4080 OpToFold = 1;
4081 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4082 OpToFold = 2;
4083 }
4084
4085 if (OpToFold) {
4086 Constant *C = GetSelectFoldableConstant(FVI);
4087 std::string Name = FVI->getName(); FVI->setName("");
4088 Instruction *NewSel =
4089 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4090 Name);
4091 InsertNewInstBefore(NewSel, SI);
4092 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4093 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4094 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4095 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4096 else {
4097 assert(0 && "Unknown instruction!!");
4098 }
4099 }
4100 }
4101 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004102
4103 if (BinaryOperator::isNot(CondVal)) {
4104 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4105 SI.setOperand(1, FalseVal);
4106 SI.setOperand(2, TrueVal);
4107 return &SI;
4108 }
4109
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004110 return 0;
4111}
4112
4113
Chris Lattner970c33a2003-06-19 17:00:31 +00004114// CallInst simplification
4115//
4116Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00004117 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4118 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00004119 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4120 bool Changed = false;
4121
4122 // memmove/cpy/set of zero bytes is a noop.
4123 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4124 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4125
4126 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004127
Chris Lattner00648e12004-10-12 04:52:52 +00004128 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4129 if (CI->getRawValue() == 1) {
4130 // Replace the instruction with just byte operations. We would
4131 // transform other cases to loads/stores, but we don't know if
4132 // alignment is sufficient.
4133 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004134 }
4135
Chris Lattner00648e12004-10-12 04:52:52 +00004136 // If we have a memmove and the source operation is a constant global,
4137 // then the source and dest pointers can't alias, so we can change this
4138 // into a call to memcpy.
4139 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4140 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4141 if (GVSrc->isConstant()) {
4142 Module *M = CI.getParent()->getParent()->getParent();
4143 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4144 CI.getCalledFunction()->getFunctionType());
4145 CI.setOperand(0, MemCpy);
4146 Changed = true;
4147 }
4148
4149 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00004150 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4151 // If this stoppoint is at the same source location as the previous
4152 // stoppoint in the chain, it is not needed.
4153 if (DbgStopPointInst *PrevSPI =
4154 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4155 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4156 SPI->getColNo() == PrevSPI->getColNo()) {
4157 SPI->replaceAllUsesWith(PrevSPI);
4158 return EraseInstFromFunction(CI);
4159 }
Chris Lattner00648e12004-10-12 04:52:52 +00004160 }
4161
Chris Lattneraec3d942003-10-07 22:32:43 +00004162 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00004163}
4164
4165// InvokeInst simplification
4166//
4167Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004168 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004169}
4170
Chris Lattneraec3d942003-10-07 22:32:43 +00004171// visitCallSite - Improvements for call and invoke instructions.
4172//
4173Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004174 bool Changed = false;
4175
4176 // If the callee is a constexpr cast of a function, attempt to move the cast
4177 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004178 if (transformConstExprCastCall(CS)) return 0;
4179
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004180 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004181
Chris Lattner61d9d812005-05-13 07:09:09 +00004182 if (Function *CalleeF = dyn_cast<Function>(Callee))
4183 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4184 Instruction *OldCall = CS.getInstruction();
4185 // If the call and callee calling conventions don't match, this call must
4186 // be unreachable, as the call is undefined.
4187 new StoreInst(ConstantBool::True,
4188 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4189 if (!OldCall->use_empty())
4190 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4191 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4192 return EraseInstFromFunction(*OldCall);
4193 return 0;
4194 }
4195
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004196 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4197 // This instruction is not reachable, just remove it. We insert a store to
4198 // undef so that we know that this code is not reachable, despite the fact
4199 // that we can't modify the CFG here.
4200 new StoreInst(ConstantBool::True,
4201 UndefValue::get(PointerType::get(Type::BoolTy)),
4202 CS.getInstruction());
4203
4204 if (!CS.getInstruction()->use_empty())
4205 CS.getInstruction()->
4206 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4207
4208 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4209 // Don't break the CFG, insert a dummy cond branch.
4210 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4211 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004212 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004213 return EraseInstFromFunction(*CS.getInstruction());
4214 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004215
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004216 const PointerType *PTy = cast<PointerType>(Callee->getType());
4217 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4218 if (FTy->isVarArg()) {
4219 // See if we can optimize any arguments passed through the varargs area of
4220 // the call.
4221 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4222 E = CS.arg_end(); I != E; ++I)
4223 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4224 // If this cast does not effect the value passed through the varargs
4225 // area, we can eliminate the use of the cast.
4226 Value *Op = CI->getOperand(0);
4227 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4228 *I = Op;
4229 Changed = true;
4230 }
4231 }
4232 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004233
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004234 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004235}
4236
Chris Lattner970c33a2003-06-19 17:00:31 +00004237// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4238// attempt to move the cast to the arguments of the call/invoke.
4239//
4240bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4241 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4242 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004243 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004244 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004245 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004246 Instruction *Caller = CS.getInstruction();
4247
4248 // Okay, this is a cast from a function to a different type. Unless doing so
4249 // would cause a type conversion of one of our arguments, change this call to
4250 // be a direct call with arguments casted to the appropriate types.
4251 //
4252 const FunctionType *FT = Callee->getFunctionType();
4253 const Type *OldRetTy = Caller->getType();
4254
Chris Lattner1f7942f2004-01-14 06:06:08 +00004255 // Check to see if we are changing the return type...
4256 if (OldRetTy != FT->getReturnType()) {
4257 if (Callee->isExternal() &&
4258 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4259 !Caller->use_empty())
4260 return false; // Cannot transform this return value...
4261
4262 // If the callsite is an invoke instruction, and the return value is used by
4263 // a PHI node in a successor, we cannot change the return type of the call
4264 // because there is no place to put the cast instruction (without breaking
4265 // the critical edge). Bail out in this case.
4266 if (!Caller->use_empty())
4267 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4268 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4269 UI != E; ++UI)
4270 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4271 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004272 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004273 return false;
4274 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004275
4276 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4277 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004278
Chris Lattner970c33a2003-06-19 17:00:31 +00004279 CallSite::arg_iterator AI = CS.arg_begin();
4280 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4281 const Type *ParamTy = FT->getParamType(i);
4282 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004283 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004284 }
4285
4286 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4287 Callee->isExternal())
4288 return false; // Do not delete arguments unless we have a function body...
4289
4290 // Okay, we decided that this is a safe thing to do: go ahead and start
4291 // inserting cast instructions as necessary...
4292 std::vector<Value*> Args;
4293 Args.reserve(NumActualArgs);
4294
4295 AI = CS.arg_begin();
4296 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4297 const Type *ParamTy = FT->getParamType(i);
4298 if ((*AI)->getType() == ParamTy) {
4299 Args.push_back(*AI);
4300 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004301 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4302 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004303 }
4304 }
4305
4306 // If the function takes more arguments than the call was taking, add them
4307 // now...
4308 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4309 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4310
4311 // If we are removing arguments to the function, emit an obnoxious warning...
4312 if (FT->getNumParams() < NumActualArgs)
4313 if (!FT->isVarArg()) {
4314 std::cerr << "WARNING: While resolving call to function '"
4315 << Callee->getName() << "' arguments were dropped!\n";
4316 } else {
4317 // Add all of the arguments in their promoted form to the arg list...
4318 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4319 const Type *PTy = getPromotedType((*AI)->getType());
4320 if (PTy != (*AI)->getType()) {
4321 // Must promote to pass through va_arg area!
4322 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4323 InsertNewInstBefore(Cast, *Caller);
4324 Args.push_back(Cast);
4325 } else {
4326 Args.push_back(*AI);
4327 }
4328 }
4329 }
4330
4331 if (FT->getReturnType() == Type::VoidTy)
4332 Caller->setName(""); // Void type should not have a name...
4333
4334 Instruction *NC;
4335 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004336 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004337 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004338 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004339 } else {
4340 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004341 if (cast<CallInst>(Caller)->isTailCall())
4342 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004343 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004344 }
4345
4346 // Insert a cast of the return type as necessary...
4347 Value *NV = NC;
4348 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4349 if (NV->getType() != Type::VoidTy) {
4350 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004351
4352 // If this is an invoke instruction, we should insert it after the first
4353 // non-phi, instruction in the normal successor block.
4354 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4355 BasicBlock::iterator I = II->getNormalDest()->begin();
4356 while (isa<PHINode>(I)) ++I;
4357 InsertNewInstBefore(NC, *I);
4358 } else {
4359 // Otherwise, it's a call, just insert cast right after the call instr
4360 InsertNewInstBefore(NC, *Caller);
4361 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004362 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004363 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004364 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004365 }
4366 }
4367
4368 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4369 Caller->replaceAllUsesWith(NV);
4370 Caller->getParent()->getInstList().erase(Caller);
4371 removeFromWorkList(Caller);
4372 return true;
4373}
4374
4375
Chris Lattner7515cab2004-11-14 19:13:23 +00004376// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4377// operator and they all are only used by the PHI, PHI together their
4378// inputs, and do the operation once, to the result of the PHI.
4379Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4380 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4381
4382 // Scan the instruction, looking for input operations that can be folded away.
4383 // If all input operands to the phi are the same instruction (e.g. a cast from
4384 // the same type or "+42") we can pull the operation through the PHI, reducing
4385 // code size and simplifying code.
4386 Constant *ConstantOp = 0;
4387 const Type *CastSrcTy = 0;
4388 if (isa<CastInst>(FirstInst)) {
4389 CastSrcTy = FirstInst->getOperand(0)->getType();
4390 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4391 // Can fold binop or shift if the RHS is a constant.
4392 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4393 if (ConstantOp == 0) return 0;
4394 } else {
4395 return 0; // Cannot fold this operation.
4396 }
4397
4398 // Check to see if all arguments are the same operation.
4399 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4400 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4401 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4402 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4403 return 0;
4404 if (CastSrcTy) {
4405 if (I->getOperand(0)->getType() != CastSrcTy)
4406 return 0; // Cast operation must match.
4407 } else if (I->getOperand(1) != ConstantOp) {
4408 return 0;
4409 }
4410 }
4411
4412 // Okay, they are all the same operation. Create a new PHI node of the
4413 // correct type, and PHI together all of the LHS's of the instructions.
4414 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4415 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004416 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004417
4418 Value *InVal = FirstInst->getOperand(0);
4419 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004420
4421 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004422 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4423 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4424 if (NewInVal != InVal)
4425 InVal = 0;
4426 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4427 }
4428
4429 Value *PhiVal;
4430 if (InVal) {
4431 // The new PHI unions all of the same values together. This is really
4432 // common, so we handle it intelligently here for compile-time speed.
4433 PhiVal = InVal;
4434 delete NewPN;
4435 } else {
4436 InsertNewInstBefore(NewPN, PN);
4437 PhiVal = NewPN;
4438 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004439
Chris Lattner7515cab2004-11-14 19:13:23 +00004440 // Insert and return the new operation.
4441 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004442 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004443 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004444 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004445 else
4446 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004447 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004448}
Chris Lattner48a44f72002-05-02 17:06:02 +00004449
Chris Lattner71536432005-01-17 05:10:15 +00004450/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4451/// that is dead.
4452static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4453 if (PN->use_empty()) return true;
4454 if (!PN->hasOneUse()) return false;
4455
4456 // Remember this node, and if we find the cycle, return.
4457 if (!PotentiallyDeadPHIs.insert(PN).second)
4458 return true;
4459
4460 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4461 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004462
Chris Lattner71536432005-01-17 05:10:15 +00004463 return false;
4464}
4465
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004466// PHINode simplification
4467//
Chris Lattner113f4f42002-06-25 16:13:24 +00004468Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00004469 if (Value *V = PN.hasConstantValue())
4470 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00004471
4472 // If the only user of this instruction is a cast instruction, and all of the
4473 // incoming values are constants, change this PHI to merge together the casted
4474 // constants.
4475 if (PN.hasOneUse())
4476 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4477 if (CI->getType() != PN.getType()) { // noop casts will be folded
4478 bool AllConstant = true;
4479 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4480 if (!isa<Constant>(PN.getIncomingValue(i))) {
4481 AllConstant = false;
4482 break;
4483 }
4484 if (AllConstant) {
4485 // Make a new PHI with all casted values.
4486 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4487 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4488 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4489 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4490 PN.getIncomingBlock(i));
4491 }
4492
4493 // Update the cast instruction.
4494 CI->setOperand(0, New);
4495 WorkList.push_back(CI); // revisit the cast instruction to fold.
4496 WorkList.push_back(New); // Make sure to revisit the new Phi
4497 return &PN; // PN is now dead!
4498 }
4499 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004500
4501 // If all PHI operands are the same operation, pull them through the PHI,
4502 // reducing code size.
4503 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4504 PN.getIncomingValue(0)->hasOneUse())
4505 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4506 return Result;
4507
Chris Lattner71536432005-01-17 05:10:15 +00004508 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4509 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4510 // PHI)... break the cycle.
4511 if (PN.hasOneUse())
4512 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4513 std::set<PHINode*> PotentiallyDeadPHIs;
4514 PotentiallyDeadPHIs.insert(&PN);
4515 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4516 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4517 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004518
Chris Lattner91daeb52003-12-19 05:58:40 +00004519 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004520}
4521
Chris Lattner69193f92004-04-05 01:30:19 +00004522static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4523 Instruction *InsertPoint,
4524 InstCombiner *IC) {
4525 unsigned PS = IC->getTargetData().getPointerSize();
4526 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004527 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4528 // We must insert a cast to ensure we sign-extend.
4529 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4530 V->getName()), *InsertPoint);
4531 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4532 *InsertPoint);
4533}
4534
Chris Lattner48a44f72002-05-02 17:06:02 +00004535
Chris Lattner113f4f42002-06-25 16:13:24 +00004536Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004537 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004538 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004539 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004540 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004541 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004542
Chris Lattner81a7a232004-10-16 18:11:37 +00004543 if (isa<UndefValue>(GEP.getOperand(0)))
4544 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4545
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004546 bool HasZeroPointerIndex = false;
4547 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4548 HasZeroPointerIndex = C->isNullValue();
4549
4550 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004551 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004552
Chris Lattner69193f92004-04-05 01:30:19 +00004553 // Eliminate unneeded casts for indices.
4554 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004555 gep_type_iterator GTI = gep_type_begin(GEP);
4556 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4557 if (isa<SequentialType>(*GTI)) {
4558 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4559 Value *Src = CI->getOperand(0);
4560 const Type *SrcTy = Src->getType();
4561 const Type *DestTy = CI->getType();
4562 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004563 if (SrcTy->getPrimitiveSizeInBits() ==
4564 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004565 // We can always eliminate a cast from ulong or long to the other.
4566 // We can always eliminate a cast from uint to int or the other on
4567 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004568 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00004569 MadeChange = true;
4570 GEP.setOperand(i, Src);
4571 }
4572 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4573 SrcTy->getPrimitiveSize() == 4) {
4574 // We can always eliminate a cast from int to [u]long. We can
4575 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4576 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004577 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004578 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004579 MadeChange = true;
4580 GEP.setOperand(i, Src);
4581 }
Chris Lattner69193f92004-04-05 01:30:19 +00004582 }
4583 }
4584 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004585 // If we are using a wider index than needed for this platform, shrink it
4586 // to what we need. If the incoming value needs a cast instruction,
4587 // insert it. This explicit cast can make subsequent optimizations more
4588 // obvious.
4589 Value *Op = GEP.getOperand(i);
4590 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004591 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004592 GEP.setOperand(i, ConstantExpr::getCast(C,
4593 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004594 MadeChange = true;
4595 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004596 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4597 Op->getName()), GEP);
4598 GEP.setOperand(i, Op);
4599 MadeChange = true;
4600 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004601
4602 // If this is a constant idx, make sure to canonicalize it to be a signed
4603 // operand, otherwise CSE and other optimizations are pessimized.
4604 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4605 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4606 CUI->getType()->getSignedVersion()));
4607 MadeChange = true;
4608 }
Chris Lattner69193f92004-04-05 01:30:19 +00004609 }
4610 if (MadeChange) return &GEP;
4611
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004612 // Combine Indices - If the source pointer to this getelementptr instruction
4613 // is a getelementptr instruction, combine the indices of the two
4614 // getelementptr instructions into a single instruction.
4615 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004616 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004617 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004618 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004619
4620 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004621 // Note that if our source is a gep chain itself that we wait for that
4622 // chain to be resolved before we perform this transformation. This
4623 // avoids us creating a TON of code in some cases.
4624 //
4625 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4626 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4627 return 0; // Wait until our source is folded to completion.
4628
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004629 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004630
4631 // Find out whether the last index in the source GEP is a sequential idx.
4632 bool EndsWithSequential = false;
4633 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4634 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004635 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004636
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004637 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004638 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004639 // Replace: gep (gep %P, long B), long A, ...
4640 // With: T = long A+B; gep %P, T, ...
4641 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004642 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004643 if (SO1 == Constant::getNullValue(SO1->getType())) {
4644 Sum = GO1;
4645 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4646 Sum = SO1;
4647 } else {
4648 // If they aren't the same type, convert both to an integer of the
4649 // target's pointer size.
4650 if (SO1->getType() != GO1->getType()) {
4651 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4652 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4653 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4654 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4655 } else {
4656 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004657 if (SO1->getType()->getPrimitiveSize() == PS) {
4658 // Convert GO1 to SO1's type.
4659 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4660
4661 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4662 // Convert SO1 to GO1's type.
4663 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4664 } else {
4665 const Type *PT = TD->getIntPtrType();
4666 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4667 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4668 }
4669 }
4670 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004671 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4672 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4673 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004674 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4675 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004676 }
Chris Lattner69193f92004-04-05 01:30:19 +00004677 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004678
4679 // Recycle the GEP we already have if possible.
4680 if (SrcGEPOperands.size() == 2) {
4681 GEP.setOperand(0, SrcGEPOperands[0]);
4682 GEP.setOperand(1, Sum);
4683 return &GEP;
4684 } else {
4685 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4686 SrcGEPOperands.end()-1);
4687 Indices.push_back(Sum);
4688 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4689 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004690 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00004691 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004692 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004693 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004694 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4695 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004696 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4697 }
4698
4699 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004700 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004701
Chris Lattner5f667a62004-05-07 22:09:22 +00004702 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004703 // GEP of global variable. If all of the indices for this GEP are
4704 // constants, we can promote this to a constexpr instead of an instruction.
4705
4706 // Scan for nonconstants...
4707 std::vector<Constant*> Indices;
4708 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4709 for (; I != E && isa<Constant>(*I); ++I)
4710 Indices.push_back(cast<Constant>(*I));
4711
4712 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004713 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004714
4715 // Replace all uses of the GEP with the new constexpr...
4716 return ReplaceInstUsesWith(GEP, CE);
4717 }
Chris Lattner567b81f2005-09-13 00:40:14 +00004718 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
4719 if (!isa<PointerType>(X->getType())) {
4720 // Not interesting. Source pointer must be a cast from pointer.
4721 } else if (HasZeroPointerIndex) {
4722 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4723 // into : GEP [10 x ubyte]* X, long 0, ...
4724 //
4725 // This occurs when the program declares an array extern like "int X[];"
4726 //
4727 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4728 const PointerType *XTy = cast<PointerType>(X->getType());
4729 if (const ArrayType *XATy =
4730 dyn_cast<ArrayType>(XTy->getElementType()))
4731 if (const ArrayType *CATy =
4732 dyn_cast<ArrayType>(CPTy->getElementType()))
4733 if (CATy->getElementType() == XATy->getElementType()) {
4734 // At this point, we know that the cast source type is a pointer
4735 // to an array of the same type as the destination pointer
4736 // array. Because the array type is never stepped over (there
4737 // is a leading zero) we can fold the cast into this GEP.
4738 GEP.setOperand(0, X);
4739 return &GEP;
4740 }
4741 } else if (GEP.getNumOperands() == 2) {
4742 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00004743 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
4744 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00004745 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4746 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
4747 if (isa<ArrayType>(SrcElTy) &&
4748 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4749 TD->getTypeSize(ResElTy)) {
4750 Value *V = InsertNewInstBefore(
4751 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4752 GEP.getOperand(1), GEP.getName()), GEP);
4753 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004754 }
Chris Lattner2a893292005-09-13 18:36:04 +00004755
4756 // Transform things like:
4757 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
4758 // (where tmp = 8*tmp2) into:
4759 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
4760
4761 if (isa<ArrayType>(SrcElTy) &&
4762 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
4763 uint64_t ArrayEltSize =
4764 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
4765
4766 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
4767 // allow either a mul, shift, or constant here.
4768 Value *NewIdx = 0;
4769 ConstantInt *Scale = 0;
4770 if (ArrayEltSize == 1) {
4771 NewIdx = GEP.getOperand(1);
4772 Scale = ConstantInt::get(NewIdx->getType(), 1);
4773 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00004774 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00004775 Scale = CI;
4776 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
4777 if (Inst->getOpcode() == Instruction::Shl &&
4778 isa<ConstantInt>(Inst->getOperand(1))) {
4779 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
4780 if (Inst->getType()->isSigned())
4781 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
4782 else
4783 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
4784 NewIdx = Inst->getOperand(0);
4785 } else if (Inst->getOpcode() == Instruction::Mul &&
4786 isa<ConstantInt>(Inst->getOperand(1))) {
4787 Scale = cast<ConstantInt>(Inst->getOperand(1));
4788 NewIdx = Inst->getOperand(0);
4789 }
4790 }
4791
4792 // If the index will be to exactly the right offset with the scale taken
4793 // out, perform the transformation.
4794 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
4795 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
4796 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00004797 (int64_t)C->getRawValue() /
4798 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00004799 else
4800 Scale = ConstantUInt::get(Scale->getType(),
4801 Scale->getRawValue() / ArrayEltSize);
4802 if (Scale->getRawValue() != 1) {
4803 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
4804 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
4805 NewIdx = InsertNewInstBefore(Sc, GEP);
4806 }
4807
4808 // Insert the new GEP instruction.
4809 Instruction *Idx =
4810 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4811 NewIdx, GEP.getName());
4812 Idx = InsertNewInstBefore(Idx, GEP);
4813 return new CastInst(Idx, GEP.getType());
4814 }
4815 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004816 }
Chris Lattnerca081252001-12-14 16:52:21 +00004817 }
4818
Chris Lattnerca081252001-12-14 16:52:21 +00004819 return 0;
4820}
4821
Chris Lattner1085bdf2002-11-04 16:18:53 +00004822Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4823 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4824 if (AI.isArrayAllocation()) // Check C != 1
4825 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4826 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004827 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004828
4829 // Create and insert the replacement instruction...
4830 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004831 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004832 else {
4833 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004834 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004835 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004836
4837 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004838
Chris Lattner1085bdf2002-11-04 16:18:53 +00004839 // Scan to the end of the allocation instructions, to skip over a block of
4840 // allocas if possible...
4841 //
4842 BasicBlock::iterator It = New;
4843 while (isa<AllocationInst>(*It)) ++It;
4844
4845 // Now that I is pointing to the first non-allocation-inst in the block,
4846 // insert our getelementptr instruction...
4847 //
Chris Lattner809dfac2005-05-04 19:10:26 +00004848 Value *NullIdx = Constant::getNullValue(Type::IntTy);
4849 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
4850 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00004851
4852 // Now make everything use the getelementptr instead of the original
4853 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004854 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004855 } else if (isa<UndefValue>(AI.getArraySize())) {
4856 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004857 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004858
4859 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4860 // Note that we only do this for alloca's, because malloc should allocate and
4861 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004862 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00004863 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004864 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4865
Chris Lattner1085bdf2002-11-04 16:18:53 +00004866 return 0;
4867}
4868
Chris Lattner8427bff2003-12-07 01:24:23 +00004869Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4870 Value *Op = FI.getOperand(0);
4871
4872 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4873 if (CastInst *CI = dyn_cast<CastInst>(Op))
4874 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4875 FI.setOperand(0, CI->getOperand(0));
4876 return &FI;
4877 }
4878
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004879 // free undef -> unreachable.
4880 if (isa<UndefValue>(Op)) {
4881 // Insert a new store to null because we cannot modify the CFG here.
4882 new StoreInst(ConstantBool::True,
4883 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4884 return EraseInstFromFunction(FI);
4885 }
4886
Chris Lattnerf3a36602004-02-28 04:57:37 +00004887 // If we have 'free null' delete the instruction. This can happen in stl code
4888 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004889 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004890 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004891
Chris Lattner8427bff2003-12-07 01:24:23 +00004892 return 0;
4893}
4894
4895
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004896/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4897/// constantexpr, return the constant value being addressed by the constant
4898/// expression, or null if something is funny.
4899///
4900static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004901 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004902 return 0; // Do not allow stepping over the value!
4903
4904 // Loop over all of the operands, tracking down which value we are
4905 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004906 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4907 for (++I; I != E; ++I)
4908 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4909 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4910 assert(CU->getValue() < STy->getNumElements() &&
4911 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004912 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00004913 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004914 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00004915 } else if (isa<ConstantAggregateZero>(C)) {
Jeff Cohen82639852005-04-23 21:38:35 +00004916 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00004917 } else if (isa<UndefValue>(C)) {
Jeff Cohen82639852005-04-23 21:38:35 +00004918 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004919 } else {
4920 return 0;
4921 }
4922 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4923 const ArrayType *ATy = cast<ArrayType>(*I);
4924 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4925 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004926 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004927 else if (isa<ConstantAggregateZero>(C))
4928 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004929 else if (isa<UndefValue>(C))
4930 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004931 else
4932 return 0;
4933 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004934 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004935 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004936 return C;
4937}
4938
Chris Lattner72684fe2005-01-31 05:51:45 +00004939/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00004940static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4941 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004942 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00004943
4944 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004945 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00004946 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004947
4948 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4949 // If the source is an array, the code below will not succeed. Check to
4950 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4951 // constants.
4952 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4953 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4954 if (ASrcTy->getNumElements() != 0) {
4955 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4956 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4957 SrcTy = cast<PointerType>(CastOp->getType());
4958 SrcPTy = SrcTy->getElementType();
4959 }
4960
4961 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00004962 // Do not allow turning this into a load of an integer, which is then
4963 // casted to a pointer, this pessimizes pointer analysis a lot.
4964 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004965 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004966 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004967
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004968 // Okay, we are casting from one integer or pointer type to another of
4969 // the same size. Instead of casting the pointer before the load, cast
4970 // the result of the loaded value.
4971 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
4972 CI->getName(),
4973 LI.isVolatile()),LI);
4974 // Now cast the result of the load.
4975 return new CastInst(NewLoad, LI.getType());
4976 }
Chris Lattner35e24772004-07-13 01:49:43 +00004977 }
4978 }
4979 return 0;
4980}
4981
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004982/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004983/// from this value cannot trap. If it is not obviously safe to load from the
4984/// specified pointer, we do a quick local scan of the basic block containing
4985/// ScanFrom, to determine if the address is already accessed.
4986static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4987 // If it is an alloca or global variable, it is always safe to load from.
4988 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4989
4990 // Otherwise, be a little bit agressive by scanning the local block where we
4991 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004992 // from/to. If so, the previous load or store would have already trapped,
4993 // so there is no harm doing an extra load (also, CSE will later eliminate
4994 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004995 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4996
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004997 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004998 --BBI;
4999
5000 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5001 if (LI->getOperand(0) == V) return true;
5002 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5003 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005004
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005005 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005006 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005007}
5008
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005009Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5010 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005011
Chris Lattnera9d84e32005-05-01 04:24:53 +00005012 // load (cast X) --> cast (load X) iff safe
5013 if (CastInst *CI = dyn_cast<CastInst>(Op))
5014 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5015 return Res;
5016
5017 // None of the following transforms are legal for volatile loads.
5018 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005019
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005020 if (&LI.getParent()->front() != &LI) {
5021 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005022 // If the instruction immediately before this is a store to the same
5023 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005024 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5025 if (SI->getOperand(1) == LI.getOperand(0))
5026 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005027 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5028 if (LIB->getOperand(0) == LI.getOperand(0))
5029 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005030 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005031
5032 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5033 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5034 isa<UndefValue>(GEPI->getOperand(0))) {
5035 // Insert a new store to null instruction before the load to indicate
5036 // that this code is not reachable. We do this instead of inserting
5037 // an unreachable instruction directly because we cannot modify the
5038 // CFG.
5039 new StoreInst(UndefValue::get(LI.getType()),
5040 Constant::getNullValue(Op->getType()), &LI);
5041 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5042 }
5043
Chris Lattner81a7a232004-10-16 18:11:37 +00005044 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005045 // load null/undef -> undef
5046 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005047 // Insert a new store to null instruction before the load to indicate that
5048 // this code is not reachable. We do this instead of inserting an
5049 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005050 new StoreInst(UndefValue::get(LI.getType()),
5051 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005052 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005053 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005054
Chris Lattner81a7a232004-10-16 18:11:37 +00005055 // Instcombine load (constant global) into the value loaded.
5056 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5057 if (GV->isConstant() && !GV->isExternal())
5058 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005059
Chris Lattner81a7a232004-10-16 18:11:37 +00005060 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5061 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5062 if (CE->getOpcode() == Instruction::GetElementPtr) {
5063 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5064 if (GV->isConstant() && !GV->isExternal())
5065 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
5066 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005067 if (CE->getOperand(0)->isNullValue()) {
5068 // Insert a new store to null instruction before the load to indicate
5069 // that this code is not reachable. We do this instead of inserting
5070 // an unreachable instruction directly because we cannot modify the
5071 // CFG.
5072 new StoreInst(UndefValue::get(LI.getType()),
5073 Constant::getNullValue(Op->getType()), &LI);
5074 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5075 }
5076
Chris Lattner81a7a232004-10-16 18:11:37 +00005077 } else if (CE->getOpcode() == Instruction::Cast) {
5078 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5079 return Res;
5080 }
5081 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005082
Chris Lattnera9d84e32005-05-01 04:24:53 +00005083 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005084 // Change select and PHI nodes to select values instead of addresses: this
5085 // helps alias analysis out a lot, allows many others simplifications, and
5086 // exposes redundancy in the code.
5087 //
5088 // Note that we cannot do the transformation unless we know that the
5089 // introduced loads cannot trap! Something like this is valid as long as
5090 // the condition is always false: load (select bool %C, int* null, int* %G),
5091 // but it would not be valid if we transformed it to load from null
5092 // unconditionally.
5093 //
5094 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5095 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005096 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5097 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005098 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005099 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005100 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005101 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005102 return new SelectInst(SI->getCondition(), V1, V2);
5103 }
5104
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005105 // load (select (cond, null, P)) -> load P
5106 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5107 if (C->isNullValue()) {
5108 LI.setOperand(0, SI->getOperand(2));
5109 return &LI;
5110 }
5111
5112 // load (select (cond, P, null)) -> load P
5113 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5114 if (C->isNullValue()) {
5115 LI.setOperand(0, SI->getOperand(1));
5116 return &LI;
5117 }
5118
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005119 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5120 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005121 bool Safe = PN->getParent() == LI.getParent();
5122
5123 // Scan all of the instructions between the PHI and the load to make
5124 // sure there are no instructions that might possibly alter the value
5125 // loaded from the PHI.
5126 if (Safe) {
5127 BasicBlock::iterator I = &LI;
5128 for (--I; !isa<PHINode>(I); --I)
5129 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5130 Safe = false;
5131 break;
5132 }
5133 }
5134
5135 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005136 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005137 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005138 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005139
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005140 if (Safe) {
5141 // Create the PHI.
5142 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5143 InsertNewInstBefore(NewPN, *PN);
5144 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5145
5146 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5147 BasicBlock *BB = PN->getIncomingBlock(i);
5148 Value *&TheLoad = LoadMap[BB];
5149 if (TheLoad == 0) {
5150 Value *InVal = PN->getIncomingValue(i);
5151 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5152 InVal->getName()+".val"),
5153 *BB->getTerminator());
5154 }
5155 NewPN->addIncoming(TheLoad, BB);
5156 }
5157 return ReplaceInstUsesWith(LI, NewPN);
5158 }
5159 }
5160 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005161 return 0;
5162}
5163
Chris Lattner72684fe2005-01-31 05:51:45 +00005164/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5165/// when possible.
5166static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5167 User *CI = cast<User>(SI.getOperand(1));
5168 Value *CastOp = CI->getOperand(0);
5169
5170 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5171 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5172 const Type *SrcPTy = SrcTy->getElementType();
5173
5174 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5175 // If the source is an array, the code below will not succeed. Check to
5176 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5177 // constants.
5178 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5179 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5180 if (ASrcTy->getNumElements() != 0) {
5181 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5182 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5183 SrcTy = cast<PointerType>(CastOp->getType());
5184 SrcPTy = SrcTy->getElementType();
5185 }
5186
5187 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005188 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005189 IC.getTargetData().getTypeSize(DestPTy)) {
5190
5191 // Okay, we are casting from one integer or pointer type to another of
5192 // the same size. Instead of casting the pointer before the store, cast
5193 // the value to be stored.
5194 Value *NewCast;
5195 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5196 NewCast = ConstantExpr::getCast(C, SrcPTy);
5197 else
5198 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5199 SrcPTy,
5200 SI.getOperand(0)->getName()+".c"), SI);
5201
5202 return new StoreInst(NewCast, CastOp);
5203 }
5204 }
5205 }
5206 return 0;
5207}
5208
Chris Lattner31f486c2005-01-31 05:36:43 +00005209Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5210 Value *Val = SI.getOperand(0);
5211 Value *Ptr = SI.getOperand(1);
5212
5213 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5214 removeFromWorkList(&SI);
5215 SI.eraseFromParent();
5216 ++NumCombined;
5217 return 0;
5218 }
5219
5220 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5221
5222 // store X, null -> turns into 'unreachable' in SimplifyCFG
5223 if (isa<ConstantPointerNull>(Ptr)) {
5224 if (!isa<UndefValue>(Val)) {
5225 SI.setOperand(0, UndefValue::get(Val->getType()));
5226 if (Instruction *U = dyn_cast<Instruction>(Val))
5227 WorkList.push_back(U); // Dropped a use.
5228 ++NumCombined;
5229 }
5230 return 0; // Do not modify these!
5231 }
5232
5233 // store undef, Ptr -> noop
5234 if (isa<UndefValue>(Val)) {
5235 removeFromWorkList(&SI);
5236 SI.eraseFromParent();
5237 ++NumCombined;
5238 return 0;
5239 }
5240
Chris Lattner72684fe2005-01-31 05:51:45 +00005241 // If the pointer destination is a cast, see if we can fold the cast into the
5242 // source instead.
5243 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5244 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5245 return Res;
5246 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5247 if (CE->getOpcode() == Instruction::Cast)
5248 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5249 return Res;
5250
Chris Lattner219175c2005-09-12 23:23:25 +00005251
5252 // If this store is the last instruction in the basic block, and if the block
5253 // ends with an unconditional branch, try to move it to the successor block.
5254 BasicBlock::iterator BBI = &SI; ++BBI;
5255 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5256 if (BI->isUnconditional()) {
5257 // Check to see if the successor block has exactly two incoming edges. If
5258 // so, see if the other predecessor contains a store to the same location.
5259 // if so, insert a PHI node (if needed) and move the stores down.
5260 BasicBlock *Dest = BI->getSuccessor(0);
5261
5262 pred_iterator PI = pred_begin(Dest);
5263 BasicBlock *Other = 0;
5264 if (*PI != BI->getParent())
5265 Other = *PI;
5266 ++PI;
5267 if (PI != pred_end(Dest)) {
5268 if (*PI != BI->getParent())
5269 if (Other)
5270 Other = 0;
5271 else
5272 Other = *PI;
5273 if (++PI != pred_end(Dest))
5274 Other = 0;
5275 }
5276 if (Other) { // If only one other pred...
5277 BBI = Other->getTerminator();
5278 // Make sure this other block ends in an unconditional branch and that
5279 // there is an instruction before the branch.
5280 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5281 BBI != Other->begin()) {
5282 --BBI;
5283 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5284
5285 // If this instruction is a store to the same location.
5286 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5287 // Okay, we know we can perform this transformation. Insert a PHI
5288 // node now if we need it.
5289 Value *MergedVal = OtherStore->getOperand(0);
5290 if (MergedVal != SI.getOperand(0)) {
5291 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5292 PN->reserveOperandSpace(2);
5293 PN->addIncoming(SI.getOperand(0), SI.getParent());
5294 PN->addIncoming(OtherStore->getOperand(0), Other);
5295 MergedVal = InsertNewInstBefore(PN, Dest->front());
5296 }
5297
5298 // Advance to a place where it is safe to insert the new store and
5299 // insert it.
5300 BBI = Dest->begin();
5301 while (isa<PHINode>(BBI)) ++BBI;
5302 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5303 OtherStore->isVolatile()), *BBI);
5304
5305 // Nuke the old stores.
5306 removeFromWorkList(&SI);
5307 removeFromWorkList(OtherStore);
5308 SI.eraseFromParent();
5309 OtherStore->eraseFromParent();
5310 ++NumCombined;
5311 return 0;
5312 }
5313 }
5314 }
5315 }
5316
Chris Lattner31f486c2005-01-31 05:36:43 +00005317 return 0;
5318}
5319
5320
Chris Lattner9eef8a72003-06-04 04:46:00 +00005321Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5322 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005323 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005324 BasicBlock *TrueDest;
5325 BasicBlock *FalseDest;
5326 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5327 !isa<Constant>(X)) {
5328 // Swap Destinations and condition...
5329 BI.setCondition(X);
5330 BI.setSuccessor(0, FalseDest);
5331 BI.setSuccessor(1, TrueDest);
5332 return &BI;
5333 }
5334
5335 // Cannonicalize setne -> seteq
5336 Instruction::BinaryOps Op; Value *Y;
5337 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5338 TrueDest, FalseDest)))
5339 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5340 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5341 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5342 std::string Name = I->getName(); I->setName("");
5343 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5344 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005345 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005346 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005347 BI.setSuccessor(0, FalseDest);
5348 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005349 removeFromWorkList(I);
5350 I->getParent()->getInstList().erase(I);
5351 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005352 return &BI;
5353 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005354
Chris Lattner9eef8a72003-06-04 04:46:00 +00005355 return 0;
5356}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005357
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005358Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5359 Value *Cond = SI.getCondition();
5360 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5361 if (I->getOpcode() == Instruction::Add)
5362 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5363 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5364 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005365 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005366 AddRHS));
5367 SI.setOperand(0, I->getOperand(0));
5368 WorkList.push_back(I);
5369 return &SI;
5370 }
5371 }
5372 return 0;
5373}
5374
Chris Lattnerca081252001-12-14 16:52:21 +00005375
Chris Lattner99f48c62002-09-02 04:59:56 +00005376void InstCombiner::removeFromWorkList(Instruction *I) {
5377 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5378 WorkList.end());
5379}
5380
Chris Lattner39c98bb2004-12-08 23:43:58 +00005381
5382/// TryToSinkInstruction - Try to move the specified instruction from its
5383/// current block into the beginning of DestBlock, which can only happen if it's
5384/// safe to move the instruction past all of the instructions between it and the
5385/// end of its block.
5386static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5387 assert(I->hasOneUse() && "Invariants didn't hold!");
5388
5389 // Cannot move control-flow-involving instructions.
5390 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005391
Chris Lattner39c98bb2004-12-08 23:43:58 +00005392 // Do not sink alloca instructions out of the entry block.
5393 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5394 return false;
5395
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005396 // We can only sink load instructions if there is nothing between the load and
5397 // the end of block that could change the value.
5398 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5399 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5400
5401 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5402 Scan != E; ++Scan)
5403 if (Scan->mayWriteToMemory())
5404 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005405 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005406
5407 BasicBlock::iterator InsertPos = DestBlock->begin();
5408 while (isa<PHINode>(InsertPos)) ++InsertPos;
5409
Chris Lattner9f269e42005-08-08 19:11:57 +00005410 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005411 ++NumSunkInst;
5412 return true;
5413}
5414
Chris Lattner113f4f42002-06-25 16:13:24 +00005415bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005416 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005417 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005418
Chris Lattner4ed40f72005-07-07 20:40:38 +00005419 {
5420 // Populate the worklist with the reachable instructions.
5421 std::set<BasicBlock*> Visited;
5422 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5423 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5424 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5425 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005426
Chris Lattner4ed40f72005-07-07 20:40:38 +00005427 // Do a quick scan over the function. If we find any blocks that are
5428 // unreachable, remove any instructions inside of them. This prevents
5429 // the instcombine code from having to deal with some bad special cases.
5430 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5431 if (!Visited.count(BB)) {
5432 Instruction *Term = BB->getTerminator();
5433 while (Term != BB->begin()) { // Remove instrs bottom-up
5434 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005435
Chris Lattner4ed40f72005-07-07 20:40:38 +00005436 DEBUG(std::cerr << "IC: DCE: " << *I);
5437 ++NumDeadInst;
5438
5439 if (!I->use_empty())
5440 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5441 I->eraseFromParent();
5442 }
5443 }
5444 }
Chris Lattnerca081252001-12-14 16:52:21 +00005445
5446 while (!WorkList.empty()) {
5447 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5448 WorkList.pop_back();
5449
Misha Brukman632df282002-10-29 23:06:16 +00005450 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005451 // Check to see if we can DIE the instruction...
5452 if (isInstructionTriviallyDead(I)) {
5453 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005454 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005455 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005456 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005457
Chris Lattnercd517ff2005-01-28 19:32:01 +00005458 DEBUG(std::cerr << "IC: DCE: " << *I);
5459
5460 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005461 removeFromWorkList(I);
5462 continue;
5463 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005464
Misha Brukman632df282002-10-29 23:06:16 +00005465 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005466 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005467 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005468 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005469 cast<Constant>(Ptr)->isNullValue() &&
5470 !isa<ConstantPointerNull>(C) &&
5471 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005472 // If this is a constant expr gep that is effectively computing an
5473 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5474 bool isFoldableGEP = true;
5475 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5476 if (!isa<ConstantInt>(I->getOperand(i)))
5477 isFoldableGEP = false;
5478 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005479 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005480 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5481 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005482 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005483 C = ConstantExpr::getCast(C, I->getType());
5484 }
5485 }
5486
Chris Lattnercd517ff2005-01-28 19:32:01 +00005487 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5488
Chris Lattner99f48c62002-09-02 04:59:56 +00005489 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005490 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005491 ReplaceInstUsesWith(*I, C);
5492
Chris Lattner99f48c62002-09-02 04:59:56 +00005493 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005494 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005495 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005496 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005497 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005498
Chris Lattner39c98bb2004-12-08 23:43:58 +00005499 // See if we can trivially sink this instruction to a successor basic block.
5500 if (I->hasOneUse()) {
5501 BasicBlock *BB = I->getParent();
5502 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5503 if (UserParent != BB) {
5504 bool UserIsSuccessor = false;
5505 // See if the user is one of our successors.
5506 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5507 if (*SI == UserParent) {
5508 UserIsSuccessor = true;
5509 break;
5510 }
5511
5512 // If the user is one of our immediate successors, and if that successor
5513 // only has us as a predecessors (we'd have to split the critical edge
5514 // otherwise), we can keep going.
5515 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5516 next(pred_begin(UserParent)) == pred_end(UserParent))
5517 // Okay, the CFG is simple enough, try to sink this instruction.
5518 Changed |= TryToSinkInstruction(I, UserParent);
5519 }
5520 }
5521
Chris Lattnerca081252001-12-14 16:52:21 +00005522 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005523 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005524 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005525 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005526 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005527 DEBUG(std::cerr << "IC: Old = " << *I
5528 << " New = " << *Result);
5529
Chris Lattner396dbfe2004-06-09 05:08:07 +00005530 // Everything uses the new instruction now.
5531 I->replaceAllUsesWith(Result);
5532
5533 // Push the new instruction and any users onto the worklist.
5534 WorkList.push_back(Result);
5535 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005536
5537 // Move the name to the new instruction first...
5538 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005539 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005540
5541 // Insert the new instruction into the basic block...
5542 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005543 BasicBlock::iterator InsertPos = I;
5544
5545 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5546 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5547 ++InsertPos;
5548
5549 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005550
Chris Lattner63d75af2004-05-01 23:27:23 +00005551 // Make sure that we reprocess all operands now that we reduced their
5552 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005553 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5554 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5555 WorkList.push_back(OpI);
5556
Chris Lattner396dbfe2004-06-09 05:08:07 +00005557 // Instructions can end up on the worklist more than once. Make sure
5558 // we do not process an instruction that has been deleted.
5559 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005560
5561 // Erase the old instruction.
5562 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005563 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005564 DEBUG(std::cerr << "IC: MOD = " << *I);
5565
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005566 // If the instruction was modified, it's possible that it is now dead.
5567 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005568 if (isInstructionTriviallyDead(I)) {
5569 // Make sure we process all operands now that we are reducing their
5570 // use counts.
5571 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5572 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5573 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005574
Chris Lattner63d75af2004-05-01 23:27:23 +00005575 // Instructions may end up in the worklist more than once. Erase all
5576 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005577 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005578 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005579 } else {
5580 WorkList.push_back(Result);
5581 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005582 }
Chris Lattner053c0932002-05-14 15:24:07 +00005583 }
Chris Lattner260ab202002-04-18 17:39:14 +00005584 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005585 }
5586 }
5587
Chris Lattner260ab202002-04-18 17:39:14 +00005588 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005589}
5590
Brian Gaeke38b79e82004-07-27 17:43:21 +00005591FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005592 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005593}
Brian Gaeke960707c2003-11-11 22:41:34 +00005594