blob: c4e07d7747de036279570dfa1c0660d1341c1fb9 [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 Lattneraf517572005-09-18 04:24:45 +0000225
226 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
227 bool isSub, Instruction &I);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000228 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
229 bool Inside, Instruction &IB);
Chris Lattner216be912005-10-24 06:03:58 +0000230 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattner260ab202002-04-18 17:39:14 +0000231 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000232
Chris Lattnerc8b70922002-07-26 21:12:46 +0000233 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000234}
235
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000236// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000237// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000238static unsigned getComplexity(Value *V) {
239 if (isa<Instruction>(V)) {
240 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000241 return 3;
242 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000243 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000244 if (isa<Argument>(V)) return 3;
245 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000246}
Chris Lattner260ab202002-04-18 17:39:14 +0000247
Chris Lattner7fb29e12003-03-11 00:12:48 +0000248// isOnlyUse - Return true if this instruction will be deleted if we stop using
249// it.
250static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000251 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000252}
253
Chris Lattnere79e8542004-02-23 06:38:22 +0000254// getPromotedType - Return the specified type promoted as it would be to pass
255// though a va_arg area...
256static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000257 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000258 case Type::SByteTyID:
259 case Type::ShortTyID: return Type::IntTy;
260 case Type::UByteTyID:
261 case Type::UShortTyID: return Type::UIntTy;
262 case Type::FloatTyID: return Type::DoubleTy;
263 default: return Ty;
264 }
265}
266
Chris Lattner567b81f2005-09-13 00:40:14 +0000267/// isCast - If the specified operand is a CastInst or a constant expr cast,
268/// return the operand value, otherwise return null.
269static Value *isCast(Value *V) {
270 if (CastInst *I = dyn_cast<CastInst>(V))
271 return I->getOperand(0);
272 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
273 if (CE->getOpcode() == Instruction::Cast)
274 return CE->getOperand(0);
275 return 0;
276}
277
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000278// SimplifyCommutative - This performs a few simplifications for commutative
279// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000280//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000281// 1. Order operands such that they are listed from right (least complex) to
282// left (most complex). This puts constants before unary operators before
283// binary operators.
284//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000285// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
286// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000287//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000288bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000289 bool Changed = false;
290 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
291 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000292
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000293 if (!I.isAssociative()) return Changed;
294 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000295 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
296 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
297 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000298 Constant *Folded = ConstantExpr::get(I.getOpcode(),
299 cast<Constant>(I.getOperand(1)),
300 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000301 I.setOperand(0, Op->getOperand(0));
302 I.setOperand(1, Folded);
303 return true;
304 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
305 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
306 isOnlyUse(Op) && isOnlyUse(Op1)) {
307 Constant *C1 = cast<Constant>(Op->getOperand(1));
308 Constant *C2 = cast<Constant>(Op1->getOperand(1));
309
310 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000311 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000312 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
313 Op1->getOperand(0),
314 Op1->getName(), &I);
315 WorkList.push_back(New);
316 I.setOperand(0, New);
317 I.setOperand(1, Folded);
318 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000319 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000320 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000321 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000322}
Chris Lattnerca081252001-12-14 16:52:21 +0000323
Chris Lattnerbb74e222003-03-10 23:06:50 +0000324// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
325// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000326//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000327static inline Value *dyn_castNegVal(Value *V) {
328 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000329 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000330
Chris Lattner9ad0d552004-12-14 20:08:06 +0000331 // Constants can be considered to be negated values if they can be folded.
332 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
333 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000334 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000335}
336
Chris Lattnerbb74e222003-03-10 23:06:50 +0000337static inline Value *dyn_castNotVal(Value *V) {
338 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000339 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000340
341 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000342 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000343 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000344 return 0;
345}
346
Chris Lattner7fb29e12003-03-11 00:12:48 +0000347// dyn_castFoldableMul - If this value is a multiply that can be folded into
348// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000349// non-constant operand of the multiply, and set CST to point to the multiplier.
350// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000351//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000352static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000353 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000354 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000355 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000356 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000357 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000358 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000359 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000360 // The multiplier is really 1 << CST.
361 Constant *One = ConstantInt::get(V->getType(), 1);
362 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
363 return I->getOperand(0);
364 }
365 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000366 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000367}
Chris Lattner31ae8632002-08-14 17:51:49 +0000368
Chris Lattner0798af32005-01-13 20:14:25 +0000369/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
370/// expression, return it.
371static User *dyn_castGetElementPtr(Value *V) {
372 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
373 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
374 if (CE->getOpcode() == Instruction::GetElementPtr)
375 return cast<User>(V);
376 return false;
377}
378
Chris Lattner623826c2004-09-28 21:48:02 +0000379// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000380static ConstantInt *AddOne(ConstantInt *C) {
381 return cast<ConstantInt>(ConstantExpr::getAdd(C,
382 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000383}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000384static ConstantInt *SubOne(ConstantInt *C) {
385 return cast<ConstantInt>(ConstantExpr::getSub(C,
386 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000387}
388
Chris Lattner0b3557f2005-09-24 23:43:33 +0000389/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
390/// this predicate to simplify operations downstream. V and Mask are known to
391/// be the same type.
392static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
393 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
394 // we cannot optimize based on the assumption that it is zero without changing
395 // to to an explicit zero. If we don't change it to zero, other code could
396 // optimized based on the contradictory assumption that it is non-zero.
397 // Because instcombine aggressively folds operations with undef args anyway,
398 // this won't lose us code quality.
399 if (Mask->isNullValue())
400 return true;
401 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
402 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
403
404 if (Instruction *I = dyn_cast<Instruction>(V)) {
405 switch (I->getOpcode()) {
Chris Lattner62010c42005-10-09 06:36:35 +0000406 case Instruction::And:
407 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
Chris Lattner03b9eb52005-10-09 22:08:50 +0000408 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
409 ConstantIntegral *C1C2 =
410 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
411 if (MaskedValueIsZero(I->getOperand(0), C1C2))
Chris Lattner62010c42005-10-09 06:36:35 +0000412 return true;
Chris Lattner03b9eb52005-10-09 22:08:50 +0000413 }
414 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
415 return MaskedValueIsZero(I->getOperand(1), Mask) ||
416 MaskedValueIsZero(I->getOperand(0), Mask);
Chris Lattner62010c42005-10-09 06:36:35 +0000417 case Instruction::Or:
Chris Lattner03b9eb52005-10-09 22:08:50 +0000418 case Instruction::Xor:
Chris Lattner62010c42005-10-09 06:36:35 +0000419 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
420 return MaskedValueIsZero(I->getOperand(1), Mask) &&
421 MaskedValueIsZero(I->getOperand(0), Mask);
422 case Instruction::Select:
423 // If the T and F values are MaskedValueIsZero, the result is also zero.
424 return MaskedValueIsZero(I->getOperand(2), Mask) &&
425 MaskedValueIsZero(I->getOperand(1), Mask);
426 case Instruction::Cast: {
427 const Type *SrcTy = I->getOperand(0)->getType();
428 if (SrcTy == Type::BoolTy)
429 return (Mask->getRawValue() & 1) == 0;
430
431 if (SrcTy->isInteger()) {
432 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
433 if (SrcTy->isUnsigned() && // Only handle zero ext.
434 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
435 return true;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000436
Chris Lattner62010c42005-10-09 06:36:35 +0000437 // If this is a noop cast, recurse.
438 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
439 SrcTy->getSignedVersion() == I->getType()) {
440 Constant *NewMask =
441 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +0000442 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner62010c42005-10-09 06:36:35 +0000443 cast<ConstantIntegral>(NewMask));
444 }
445 }
446 break;
447 }
448 case Instruction::Shl:
449 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
450 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
451 return MaskedValueIsZero(I->getOperand(0),
452 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)));
453 break;
454 case Instruction::Shr:
455 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
456 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
457 if (I->getType()->isUnsigned()) {
458 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
459 C1 = ConstantExpr::getShr(C1, SA);
460 C1 = ConstantExpr::getAnd(C1, Mask);
461 if (C1->isNullValue())
462 return true;
463 }
464 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000465 }
466 }
467
468 return false;
469}
470
Chris Lattner623826c2004-09-28 21:48:02 +0000471// isTrueWhenEqual - Return true if the specified setcondinst instruction is
472// true when both operands are equal...
473//
474static bool isTrueWhenEqual(Instruction &I) {
475 return I.getOpcode() == Instruction::SetEQ ||
476 I.getOpcode() == Instruction::SetGE ||
477 I.getOpcode() == Instruction::SetLE;
478}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000479
480/// AssociativeOpt - Perform an optimization on an associative operator. This
481/// function is designed to check a chain of associative operators for a
482/// potential to apply a certain optimization. Since the optimization may be
483/// applicable if the expression was reassociated, this checks the chain, then
484/// reassociates the expression as necessary to expose the optimization
485/// opportunity. This makes use of a special Functor, which must define
486/// 'shouldApply' and 'apply' methods.
487///
488template<typename Functor>
489Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
490 unsigned Opcode = Root.getOpcode();
491 Value *LHS = Root.getOperand(0);
492
493 // Quick check, see if the immediate LHS matches...
494 if (F.shouldApply(LHS))
495 return F.apply(Root);
496
497 // Otherwise, if the LHS is not of the same opcode as the root, return.
498 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000499 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000500 // Should we apply this transform to the RHS?
501 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
502
503 // If not to the RHS, check to see if we should apply to the LHS...
504 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
505 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
506 ShouldApply = true;
507 }
508
509 // If the functor wants to apply the optimization to the RHS of LHSI,
510 // reassociate the expression from ((? op A) op B) to (? op (A op B))
511 if (ShouldApply) {
512 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000513
Chris Lattnerb8b97502003-08-13 19:01:45 +0000514 // Now all of the instructions are in the current basic block, go ahead
515 // and perform the reassociation.
516 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
517
518 // First move the selected RHS to the LHS of the root...
519 Root.setOperand(0, LHSI->getOperand(1));
520
521 // Make what used to be the LHS of the root be the user of the root...
522 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000523 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000524 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
525 return 0;
526 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000527 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000528 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000529 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
530 BasicBlock::iterator ARI = &Root; ++ARI;
531 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
532 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000533
534 // Now propagate the ExtraOperand down the chain of instructions until we
535 // get to LHSI.
536 while (TmpLHSI != LHSI) {
537 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000538 // Move the instruction to immediately before the chain we are
539 // constructing to avoid breaking dominance properties.
540 NextLHSI->getParent()->getInstList().remove(NextLHSI);
541 BB->getInstList().insert(ARI, NextLHSI);
542 ARI = NextLHSI;
543
Chris Lattnerb8b97502003-08-13 19:01:45 +0000544 Value *NextOp = NextLHSI->getOperand(1);
545 NextLHSI->setOperand(1, ExtraOperand);
546 TmpLHSI = NextLHSI;
547 ExtraOperand = NextOp;
548 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000549
Chris Lattnerb8b97502003-08-13 19:01:45 +0000550 // Now that the instructions are reassociated, have the functor perform
551 // the transformation...
552 return F.apply(Root);
553 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000554
Chris Lattnerb8b97502003-08-13 19:01:45 +0000555 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
556 }
557 return 0;
558}
559
560
561// AddRHS - Implements: X + X --> X << 1
562struct AddRHS {
563 Value *RHS;
564 AddRHS(Value *rhs) : RHS(rhs) {}
565 bool shouldApply(Value *LHS) const { return LHS == RHS; }
566 Instruction *apply(BinaryOperator &Add) const {
567 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
568 ConstantInt::get(Type::UByteTy, 1));
569 }
570};
571
572// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
573// iff C1&C2 == 0
574struct AddMaskingAnd {
575 Constant *C2;
576 AddMaskingAnd(Constant *c) : C2(c) {}
577 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000578 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000579 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000580 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000581 }
582 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000583 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000584 }
585};
586
Chris Lattner86102b82005-01-01 16:22:27 +0000587static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000588 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000589 if (isa<CastInst>(I)) {
590 if (Constant *SOC = dyn_cast<Constant>(SO))
591 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000592
Chris Lattner86102b82005-01-01 16:22:27 +0000593 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
594 SO->getName() + ".cast"), I);
595 }
596
Chris Lattner183b3362004-04-09 19:05:30 +0000597 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000598 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
599 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000600
Chris Lattner183b3362004-04-09 19:05:30 +0000601 if (Constant *SOC = dyn_cast<Constant>(SO)) {
602 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000603 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
604 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000605 }
606
607 Value *Op0 = SO, *Op1 = ConstOperand;
608 if (!ConstIsRHS)
609 std::swap(Op0, Op1);
610 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000611 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
612 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
613 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
614 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000615 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000616 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000617 abort();
618 }
Chris Lattner86102b82005-01-01 16:22:27 +0000619 return IC->InsertNewInstBefore(New, I);
620}
621
622// FoldOpIntoSelect - Given an instruction with a select as one operand and a
623// constant as the other operand, try to fold the binary operator into the
624// select arguments. This also works for Cast instructions, which obviously do
625// not have a second operand.
626static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
627 InstCombiner *IC) {
628 // Don't modify shared select instructions
629 if (!SI->hasOneUse()) return 0;
630 Value *TV = SI->getOperand(1);
631 Value *FV = SI->getOperand(2);
632
633 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000634 // Bool selects with constant operands can be folded to logical ops.
635 if (SI->getType() == Type::BoolTy) return 0;
636
Chris Lattner86102b82005-01-01 16:22:27 +0000637 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
638 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
639
640 return new SelectInst(SI->getCondition(), SelectTrueVal,
641 SelectFalseVal);
642 }
643 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000644}
645
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000646
647/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
648/// node as operand #0, see if we can fold the instruction into the PHI (which
649/// is only possible if all operands to the PHI are constants).
650Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
651 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000652 unsigned NumPHIValues = PN->getNumIncomingValues();
653 if (!PN->hasOneUse() || NumPHIValues == 0 ||
654 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000655
656 // Check to see if all of the operands of the PHI are constants. If not, we
657 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000658 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000659 if (!isa<Constant>(PN->getIncomingValue(i)))
660 return 0;
661
662 // Okay, we can do the transformation: create the new PHI node.
663 PHINode *NewPN = new PHINode(I.getType(), I.getName());
664 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000665 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000666 InsertNewInstBefore(NewPN, *PN);
667
668 // Next, add all of the operands to the PHI.
669 if (I.getNumOperands() == 2) {
670 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000671 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000672 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
673 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
674 PN->getIncomingBlock(i));
675 }
676 } else {
677 assert(isa<CastInst>(I) && "Unary op should be a cast!");
678 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000679 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000680 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
681 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
682 PN->getIncomingBlock(i));
683 }
684 }
685 return ReplaceInstUsesWith(I, NewPN);
686}
687
Chris Lattner113f4f42002-06-25 16:13:24 +0000688Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000689 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000690 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000691
Chris Lattnercf4a9962004-04-10 22:01:55 +0000692 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000693 // X + undef -> undef
694 if (isa<UndefValue>(RHS))
695 return ReplaceInstUsesWith(I, RHS);
696
Chris Lattnercf4a9962004-04-10 22:01:55 +0000697 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +0000698 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
699 if (RHSC->isNullValue())
700 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +0000701 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
702 if (CFP->isExactlyValue(-0.0))
703 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +0000704 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000705
Chris Lattnercf4a9962004-04-10 22:01:55 +0000706 // X + (signbit) --> X ^ signbit
707 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000708 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnercf4a9962004-04-10 22:01:55 +0000709 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000710 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000711 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000712 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000713
714 if (isa<PHINode>(LHS))
715 if (Instruction *NV = FoldOpIntoPhi(I))
716 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000717
718 ConstantInt *XorRHS;
719 Value *XorLHS;
720 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
721 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
722 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
723 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
724
725 uint64_t C0080Val = 1ULL << 31;
726 int64_t CFF80Val = -C0080Val;
727 unsigned Size = 32;
728 do {
729 if (TySizeBits > Size) {
730 bool Found = false;
731 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
732 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
733 if (RHSSExt == CFF80Val) {
734 if (XorRHS->getZExtValue() == C0080Val)
735 Found = true;
736 } else if (RHSZExt == C0080Val) {
737 if (XorRHS->getSExtValue() == CFF80Val)
738 Found = true;
739 }
740 if (Found) {
741 // This is a sign extend if the top bits are known zero.
742 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
743 Mask = ConstantExpr::getShl(Mask,
744 ConstantInt::get(Type::UByteTy, 64-TySizeBits-Size));
745 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
746 Size = 0; // Not a sign ext, but can't be any others either.
747 goto FoundSExt;
748 }
749 }
750 Size >>= 1;
751 C0080Val >>= Size;
752 CFF80Val >>= Size;
753 } while (Size >= 8);
754
755FoundSExt:
756 const Type *MiddleType = 0;
757 switch (Size) {
758 default: break;
759 case 32: MiddleType = Type::IntTy; break;
760 case 16: MiddleType = Type::ShortTy; break;
761 case 8: MiddleType = Type::SByteTy; break;
762 }
763 if (MiddleType) {
764 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
765 InsertNewInstBefore(NewTrunc, I);
766 return new CastInst(NewTrunc, I.getType());
767 }
768 }
Chris Lattnercf4a9962004-04-10 22:01:55 +0000769 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000770
Chris Lattnerb8b97502003-08-13 19:01:45 +0000771 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000772 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000773 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000774
775 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
776 if (RHSI->getOpcode() == Instruction::Sub)
777 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
778 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
779 }
780 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
781 if (LHSI->getOpcode() == Instruction::Sub)
782 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
783 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
784 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000785 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000786
Chris Lattner147e9752002-05-08 22:46:53 +0000787 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000788 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000789 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000790
791 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000792 if (!isa<Constant>(RHS))
793 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000794 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000795
Misha Brukmanb1c93172005-04-21 23:48:37 +0000796
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000797 ConstantInt *C2;
798 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
799 if (X == RHS) // X*C + X --> X * (C+1)
800 return BinaryOperator::createMul(RHS, AddOne(C2));
801
802 // X*C1 + X*C2 --> X * (C1+C2)
803 ConstantInt *C1;
804 if (X == dyn_castFoldableMul(RHS, C1))
805 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000806 }
807
808 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000809 if (dyn_castFoldableMul(RHS, C2) == LHS)
810 return BinaryOperator::createMul(LHS, AddOne(C2));
811
Chris Lattner57c8d992003-02-18 19:57:07 +0000812
Chris Lattnerb8b97502003-08-13 19:01:45 +0000813 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000814 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000815 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000816
Chris Lattnerb9cde762003-10-02 15:11:26 +0000817 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000818 Value *X;
819 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
820 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
821 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000822 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000823
Chris Lattnerbff91d92004-10-08 05:07:56 +0000824 // (X & FF00) + xx00 -> (X+xx00) & FF00
825 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
826 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
827 if (Anded == CRHS) {
828 // See if all bits from the first bit set in the Add RHS up are included
829 // in the mask. First, get the rightmost bit.
830 uint64_t AddRHSV = CRHS->getRawValue();
831
832 // Form a mask of all bits from the lowest bit added through the top.
833 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner2f1457f2005-04-24 17:46:05 +0000834 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerbff91d92004-10-08 05:07:56 +0000835
836 // See if the and mask includes all of these bits.
837 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000838
Chris Lattnerbff91d92004-10-08 05:07:56 +0000839 if (AddRHSHighBits == AddRHSHighBitsAnd) {
840 // Okay, the xform is safe. Insert the new add pronto.
841 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
842 LHS->getName()), I);
843 return BinaryOperator::createAnd(NewAdd, C2);
844 }
845 }
846 }
847
Chris Lattnerd4252a72004-07-30 07:50:03 +0000848 // Try to fold constant add into select arguments.
849 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000850 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000851 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000852 }
853
Chris Lattner113f4f42002-06-25 16:13:24 +0000854 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000855}
856
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000857// isSignBit - Return true if the value represented by the constant only has the
858// highest order bit set.
859static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000860 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000861 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000862}
863
Chris Lattner022167f2004-03-13 00:11:49 +0000864/// RemoveNoopCast - Strip off nonconverting casts from the value.
865///
866static Value *RemoveNoopCast(Value *V) {
867 if (CastInst *CI = dyn_cast<CastInst>(V)) {
868 const Type *CTy = CI->getType();
869 const Type *OpTy = CI->getOperand(0)->getType();
870 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000871 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000872 return RemoveNoopCast(CI->getOperand(0));
873 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
874 return RemoveNoopCast(CI->getOperand(0));
875 }
876 return V;
877}
878
Chris Lattner113f4f42002-06-25 16:13:24 +0000879Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000880 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000881
Chris Lattnere6794492002-08-12 21:17:25 +0000882 if (Op0 == Op1) // sub X, X -> 0
883 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000884
Chris Lattnere6794492002-08-12 21:17:25 +0000885 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000886 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000887 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000888
Chris Lattner81a7a232004-10-16 18:11:37 +0000889 if (isa<UndefValue>(Op0))
890 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
891 if (isa<UndefValue>(Op1))
892 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
893
Chris Lattner8f2f5982003-11-05 01:06:05 +0000894 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
895 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000896 if (C->isAllOnesValue())
897 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000898
Chris Lattner8f2f5982003-11-05 01:06:05 +0000899 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000900 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000901 if (match(Op1, m_Not(m_Value(X))))
902 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000903 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000904 // -((uint)X >> 31) -> ((int)X >> 31)
905 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000906 if (C->isNullValue()) {
907 Value *NoopCastedRHS = RemoveNoopCast(Op1);
908 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000909 if (SI->getOpcode() == Instruction::Shr)
910 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
911 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000912 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000913 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000914 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000915 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000916 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000917 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000918 // Ok, the transformation is safe. Insert a cast of the incoming
919 // value, then the new shift, then the new cast.
920 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
921 SI->getOperand(0)->getName());
922 Value *InV = InsertNewInstBefore(FirstCast, I);
923 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
924 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000925 if (NewShift->getType() == I.getType())
926 return NewShift;
927 else {
928 InV = InsertNewInstBefore(NewShift, I);
929 return new CastInst(NewShift, I.getType());
930 }
Chris Lattner92295c52004-03-12 23:53:13 +0000931 }
932 }
Chris Lattner022167f2004-03-13 00:11:49 +0000933 }
Chris Lattner183b3362004-04-09 19:05:30 +0000934
935 // Try to fold constant sub into select arguments.
936 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000937 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000938 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000939
940 if (isa<PHINode>(Op0))
941 if (Instruction *NV = FoldOpIntoPhi(I))
942 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000943 }
944
Chris Lattnera9be4492005-04-07 16:15:25 +0000945 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
946 if (Op1I->getOpcode() == Instruction::Add &&
947 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000948 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000949 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000950 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000951 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000952 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
953 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
954 // C1-(X+C2) --> (C1-C2)-X
955 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
956 Op1I->getOperand(0));
957 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000958 }
959
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000960 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000961 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
962 // is not used by anyone else...
963 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000964 if (Op1I->getOpcode() == Instruction::Sub &&
965 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000966 // Swap the two operands of the subexpr...
967 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
968 Op1I->setOperand(0, IIOp1);
969 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000970
Chris Lattner3082c5a2003-02-18 19:28:33 +0000971 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000972 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000973 }
974
975 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
976 //
977 if (Op1I->getOpcode() == Instruction::And &&
978 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
979 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
980
Chris Lattner396dbfe2004-06-09 05:08:07 +0000981 Value *NewNot =
982 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000983 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000984 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000985
Chris Lattner0aee4b72004-10-06 15:08:25 +0000986 // -(X sdiv C) -> (X sdiv -C)
987 if (Op1I->getOpcode() == Instruction::Div)
988 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000989 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000990 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000991 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000992 ConstantExpr::getNeg(DivRHS));
993
Chris Lattner57c8d992003-02-18 19:57:07 +0000994 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000995 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000996 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000997 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000998 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000999 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001000 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001001 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001002 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001003
Chris Lattner47060462005-04-07 17:14:51 +00001004 if (!Op0->getType()->isFloatingPoint())
1005 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1006 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001007 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1008 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1009 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1010 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001011 } else if (Op0I->getOpcode() == Instruction::Sub) {
1012 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1013 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001014 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001015
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001016 ConstantInt *C1;
1017 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1018 if (X == Op1) { // X*C - X --> X * (C-1)
1019 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1020 return BinaryOperator::createMul(Op1, CP1);
1021 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001022
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001023 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1024 if (X == dyn_castFoldableMul(Op1, C2))
1025 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1026 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001027 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001028}
1029
Chris Lattnere79e8542004-02-23 06:38:22 +00001030/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1031/// really just returns true if the most significant (sign) bit is set.
1032static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1033 if (RHS->getType()->isSigned()) {
1034 // True if source is LHS < 0 or LHS <= -1
1035 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1036 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1037 } else {
1038 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1039 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1040 // the size of the integer type.
1041 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001042 return RHSC->getValue() ==
1043 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001044 if (Opcode == Instruction::SetGT)
1045 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001046 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001047 }
1048 return false;
1049}
1050
Chris Lattner113f4f42002-06-25 16:13:24 +00001051Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001052 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001053 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001054
Chris Lattner81a7a232004-10-16 18:11:37 +00001055 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1056 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1057
Chris Lattnere6794492002-08-12 21:17:25 +00001058 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001059 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1060 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001061
1062 // ((X << C1)*C2) == (X * (C2 << C1))
1063 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1064 if (SI->getOpcode() == Instruction::Shl)
1065 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001066 return BinaryOperator::createMul(SI->getOperand(0),
1067 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001068
Chris Lattnercce81be2003-09-11 22:24:54 +00001069 if (CI->isNullValue())
1070 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1071 if (CI->equalsInt(1)) // X * 1 == X
1072 return ReplaceInstUsesWith(I, Op0);
1073 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001074 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001075
Chris Lattnercce81be2003-09-11 22:24:54 +00001076 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001077 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1078 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001079 return new ShiftInst(Instruction::Shl, Op0,
1080 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001081 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001082 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001083 if (Op1F->isNullValue())
1084 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001085
Chris Lattner3082c5a2003-02-18 19:28:33 +00001086 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1087 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1088 if (Op1F->getValue() == 1.0)
1089 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1090 }
Chris Lattner183b3362004-04-09 19:05:30 +00001091
1092 // Try to fold constant mul into select arguments.
1093 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001094 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001095 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001096
1097 if (isa<PHINode>(Op0))
1098 if (Instruction *NV = FoldOpIntoPhi(I))
1099 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001100 }
1101
Chris Lattner934a64cf2003-03-10 23:23:04 +00001102 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1103 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001104 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001105
Chris Lattner2635b522004-02-23 05:39:21 +00001106 // If one of the operands of the multiply is a cast from a boolean value, then
1107 // we know the bool is either zero or one, so this is a 'masking' multiply.
1108 // See if we can simplify things based on how the boolean was originally
1109 // formed.
1110 CastInst *BoolCast = 0;
1111 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1112 if (CI->getOperand(0)->getType() == Type::BoolTy)
1113 BoolCast = CI;
1114 if (!BoolCast)
1115 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1116 if (CI->getOperand(0)->getType() == Type::BoolTy)
1117 BoolCast = CI;
1118 if (BoolCast) {
1119 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1120 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1121 const Type *SCOpTy = SCIOp0->getType();
1122
Chris Lattnere79e8542004-02-23 06:38:22 +00001123 // If the setcc is true iff the sign bit of X is set, then convert this
1124 // multiply into a shift/and combination.
1125 if (isa<ConstantInt>(SCIOp1) &&
1126 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001127 // Shift the X value right to turn it into "all signbits".
1128 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001129 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001130 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001131 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001132 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1133 SCIOp0->getName()), I);
1134 }
1135
1136 Value *V =
1137 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1138 BoolCast->getOperand(0)->getName()+
1139 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001140
1141 // If the multiply type is not the same as the source type, sign extend
1142 // or truncate to the multiply type.
1143 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001144 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001145
Chris Lattner2635b522004-02-23 05:39:21 +00001146 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001147 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001148 }
1149 }
1150 }
1151
Chris Lattner113f4f42002-06-25 16:13:24 +00001152 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001153}
1154
Chris Lattner113f4f42002-06-25 16:13:24 +00001155Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001157
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001158 if (isa<UndefValue>(Op0)) // undef / X -> 0
1159 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1160 if (isa<UndefValue>(Op1))
1161 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1162
1163 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001164 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001165 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001166 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001167
Chris Lattnere20c3342004-04-26 14:01:59 +00001168 // div X, -1 == -X
1169 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001170 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001171
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001172 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001173 if (LHS->getOpcode() == Instruction::Div)
1174 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001175 // (X / C1) / C2 -> X / (C1*C2)
1176 return BinaryOperator::createDiv(LHS->getOperand(0),
1177 ConstantExpr::getMul(RHS, LHSRHS));
1178 }
1179
Chris Lattner3082c5a2003-02-18 19:28:33 +00001180 // Check to see if this is an unsigned division with an exact power of 2,
1181 // if so, convert to a right shift.
1182 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1183 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001184 if (isPowerOf2_64(Val)) {
1185 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001186 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001187 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001188 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001189
Chris Lattner4ad08352004-10-09 02:50:40 +00001190 // -X/C -> X/-C
1191 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001192 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001193 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1194
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001195 if (!RHS->isNullValue()) {
1196 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001197 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001198 return R;
1199 if (isa<PHINode>(Op0))
1200 if (Instruction *NV = FoldOpIntoPhi(I))
1201 return NV;
1202 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001203 }
1204
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001205 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1206 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1207 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1208 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1209 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1210 if (STO->getValue() == 0) { // Couldn't be this argument.
1211 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001212 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001213 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001214 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001215 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001216 }
1217
Chris Lattner42362612005-04-08 04:03:26 +00001218 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001219 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1220 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001221 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1222 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1223 TC, SI->getName()+".t");
1224 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001225
Chris Lattner42362612005-04-08 04:03:26 +00001226 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1227 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1228 FC, SI->getName()+".f");
1229 FSI = InsertNewInstBefore(FSI, I);
1230 return new SelectInst(SI->getOperand(0), TSI, FSI);
1231 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001232 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001233
Chris Lattner3082c5a2003-02-18 19:28:33 +00001234 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001235 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001236 if (LHS->equalsInt(0))
1237 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1238
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001239 return 0;
1240}
1241
1242
Chris Lattner113f4f42002-06-25 16:13:24 +00001243Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001244 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001245 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001246 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001247 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001248 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001249 // X % -Y -> X % Y
1250 AddUsesToWorkList(I);
1251 I.setOperand(1, RHSNeg);
1252 return &I;
1253 }
1254
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001255 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001256 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001257 if (isa<UndefValue>(Op1))
1258 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001259
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001260 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001261 if (RHS->equalsInt(1)) // X % 1 == 0
1262 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1263
1264 // Check to see if this is an unsigned remainder with an exact power of 2,
1265 // if so, convert to a bitwise and.
1266 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1267 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001268 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001269 return BinaryOperator::createAnd(Op0,
1270 ConstantUInt::get(I.getType(), Val-1));
1271
1272 if (!RHS->isNullValue()) {
1273 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001274 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001275 return R;
1276 if (isa<PHINode>(Op0))
1277 if (Instruction *NV = FoldOpIntoPhi(I))
1278 return NV;
1279 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001280 }
1281
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001282 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1283 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1284 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1285 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1286 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1287 if (STO->getValue() == 0) { // Couldn't be this argument.
1288 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001289 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001290 } else if (SFO->getValue() == 0) {
1291 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001292 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001293 }
1294
1295 if (!(STO->getValue() & (STO->getValue()-1)) &&
1296 !(SFO->getValue() & (SFO->getValue()-1))) {
1297 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1298 SubOne(STO), SI->getName()+".t"), I);
1299 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1300 SubOne(SFO), SI->getName()+".f"), I);
1301 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1302 }
1303 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001304
Chris Lattner3082c5a2003-02-18 19:28:33 +00001305 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001306 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001307 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001308 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1309
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001310 return 0;
1311}
1312
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001313// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001314static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001315 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1316 // Calculate -1 casted to the right type...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001317 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001318 uint64_t Val = ~0ULL; // All ones
1319 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1320 return CU->getValue() == Val-1;
1321 }
1322
1323 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001324
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001325 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001326 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001327 int64_t Val = INT64_MAX; // All ones
1328 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1329 return CS->getValue() == Val-1;
1330}
1331
1332// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001333static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001334 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1335 return CU->getValue() == 1;
1336
1337 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001338
1339 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001340 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001341 int64_t Val = -1; // All ones
1342 Val <<= TypeBits-1; // Shift over to the right spot
1343 return CS->getValue() == Val+1;
1344}
1345
Chris Lattner35167c32004-06-09 07:59:58 +00001346// isOneBitSet - Return true if there is exactly one bit set in the specified
1347// constant.
1348static bool isOneBitSet(const ConstantInt *CI) {
1349 uint64_t V = CI->getRawValue();
1350 return V && (V & (V-1)) == 0;
1351}
1352
Chris Lattner8fc5af42004-09-23 21:46:38 +00001353#if 0 // Currently unused
1354// isLowOnes - Return true if the constant is of the form 0+1+.
1355static bool isLowOnes(const ConstantInt *CI) {
1356 uint64_t V = CI->getRawValue();
1357
1358 // There won't be bits set in parts that the type doesn't contain.
1359 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1360
1361 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1362 return U && V && (U & V) == 0;
1363}
1364#endif
1365
1366// isHighOnes - Return true if the constant is of the form 1+0+.
1367// This is the same as lowones(~X).
1368static bool isHighOnes(const ConstantInt *CI) {
1369 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001370 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001371
1372 // There won't be bits set in parts that the type doesn't contain.
1373 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1374
1375 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1376 return U && V && (U & V) == 0;
1377}
1378
1379
Chris Lattner3ac7c262003-08-13 20:16:26 +00001380/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1381/// are carefully arranged to allow folding of expressions such as:
1382///
1383/// (A < B) | (A > B) --> (A != B)
1384///
1385/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1386/// represents that the comparison is true if A == B, and bit value '1' is true
1387/// if A < B.
1388///
1389static unsigned getSetCondCode(const SetCondInst *SCI) {
1390 switch (SCI->getOpcode()) {
1391 // False -> 0
1392 case Instruction::SetGT: return 1;
1393 case Instruction::SetEQ: return 2;
1394 case Instruction::SetGE: return 3;
1395 case Instruction::SetLT: return 4;
1396 case Instruction::SetNE: return 5;
1397 case Instruction::SetLE: return 6;
1398 // True -> 7
1399 default:
1400 assert(0 && "Invalid SetCC opcode!");
1401 return 0;
1402 }
1403}
1404
1405/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1406/// opcode and two operands into either a constant true or false, or a brand new
1407/// SetCC instruction.
1408static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1409 switch (Opcode) {
1410 case 0: return ConstantBool::False;
1411 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1412 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1413 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1414 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1415 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1416 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1417 case 7: return ConstantBool::True;
1418 default: assert(0 && "Illegal SetCCCode!"); return 0;
1419 }
1420}
1421
1422// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1423struct FoldSetCCLogical {
1424 InstCombiner &IC;
1425 Value *LHS, *RHS;
1426 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1427 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1428 bool shouldApply(Value *V) const {
1429 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1430 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1431 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1432 return false;
1433 }
1434 Instruction *apply(BinaryOperator &Log) const {
1435 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1436 if (SCI->getOperand(0) != LHS) {
1437 assert(SCI->getOperand(1) == LHS);
1438 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1439 }
1440
1441 unsigned LHSCode = getSetCondCode(SCI);
1442 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1443 unsigned Code;
1444 switch (Log.getOpcode()) {
1445 case Instruction::And: Code = LHSCode & RHSCode; break;
1446 case Instruction::Or: Code = LHSCode | RHSCode; break;
1447 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001448 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001449 }
1450
1451 Value *RV = getSetCCValue(Code, LHS, RHS);
1452 if (Instruction *I = dyn_cast<Instruction>(RV))
1453 return I;
1454 // Otherwise, it's a constant boolean value...
1455 return IC.ReplaceInstUsesWith(Log, RV);
1456 }
1457};
1458
Chris Lattnerba1cb382003-09-19 17:17:26 +00001459// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1460// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1461// guaranteed to be either a shift instruction or a binary operator.
1462Instruction *InstCombiner::OptAndOp(Instruction *Op,
1463 ConstantIntegral *OpRHS,
1464 ConstantIntegral *AndRHS,
1465 BinaryOperator &TheAnd) {
1466 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001467 Constant *Together = 0;
1468 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001469 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001470
Chris Lattnerba1cb382003-09-19 17:17:26 +00001471 switch (Op->getOpcode()) {
1472 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001473 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001474 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1475 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001476 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001477 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001478 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001479 }
1480 break;
1481 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001482 if (Together == AndRHS) // (X | C) & C --> C
1483 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001484
Chris Lattner86102b82005-01-01 16:22:27 +00001485 if (Op->hasOneUse() && Together != OpRHS) {
1486 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1487 std::string Op0Name = Op->getName(); Op->setName("");
1488 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1489 InsertNewInstBefore(Or, TheAnd);
1490 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001491 }
1492 break;
1493 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001494 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001495 // Adding a one to a single bit bit-field should be turned into an XOR
1496 // of the bit. First thing to check is to see if this AND is with a
1497 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001498 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001499
1500 // Clear bits that are not part of the constant.
Chris Lattner2f1457f2005-04-24 17:46:05 +00001501 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerba1cb382003-09-19 17:17:26 +00001502
1503 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001504 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001505 // Ok, at this point, we know that we are masking the result of the
1506 // ADD down to exactly one bit. If the constant we are adding has
1507 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001508 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001509
Chris Lattnerba1cb382003-09-19 17:17:26 +00001510 // Check to see if any bits below the one bit set in AndRHSV are set.
1511 if ((AddRHS & (AndRHSV-1)) == 0) {
1512 // If not, the only thing that can effect the output of the AND is
1513 // the bit specified by AndRHSV. If that bit is set, the effect of
1514 // the XOR is to toggle the bit. If it is clear, then the ADD has
1515 // no effect.
1516 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1517 TheAnd.setOperand(0, X);
1518 return &TheAnd;
1519 } else {
1520 std::string Name = Op->getName(); Op->setName("");
1521 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001522 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001523 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001524 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001525 }
1526 }
1527 }
1528 }
1529 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001530
1531 case Instruction::Shl: {
1532 // We know that the AND will not produce any of the bits shifted in, so if
1533 // the anded constant includes them, clear them now!
1534 //
1535 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001536 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1537 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001538
Chris Lattner7e794272004-09-24 15:21:34 +00001539 if (CI == ShlMask) { // Masking out bits that the shift already masks
1540 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1541 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001542 TheAnd.setOperand(1, CI);
1543 return &TheAnd;
1544 }
1545 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001546 }
Chris Lattner2da29172003-09-19 19:05:02 +00001547 case Instruction::Shr:
1548 // We know that the AND will not produce any of the bits shifted in, so if
1549 // the anded constant includes them, clear them now! This only applies to
1550 // unsigned shifts, because a signed shr may bring in set bits!
1551 //
1552 if (AndRHS->getType()->isUnsigned()) {
1553 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001554 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1555 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1556
1557 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1558 return ReplaceInstUsesWith(TheAnd, Op);
1559 } else if (CI != AndRHS) {
1560 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001561 return &TheAnd;
1562 }
Chris Lattner7e794272004-09-24 15:21:34 +00001563 } else { // Signed shr.
1564 // See if this is shifting in some sign extension, then masking it out
1565 // with an and.
1566 if (Op->hasOneUse()) {
1567 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1568 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1569 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001570 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001571 // Make the argument unsigned.
1572 Value *ShVal = Op->getOperand(0);
1573 ShVal = InsertCastBefore(ShVal,
1574 ShVal->getType()->getUnsignedVersion(),
1575 TheAnd);
1576 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1577 OpRHS, Op->getName()),
1578 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001579 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1580 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1581 TheAnd.getName()),
1582 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001583 return new CastInst(ShVal, Op->getType());
1584 }
1585 }
Chris Lattner2da29172003-09-19 19:05:02 +00001586 }
1587 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001588 }
1589 return 0;
1590}
1591
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001592
Chris Lattner6862fbd2004-09-29 17:40:11 +00001593/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1594/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1595/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1596/// insert new instructions.
1597Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1598 bool Inside, Instruction &IB) {
1599 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1600 "Lo is not <= Hi in range emission code!");
1601 if (Inside) {
1602 if (Lo == Hi) // Trivially false.
1603 return new SetCondInst(Instruction::SetNE, V, V);
1604 if (cast<ConstantIntegral>(Lo)->isMinValue())
1605 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001606
Chris Lattner6862fbd2004-09-29 17:40:11 +00001607 Constant *AddCST = ConstantExpr::getNeg(Lo);
1608 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1609 InsertNewInstBefore(Add, IB);
1610 // Convert to unsigned for the comparison.
1611 const Type *UnsType = Add->getType()->getUnsignedVersion();
1612 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1613 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1614 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1615 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1616 }
1617
1618 if (Lo == Hi) // Trivially true.
1619 return new SetCondInst(Instruction::SetEQ, V, V);
1620
1621 Hi = SubOne(cast<ConstantInt>(Hi));
1622 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1623 return new SetCondInst(Instruction::SetGT, V, Hi);
1624
1625 // Emit X-Lo > Hi-Lo-1
1626 Constant *AddCST = ConstantExpr::getNeg(Lo);
1627 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1628 InsertNewInstBefore(Add, IB);
1629 // Convert to unsigned for the comparison.
1630 const Type *UnsType = Add->getType()->getUnsignedVersion();
1631 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1632 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1633 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1634 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1635}
1636
Chris Lattnerb4b25302005-09-18 07:22:02 +00001637// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1638// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1639// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1640// not, since all 1s are not contiguous.
1641static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1642 uint64_t V = Val->getRawValue();
1643 if (!isShiftedMask_64(V)) return false;
1644
1645 // look for the first zero bit after the run of ones
1646 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1647 // look for the first non-zero bit
1648 ME = 64-CountLeadingZeros_64(V);
1649 return true;
1650}
1651
1652
1653
1654/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1655/// where isSub determines whether the operator is a sub. If we can fold one of
1656/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00001657///
1658/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1659/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1660/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1661///
1662/// return (A +/- B).
1663///
1664Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1665 ConstantIntegral *Mask, bool isSub,
1666 Instruction &I) {
1667 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1668 if (!LHSI || LHSI->getNumOperands() != 2 ||
1669 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1670
1671 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1672
1673 switch (LHSI->getOpcode()) {
1674 default: return 0;
1675 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001676 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1677 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1678 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1679 break;
1680
1681 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1682 // part, we don't need any explicit masks to take them out of A. If that
1683 // is all N is, ignore it.
1684 unsigned MB, ME;
1685 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1686 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1687 Mask = ConstantExpr::getUShr(Mask,
1688 ConstantInt::get(Type::UByteTy,
1689 (64-MB+1)));
1690 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1691 break;
1692 }
1693 }
Chris Lattneraf517572005-09-18 04:24:45 +00001694 return 0;
1695 case Instruction::Or:
1696 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001697 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1698 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1699 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00001700 break;
1701 return 0;
1702 }
1703
1704 Instruction *New;
1705 if (isSub)
1706 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1707 else
1708 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1709 return InsertNewInstBefore(New, I);
1710}
1711
Chris Lattner113f4f42002-06-25 16:13:24 +00001712Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001713 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001715
Chris Lattner81a7a232004-10-16 18:11:37 +00001716 if (isa<UndefValue>(Op1)) // X & undef -> 0
1717 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1718
Chris Lattner86102b82005-01-01 16:22:27 +00001719 // and X, X = X
1720 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001721 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001722
Chris Lattner86102b82005-01-01 16:22:27 +00001723 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001724 // and X, -1 == X
1725 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001726 return ReplaceInstUsesWith(I, Op0);
Chris Lattner38a1b002005-10-26 17:18:16 +00001727
1728 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1729 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1730 // through many levels of ands.
1731 {
1732 Value *X; ConstantInt *C1;
1733 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1734 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1735 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001736
Chris Lattner86102b82005-01-01 16:22:27 +00001737 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1738 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1739
1740 // If the mask is not masking out any bits, there is no reason to do the
1741 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001742 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001743 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001744 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001745 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001746
Chris Lattnerba1cb382003-09-19 17:17:26 +00001747 // Optimize a variety of ((val OP C1) & C2) combinations...
1748 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1749 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001750 Value *Op0LHS = Op0I->getOperand(0);
1751 Value *Op0RHS = Op0I->getOperand(1);
1752 switch (Op0I->getOpcode()) {
1753 case Instruction::Xor:
1754 case Instruction::Or:
1755 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1756 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1757 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001758 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001759 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001760 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001761
1762 // If the mask is only needed on one incoming arm, push it up.
1763 if (Op0I->hasOneUse()) {
1764 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1765 // Not masking anything out for the LHS, move to RHS.
1766 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1767 Op0RHS->getName()+".masked");
1768 InsertNewInstBefore(NewRHS, I);
1769 return BinaryOperator::create(
1770 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001771 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001772 if (!isa<Constant>(NotAndRHS) &&
1773 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1774 // Not masking anything out for the RHS, move to LHS.
1775 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1776 Op0LHS->getName()+".masked");
1777 InsertNewInstBefore(NewLHS, I);
1778 return BinaryOperator::create(
1779 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1780 }
1781 }
1782
Chris Lattner86102b82005-01-01 16:22:27 +00001783 break;
1784 case Instruction::And:
1785 // (X & V) & C2 --> 0 iff (V & C2) == 0
1786 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1787 MaskedValueIsZero(Op0RHS, AndRHS))
1788 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1789 break;
Chris Lattneraf517572005-09-18 04:24:45 +00001790 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001791 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1792 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1793 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1794 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1795 return BinaryOperator::createAnd(V, AndRHS);
1796 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1797 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00001798 break;
1799
1800 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001801 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1802 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1803 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1804 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1805 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00001806 break;
Chris Lattner86102b82005-01-01 16:22:27 +00001807 }
1808
Chris Lattner16464b32003-07-23 19:25:52 +00001809 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001810 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001811 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001812 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1813 const Type *SrcTy = CI->getOperand(0)->getType();
1814
Chris Lattner2c14cf72005-08-07 07:03:10 +00001815 // If this is an integer truncation or change from signed-to-unsigned, and
1816 // if the source is an and/or with immediate, transform it. This
1817 // frequently occurs for bitfield accesses.
1818 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1819 if (SrcTy->getPrimitiveSizeInBits() >=
1820 I.getType()->getPrimitiveSizeInBits() &&
1821 CastOp->getNumOperands() == 2)
1822 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1823 if (CastOp->getOpcode() == Instruction::And) {
1824 // Change: and (cast (and X, C1) to T), C2
1825 // into : and (cast X to T), trunc(C1)&C2
1826 // This will folds the two ands together, which may allow other
1827 // simplifications.
1828 Instruction *NewCast =
1829 new CastInst(CastOp->getOperand(0), I.getType(),
1830 CastOp->getName()+".shrunk");
1831 NewCast = InsertNewInstBefore(NewCast, I);
1832
1833 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1834 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1835 return BinaryOperator::createAnd(NewCast, C3);
1836 } else if (CastOp->getOpcode() == Instruction::Or) {
1837 // Change: and (cast (or X, C1) to T), C2
1838 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1839 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1840 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1841 return ReplaceInstUsesWith(I, AndRHS);
1842 }
1843 }
1844
1845
Chris Lattner86102b82005-01-01 16:22:27 +00001846 // If this is an integer sign or zero extension instruction.
1847 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001848 SrcTy->getPrimitiveSizeInBits() <
1849 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001850
1851 if (SrcTy->isUnsigned()) {
1852 // See if this and is clearing out bits that are known to be zero
1853 // anyway (due to the zero extension).
1854 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1855 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1856 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1857 if (Result == Mask) // The "and" isn't doing anything, remove it.
1858 return ReplaceInstUsesWith(I, CI);
1859 if (Result != AndRHS) { // Reduce the and RHS constant.
1860 I.setOperand(1, Result);
1861 return &I;
1862 }
1863
1864 } else {
1865 if (CI->hasOneUse() && SrcTy->isInteger()) {
1866 // We can only do this if all of the sign bits brought in are masked
1867 // out. Compute this by first getting 0000011111, then inverting
1868 // it.
1869 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1870 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1871 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1872 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1873 // If the and is clearing all of the sign bits, change this to a
1874 // zero extension cast. To do this, cast the cast input to
1875 // unsigned, then to the requested size.
1876 Value *CastOp = CI->getOperand(0);
1877 Instruction *NC =
1878 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1879 CI->getName()+".uns");
1880 NC = InsertNewInstBefore(NC, I);
1881 // Finally, insert a replacement for CI.
1882 NC = new CastInst(NC, CI->getType(), CI->getName());
1883 CI->setName("");
1884 NC = InsertNewInstBefore(NC, I);
1885 WorkList.push_back(CI); // Delete CI later.
1886 I.setOperand(0, NC);
1887 return &I; // The AND operand was modified.
1888 }
1889 }
1890 }
1891 }
Chris Lattner33217db2003-07-23 19:36:21 +00001892 }
Chris Lattner183b3362004-04-09 19:05:30 +00001893
1894 // Try to fold constant and into select arguments.
1895 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001896 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001897 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001898 if (isa<PHINode>(Op0))
1899 if (Instruction *NV = FoldOpIntoPhi(I))
1900 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001901 }
1902
Chris Lattnerbb74e222003-03-10 23:06:50 +00001903 Value *Op0NotVal = dyn_castNotVal(Op0);
1904 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001905
Chris Lattner023a4832004-06-18 06:07:51 +00001906 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1907 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1908
Misha Brukman9c003d82004-07-30 12:50:08 +00001909 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001910 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001911 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1912 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001913 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001914 return BinaryOperator::createNot(Or);
1915 }
1916
Chris Lattner623826c2004-09-28 21:48:02 +00001917 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1918 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001919 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1920 return R;
1921
Chris Lattner623826c2004-09-28 21:48:02 +00001922 Value *LHSVal, *RHSVal;
1923 ConstantInt *LHSCst, *RHSCst;
1924 Instruction::BinaryOps LHSCC, RHSCC;
1925 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1926 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1927 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1928 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001929 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001930 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1931 // Ensure that the larger constant is on the RHS.
1932 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1933 SetCondInst *LHS = cast<SetCondInst>(Op0);
1934 if (cast<ConstantBool>(Cmp)->getValue()) {
1935 std::swap(LHS, RHS);
1936 std::swap(LHSCst, RHSCst);
1937 std::swap(LHSCC, RHSCC);
1938 }
1939
1940 // At this point, we know we have have two setcc instructions
1941 // comparing a value against two constants and and'ing the result
1942 // together. Because of the above check, we know that we only have
1943 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1944 // FoldSetCCLogical check above), that the two constants are not
1945 // equal.
1946 assert(LHSCst != RHSCst && "Compares not folded above?");
1947
1948 switch (LHSCC) {
1949 default: assert(0 && "Unknown integer condition code!");
1950 case Instruction::SetEQ:
1951 switch (RHSCC) {
1952 default: assert(0 && "Unknown integer condition code!");
1953 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1954 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1955 return ReplaceInstUsesWith(I, ConstantBool::False);
1956 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1957 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1958 return ReplaceInstUsesWith(I, LHS);
1959 }
1960 case Instruction::SetNE:
1961 switch (RHSCC) {
1962 default: assert(0 && "Unknown integer condition code!");
1963 case Instruction::SetLT:
1964 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1965 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1966 break; // (X != 13 & X < 15) -> no change
1967 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1968 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1969 return ReplaceInstUsesWith(I, RHS);
1970 case Instruction::SetNE:
1971 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1972 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1973 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1974 LHSVal->getName()+".off");
1975 InsertNewInstBefore(Add, I);
1976 const Type *UnsType = Add->getType()->getUnsignedVersion();
1977 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1978 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1979 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1980 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1981 }
1982 break; // (X != 13 & X != 15) -> no change
1983 }
1984 break;
1985 case Instruction::SetLT:
1986 switch (RHSCC) {
1987 default: assert(0 && "Unknown integer condition code!");
1988 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1989 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1990 return ReplaceInstUsesWith(I, ConstantBool::False);
1991 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1992 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1993 return ReplaceInstUsesWith(I, LHS);
1994 }
1995 case Instruction::SetGT:
1996 switch (RHSCC) {
1997 default: assert(0 && "Unknown integer condition code!");
1998 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1999 return ReplaceInstUsesWith(I, LHS);
2000 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2001 return ReplaceInstUsesWith(I, RHS);
2002 case Instruction::SetNE:
2003 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2004 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2005 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002006 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2007 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002008 }
2009 }
2010 }
2011 }
2012
Chris Lattner113f4f42002-06-25 16:13:24 +00002013 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002014}
2015
Chris Lattner113f4f42002-06-25 16:13:24 +00002016Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002017 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002018 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002019
Chris Lattner81a7a232004-10-16 18:11:37 +00002020 if (isa<UndefValue>(Op1))
2021 return ReplaceInstUsesWith(I, // X | undef -> -1
2022 ConstantIntegral::getAllOnesValue(I.getType()));
2023
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002024 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002025 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2026 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002027
2028 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002029 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002030 // If X is known to only contain bits that already exist in RHS, just
2031 // replace this instruction with RHS directly.
2032 if (MaskedValueIsZero(Op0,
2033 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2034 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002035
Chris Lattnerd4252a72004-07-30 07:50:03 +00002036 ConstantInt *C1; Value *X;
2037 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2038 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002039 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2040 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002041 InsertNewInstBefore(Or, I);
2042 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2043 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002044
Chris Lattnerd4252a72004-07-30 07:50:03 +00002045 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2046 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2047 std::string Op0Name = Op0->getName(); Op0->setName("");
2048 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2049 InsertNewInstBefore(Or, I);
2050 return BinaryOperator::createXor(Or,
2051 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002052 }
Chris Lattner183b3362004-04-09 19:05:30 +00002053
2054 // Try to fold constant and into select arguments.
2055 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002056 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002057 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002058 if (isa<PHINode>(Op0))
2059 if (Instruction *NV = FoldOpIntoPhi(I))
2060 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002061 }
2062
Chris Lattnerd4252a72004-07-30 07:50:03 +00002063 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattner4294cec2005-05-07 23:49:08 +00002064
2065 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2066 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2067 return ReplaceInstUsesWith(I, Op1);
2068 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2069 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2070 return ReplaceInstUsesWith(I, Op0);
2071
Chris Lattnerb62f5082005-05-09 04:58:36 +00002072 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2073 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2074 MaskedValueIsZero(Op1, C1)) {
2075 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2076 Op0->setName("");
2077 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2078 }
2079
2080 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2081 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2082 MaskedValueIsZero(Op0, C1)) {
2083 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2084 Op0->setName("");
2085 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2086 }
2087
Chris Lattner15212982005-09-18 03:42:07 +00002088 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002089 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002090 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2091
2092 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2093 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2094
2095
Chris Lattner01f56c62005-09-18 06:02:59 +00002096 // If we have: ((V + N) & C1) | (V & C2)
2097 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2098 // replace with V+N.
2099 if (C1 == ConstantExpr::getNot(C2)) {
2100 Value *V1, *V2;
2101 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2102 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2103 // Add commutes, try both ways.
2104 if (V1 == B && MaskedValueIsZero(V2, C2))
2105 return ReplaceInstUsesWith(I, A);
2106 if (V2 == B && MaskedValueIsZero(V1, C2))
2107 return ReplaceInstUsesWith(I, A);
2108 }
2109 // Or commutes, try both ways.
2110 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2111 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2112 // Add commutes, try both ways.
2113 if (V1 == A && MaskedValueIsZero(V2, C1))
2114 return ReplaceInstUsesWith(I, B);
2115 if (V2 == A && MaskedValueIsZero(V1, C1))
2116 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002117 }
2118 }
2119 }
Chris Lattner812aab72003-08-12 19:11:07 +00002120
Chris Lattnerd4252a72004-07-30 07:50:03 +00002121 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2122 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002123 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002124 ConstantIntegral::getAllOnesValue(I.getType()));
2125 } else {
2126 A = 0;
2127 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002128 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002129 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2130 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002131 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002132 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002133
Misha Brukman9c003d82004-07-30 12:50:08 +00002134 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002135 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2136 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2137 I.getName()+".demorgan"), I);
2138 return BinaryOperator::createNot(And);
2139 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002140 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002141
Chris Lattner3ac7c262003-08-13 20:16:26 +00002142 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002143 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002144 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2145 return R;
2146
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002147 Value *LHSVal, *RHSVal;
2148 ConstantInt *LHSCst, *RHSCst;
2149 Instruction::BinaryOps LHSCC, RHSCC;
2150 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2151 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2152 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2153 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002154 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002155 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2156 // Ensure that the larger constant is on the RHS.
2157 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2158 SetCondInst *LHS = cast<SetCondInst>(Op0);
2159 if (cast<ConstantBool>(Cmp)->getValue()) {
2160 std::swap(LHS, RHS);
2161 std::swap(LHSCst, RHSCst);
2162 std::swap(LHSCC, RHSCC);
2163 }
2164
2165 // At this point, we know we have have two setcc instructions
2166 // comparing a value against two constants and or'ing the result
2167 // together. Because of the above check, we know that we only have
2168 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2169 // FoldSetCCLogical check above), that the two constants are not
2170 // equal.
2171 assert(LHSCst != RHSCst && "Compares not folded above?");
2172
2173 switch (LHSCC) {
2174 default: assert(0 && "Unknown integer condition code!");
2175 case Instruction::SetEQ:
2176 switch (RHSCC) {
2177 default: assert(0 && "Unknown integer condition code!");
2178 case Instruction::SetEQ:
2179 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2180 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2181 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2182 LHSVal->getName()+".off");
2183 InsertNewInstBefore(Add, I);
2184 const Type *UnsType = Add->getType()->getUnsignedVersion();
2185 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2186 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2187 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2188 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2189 }
2190 break; // (X == 13 | X == 15) -> no change
2191
Chris Lattner5c219462005-04-19 06:04:18 +00002192 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2193 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002194 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2195 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2196 return ReplaceInstUsesWith(I, RHS);
2197 }
2198 break;
2199 case Instruction::SetNE:
2200 switch (RHSCC) {
2201 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002202 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2203 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2204 return ReplaceInstUsesWith(I, LHS);
2205 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002206 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002207 return ReplaceInstUsesWith(I, ConstantBool::True);
2208 }
2209 break;
2210 case Instruction::SetLT:
2211 switch (RHSCC) {
2212 default: assert(0 && "Unknown integer condition code!");
2213 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2214 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002215 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2216 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002217 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2218 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2219 return ReplaceInstUsesWith(I, RHS);
2220 }
2221 break;
2222 case Instruction::SetGT:
2223 switch (RHSCC) {
2224 default: assert(0 && "Unknown integer condition code!");
2225 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2226 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2227 return ReplaceInstUsesWith(I, LHS);
2228 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2229 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2230 return ReplaceInstUsesWith(I, ConstantBool::True);
2231 }
2232 }
2233 }
2234 }
Chris Lattner15212982005-09-18 03:42:07 +00002235
Chris Lattner113f4f42002-06-25 16:13:24 +00002236 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002237}
2238
Chris Lattnerc2076352004-02-16 01:20:27 +00002239// XorSelf - Implements: X ^ X --> 0
2240struct XorSelf {
2241 Value *RHS;
2242 XorSelf(Value *rhs) : RHS(rhs) {}
2243 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2244 Instruction *apply(BinaryOperator &Xor) const {
2245 return &Xor;
2246 }
2247};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002248
2249
Chris Lattner113f4f42002-06-25 16:13:24 +00002250Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002251 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002252 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002253
Chris Lattner81a7a232004-10-16 18:11:37 +00002254 if (isa<UndefValue>(Op1))
2255 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2256
Chris Lattnerc2076352004-02-16 01:20:27 +00002257 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2258 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2259 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002260 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002261 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002262
Chris Lattner97638592003-07-23 21:37:07 +00002263 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002264 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002265 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002266 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002267
Chris Lattner97638592003-07-23 21:37:07 +00002268 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002269 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002270 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002271 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002272 return new SetCondInst(SCI->getInverseCondition(),
2273 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002274
Chris Lattner8f2f5982003-11-05 01:06:05 +00002275 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002276 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2277 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002278 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2279 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002280 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002281 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002282 }
Chris Lattner023a4832004-06-18 06:07:51 +00002283
2284 // ~(~X & Y) --> (X | ~Y)
2285 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2286 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2287 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2288 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002289 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002290 Op0I->getOperand(1)->getName()+".not");
2291 InsertNewInstBefore(NotY, I);
2292 return BinaryOperator::createOr(Op0NotVal, NotY);
2293 }
2294 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002295
Chris Lattner97638592003-07-23 21:37:07 +00002296 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002297 switch (Op0I->getOpcode()) {
2298 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002299 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002300 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002301 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2302 return BinaryOperator::createSub(
2303 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002304 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002305 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002306 }
Chris Lattnere5806662003-11-04 23:50:51 +00002307 break;
2308 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002309 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002310 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2311 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002312 break;
2313 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002314 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002315 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002316 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002317 break;
2318 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002319 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002320 }
Chris Lattner183b3362004-04-09 19:05:30 +00002321
2322 // Try to fold constant and into select arguments.
2323 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002324 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002325 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002326 if (isa<PHINode>(Op0))
2327 if (Instruction *NV = FoldOpIntoPhi(I))
2328 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002329 }
2330
Chris Lattnerbb74e222003-03-10 23:06:50 +00002331 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002332 if (X == Op1)
2333 return ReplaceInstUsesWith(I,
2334 ConstantIntegral::getAllOnesValue(I.getType()));
2335
Chris Lattnerbb74e222003-03-10 23:06:50 +00002336 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002337 if (X == Op0)
2338 return ReplaceInstUsesWith(I,
2339 ConstantIntegral::getAllOnesValue(I.getType()));
2340
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002341 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002342 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002343 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2344 cast<BinaryOperator>(Op1I)->swapOperands();
2345 I.swapOperands();
2346 std::swap(Op0, Op1);
2347 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2348 I.swapOperands();
2349 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002350 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002351 } else if (Op1I->getOpcode() == Instruction::Xor) {
2352 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2353 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2354 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2355 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2356 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002357
2358 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002359 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002360 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2361 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002362 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002363 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2364 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002365 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002366 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002367 } else if (Op0I->getOpcode() == Instruction::Xor) {
2368 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2369 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2370 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2371 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002372 }
2373
Chris Lattner7aa2d472004-08-01 19:42:59 +00002374 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002375 Value *A, *B; ConstantInt *C1, *C2;
2376 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2377 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002378 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002379 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002380
Chris Lattner3ac7c262003-08-13 20:16:26 +00002381 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2382 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2383 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2384 return R;
2385
Chris Lattner113f4f42002-06-25 16:13:24 +00002386 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002387}
2388
Chris Lattner6862fbd2004-09-29 17:40:11 +00002389/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2390/// overflowed for this type.
2391static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2392 ConstantInt *In2) {
2393 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2394 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2395}
2396
2397static bool isPositive(ConstantInt *C) {
2398 return cast<ConstantSInt>(C)->getValue() >= 0;
2399}
2400
2401/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2402/// overflowed for this type.
2403static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2404 ConstantInt *In2) {
2405 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2406
2407 if (In1->getType()->isUnsigned())
2408 return cast<ConstantUInt>(Result)->getValue() <
2409 cast<ConstantUInt>(In1)->getValue();
2410 if (isPositive(In1) != isPositive(In2))
2411 return false;
2412 if (isPositive(In1))
2413 return cast<ConstantSInt>(Result)->getValue() <
2414 cast<ConstantSInt>(In1)->getValue();
2415 return cast<ConstantSInt>(Result)->getValue() >
2416 cast<ConstantSInt>(In1)->getValue();
2417}
2418
Chris Lattner0798af32005-01-13 20:14:25 +00002419/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2420/// code necessary to compute the offset from the base pointer (without adding
2421/// in the base pointer). Return the result as a signed integer of intptr size.
2422static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2423 TargetData &TD = IC.getTargetData();
2424 gep_type_iterator GTI = gep_type_begin(GEP);
2425 const Type *UIntPtrTy = TD.getIntPtrType();
2426 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2427 Value *Result = Constant::getNullValue(SIntPtrTy);
2428
2429 // Build a mask for high order bits.
2430 uint64_t PtrSizeMask = ~0ULL;
2431 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2432
Chris Lattner0798af32005-01-13 20:14:25 +00002433 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2434 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002435 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002436 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2437 SIntPtrTy);
2438 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2439 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002440 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002441 Scale = ConstantExpr::getMul(OpC, Scale);
2442 if (Constant *RC = dyn_cast<Constant>(Result))
2443 Result = ConstantExpr::getAdd(RC, Scale);
2444 else {
2445 // Emit an add instruction.
2446 Result = IC.InsertNewInstBefore(
2447 BinaryOperator::createAdd(Result, Scale,
2448 GEP->getName()+".offs"), I);
2449 }
2450 }
2451 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002452 // Convert to correct type.
2453 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2454 Op->getName()+".c"), I);
2455 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002456 // We'll let instcombine(mul) convert this to a shl if possible.
2457 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2458 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002459
2460 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002461 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002462 GEP->getName()+".offs"), I);
2463 }
2464 }
2465 return Result;
2466}
2467
2468/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2469/// else. At this point we know that the GEP is on the LHS of the comparison.
2470Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2471 Instruction::BinaryOps Cond,
2472 Instruction &I) {
2473 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002474
2475 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2476 if (isa<PointerType>(CI->getOperand(0)->getType()))
2477 RHS = CI->getOperand(0);
2478
Chris Lattner0798af32005-01-13 20:14:25 +00002479 Value *PtrBase = GEPLHS->getOperand(0);
2480 if (PtrBase == RHS) {
2481 // As an optimization, we don't actually have to compute the actual value of
2482 // OFFSET if this is a seteq or setne comparison, just return whether each
2483 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002484 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2485 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002486 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2487 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002488 bool EmitIt = true;
2489 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2490 if (isa<UndefValue>(C)) // undef index -> undef.
2491 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2492 if (C->isNullValue())
2493 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002494 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2495 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002496 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002497 return ReplaceInstUsesWith(I, // No comparison is needed here.
2498 ConstantBool::get(Cond == Instruction::SetNE));
2499 }
2500
2501 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002502 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002503 new SetCondInst(Cond, GEPLHS->getOperand(i),
2504 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2505 if (InVal == 0)
2506 InVal = Comp;
2507 else {
2508 InVal = InsertNewInstBefore(InVal, I);
2509 InsertNewInstBefore(Comp, I);
2510 if (Cond == Instruction::SetNE) // True if any are unequal
2511 InVal = BinaryOperator::createOr(InVal, Comp);
2512 else // True if all are equal
2513 InVal = BinaryOperator::createAnd(InVal, Comp);
2514 }
2515 }
2516 }
2517
2518 if (InVal)
2519 return InVal;
2520 else
2521 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2522 ConstantBool::get(Cond == Instruction::SetEQ));
2523 }
Chris Lattner0798af32005-01-13 20:14:25 +00002524
2525 // Only lower this if the setcc is the only user of the GEP or if we expect
2526 // the result to fold to a constant!
2527 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2528 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2529 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2530 return new SetCondInst(Cond, Offset,
2531 Constant::getNullValue(Offset->getType()));
2532 }
2533 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002534 // If the base pointers are different, but the indices are the same, just
2535 // compare the base pointer.
2536 if (PtrBase != GEPRHS->getOperand(0)) {
2537 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002538 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002539 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002540 if (IndicesTheSame)
2541 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2542 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2543 IndicesTheSame = false;
2544 break;
2545 }
2546
2547 // If all indices are the same, just compare the base pointers.
2548 if (IndicesTheSame)
2549 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2550 GEPRHS->getOperand(0));
2551
2552 // Otherwise, the base pointers are different and the indices are
2553 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002554 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002555 }
Chris Lattner0798af32005-01-13 20:14:25 +00002556
Chris Lattner81e84172005-01-13 22:25:21 +00002557 // If one of the GEPs has all zero indices, recurse.
2558 bool AllZeros = true;
2559 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2560 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2561 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2562 AllZeros = false;
2563 break;
2564 }
2565 if (AllZeros)
2566 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2567 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002568
2569 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002570 AllZeros = true;
2571 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2572 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2573 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2574 AllZeros = false;
2575 break;
2576 }
2577 if (AllZeros)
2578 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2579
Chris Lattner4fa89822005-01-14 00:20:05 +00002580 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2581 // If the GEPs only differ by one index, compare it.
2582 unsigned NumDifferences = 0; // Keep track of # differences.
2583 unsigned DiffOperand = 0; // The operand that differs.
2584 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2585 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002586 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2587 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002588 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002589 NumDifferences = 2;
2590 break;
2591 } else {
2592 if (NumDifferences++) break;
2593 DiffOperand = i;
2594 }
2595 }
2596
2597 if (NumDifferences == 0) // SAME GEP?
2598 return ReplaceInstUsesWith(I, // No comparison is needed here.
2599 ConstantBool::get(Cond == Instruction::SetEQ));
2600 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002601 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2602 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002603
2604 // Convert the operands to signed values to make sure to perform a
2605 // signed comparison.
2606 const Type *NewTy = LHSV->getType()->getSignedVersion();
2607 if (LHSV->getType() != NewTy)
2608 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2609 LHSV->getName()), I);
2610 if (RHSV->getType() != NewTy)
2611 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2612 RHSV->getName()), I);
2613 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002614 }
2615 }
2616
Chris Lattner0798af32005-01-13 20:14:25 +00002617 // Only lower this if the setcc is the only user of the GEP or if we expect
2618 // the result to fold to a constant!
2619 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2620 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2621 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2622 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2623 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2624 return new SetCondInst(Cond, L, R);
2625 }
2626 }
2627 return 0;
2628}
2629
2630
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002631Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002632 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002633 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2634 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002635
2636 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002637 if (Op0 == Op1)
2638 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002639
Chris Lattner81a7a232004-10-16 18:11:37 +00002640 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2641 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2642
Chris Lattner15ff1e12004-11-14 07:33:16 +00002643 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2644 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002645 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2646 isa<ConstantPointerNull>(Op0)) &&
2647 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002648 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002649 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2650
2651 // setcc's with boolean values can always be turned into bitwise operations
2652 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002653 switch (I.getOpcode()) {
2654 default: assert(0 && "Invalid setcc instruction!");
2655 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002656 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002657 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002658 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002659 }
Chris Lattner4456da62004-08-11 00:50:51 +00002660 case Instruction::SetNE:
2661 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002662
Chris Lattner4456da62004-08-11 00:50:51 +00002663 case Instruction::SetGT:
2664 std::swap(Op0, Op1); // Change setgt -> setlt
2665 // FALL THROUGH
2666 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2667 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2668 InsertNewInstBefore(Not, I);
2669 return BinaryOperator::createAnd(Not, Op1);
2670 }
2671 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002672 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002673 // FALL THROUGH
2674 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2675 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2676 InsertNewInstBefore(Not, I);
2677 return BinaryOperator::createOr(Not, Op1);
2678 }
2679 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002680 }
2681
Chris Lattner2dd01742004-06-09 04:24:29 +00002682 // See if we are doing a comparison between a constant and an instruction that
2683 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002684 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002685 // Check to see if we are comparing against the minimum or maximum value...
2686 if (CI->isMinValue()) {
2687 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2688 return ReplaceInstUsesWith(I, ConstantBool::False);
2689 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2690 return ReplaceInstUsesWith(I, ConstantBool::True);
2691 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2692 return BinaryOperator::createSetEQ(Op0, Op1);
2693 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2694 return BinaryOperator::createSetNE(Op0, Op1);
2695
2696 } else if (CI->isMaxValue()) {
2697 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2698 return ReplaceInstUsesWith(I, ConstantBool::False);
2699 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2700 return ReplaceInstUsesWith(I, ConstantBool::True);
2701 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2702 return BinaryOperator::createSetEQ(Op0, Op1);
2703 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2704 return BinaryOperator::createSetNE(Op0, Op1);
2705
2706 // Comparing against a value really close to min or max?
2707 } else if (isMinValuePlusOne(CI)) {
2708 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2709 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2710 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2711 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2712
2713 } else if (isMaxValueMinusOne(CI)) {
2714 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2715 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2716 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2717 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2718 }
2719
2720 // If we still have a setle or setge instruction, turn it into the
2721 // appropriate setlt or setgt instruction. Since the border cases have
2722 // already been handled above, this requires little checking.
2723 //
2724 if (I.getOpcode() == Instruction::SetLE)
2725 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2726 if (I.getOpcode() == Instruction::SetGE)
2727 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2728
Chris Lattnere1e10e12004-05-25 06:32:08 +00002729 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002730 switch (LHSI->getOpcode()) {
2731 case Instruction::And:
2732 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2733 LHSI->getOperand(0)->hasOneUse()) {
2734 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2735 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2736 // happens a LOT in code produced by the C front-end, for bitfield
2737 // access.
2738 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2739 ConstantUInt *ShAmt;
2740 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2741 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2742 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002743
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002744 // We can fold this as long as we can't shift unknown bits
2745 // into the mask. This can only happen with signed shift
2746 // rights, as they sign-extend.
2747 if (ShAmt) {
2748 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002749 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002750 if (!CanFold) {
2751 // To test for the bad case of the signed shr, see if any
2752 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002753 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2754 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2755
2756 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002757 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002758 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2759 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2760 CanFold = true;
2761 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002762
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002763 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002764 Constant *NewCst;
2765 if (Shift->getOpcode() == Instruction::Shl)
2766 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2767 else
2768 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002769
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002770 // Check to see if we are shifting out any of the bits being
2771 // compared.
2772 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2773 // If we shifted bits out, the fold is not going to work out.
2774 // As a special case, check to see if this means that the
2775 // result is always true or false now.
2776 if (I.getOpcode() == Instruction::SetEQ)
2777 return ReplaceInstUsesWith(I, ConstantBool::False);
2778 if (I.getOpcode() == Instruction::SetNE)
2779 return ReplaceInstUsesWith(I, ConstantBool::True);
2780 } else {
2781 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002782 Constant *NewAndCST;
2783 if (Shift->getOpcode() == Instruction::Shl)
2784 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2785 else
2786 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2787 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002788 LHSI->setOperand(0, Shift->getOperand(0));
2789 WorkList.push_back(Shift); // Shift is dead.
2790 AddUsesToWorkList(I);
2791 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002792 }
2793 }
Chris Lattner35167c32004-06-09 07:59:58 +00002794 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002795 }
2796 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002797
Chris Lattner272d5ca2004-09-28 18:22:15 +00002798 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2799 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2800 switch (I.getOpcode()) {
2801 default: break;
2802 case Instruction::SetEQ:
2803 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002804 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2805
2806 // Check that the shift amount is in range. If not, don't perform
2807 // undefined shifts. When the shift is visited it will be
2808 // simplified.
2809 if (ShAmt->getValue() >= TypeBits)
2810 break;
2811
Chris Lattner272d5ca2004-09-28 18:22:15 +00002812 // If we are comparing against bits always shifted out, the
2813 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002814 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002815 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2816 if (Comp != CI) {// Comparing against a bit that we know is zero.
2817 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2818 Constant *Cst = ConstantBool::get(IsSetNE);
2819 return ReplaceInstUsesWith(I, Cst);
2820 }
2821
2822 if (LHSI->hasOneUse()) {
2823 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002824 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002825 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2826
2827 Constant *Mask;
2828 if (CI->getType()->isUnsigned()) {
2829 Mask = ConstantUInt::get(CI->getType(), Val);
2830 } else if (ShAmtVal != 0) {
2831 Mask = ConstantSInt::get(CI->getType(), Val);
2832 } else {
2833 Mask = ConstantInt::getAllOnesValue(CI->getType());
2834 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002835
Chris Lattner272d5ca2004-09-28 18:22:15 +00002836 Instruction *AndI =
2837 BinaryOperator::createAnd(LHSI->getOperand(0),
2838 Mask, LHSI->getName()+".mask");
2839 Value *And = InsertNewInstBefore(AndI, I);
2840 return new SetCondInst(I.getOpcode(), And,
2841 ConstantExpr::getUShr(CI, ShAmt));
2842 }
2843 }
2844 }
2845 }
2846 break;
2847
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002848 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002849 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002850 switch (I.getOpcode()) {
2851 default: break;
2852 case Instruction::SetEQ:
2853 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002854
2855 // Check that the shift amount is in range. If not, don't perform
2856 // undefined shifts. When the shift is visited it will be
2857 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002858 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002859 if (ShAmt->getValue() >= TypeBits)
2860 break;
2861
Chris Lattner1023b872004-09-27 16:18:50 +00002862 // If we are comparing against bits always shifted out, the
2863 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002864 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002865 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002866
Chris Lattner1023b872004-09-27 16:18:50 +00002867 if (Comp != CI) {// Comparing against a bit that we know is zero.
2868 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2869 Constant *Cst = ConstantBool::get(IsSetNE);
2870 return ReplaceInstUsesWith(I, Cst);
2871 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002872
Chris Lattner1023b872004-09-27 16:18:50 +00002873 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002874 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002875
Chris Lattner1023b872004-09-27 16:18:50 +00002876 // Otherwise strength reduce the shift into an and.
2877 uint64_t Val = ~0ULL; // All ones.
2878 Val <<= ShAmtVal; // Shift over to the right spot.
2879
2880 Constant *Mask;
2881 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002882 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002883 Mask = ConstantUInt::get(CI->getType(), Val);
2884 } else {
2885 Mask = ConstantSInt::get(CI->getType(), Val);
2886 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002887
Chris Lattner1023b872004-09-27 16:18:50 +00002888 Instruction *AndI =
2889 BinaryOperator::createAnd(LHSI->getOperand(0),
2890 Mask, LHSI->getName()+".mask");
2891 Value *And = InsertNewInstBefore(AndI, I);
2892 return new SetCondInst(I.getOpcode(), And,
2893 ConstantExpr::getShl(CI, ShAmt));
2894 }
2895 break;
2896 }
2897 }
2898 }
2899 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002900
Chris Lattner6862fbd2004-09-29 17:40:11 +00002901 case Instruction::Div:
2902 // Fold: (div X, C1) op C2 -> range check
2903 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2904 // Fold this div into the comparison, producing a range check.
2905 // Determine, based on the divide type, what the range is being
2906 // checked. If there is an overflow on the low or high side, remember
2907 // it, otherwise compute the range [low, hi) bounding the new value.
2908 bool LoOverflow = false, HiOverflow = 0;
2909 ConstantInt *LoBound = 0, *HiBound = 0;
2910
2911 ConstantInt *Prod;
2912 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2913
Chris Lattnera92af962004-10-11 19:40:04 +00002914 Instruction::BinaryOps Opcode = I.getOpcode();
2915
Chris Lattner6862fbd2004-09-29 17:40:11 +00002916 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2917 } else if (LHSI->getType()->isUnsigned()) { // udiv
2918 LoBound = Prod;
2919 LoOverflow = ProdOV;
2920 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2921 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2922 if (CI->isNullValue()) { // (X / pos) op 0
2923 // Can't overflow.
2924 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2925 HiBound = DivRHS;
2926 } else if (isPositive(CI)) { // (X / pos) op pos
2927 LoBound = Prod;
2928 LoOverflow = ProdOV;
2929 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2930 } else { // (X / pos) op neg
2931 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2932 LoOverflow = AddWithOverflow(LoBound, Prod,
2933 cast<ConstantInt>(DivRHSH));
2934 HiBound = Prod;
2935 HiOverflow = ProdOV;
2936 }
2937 } else { // Divisor is < 0.
2938 if (CI->isNullValue()) { // (X / neg) op 0
2939 LoBound = AddOne(DivRHS);
2940 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002941 if (HiBound == DivRHS)
2942 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002943 } else if (isPositive(CI)) { // (X / neg) op pos
2944 HiOverflow = LoOverflow = ProdOV;
2945 if (!LoOverflow)
2946 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2947 HiBound = AddOne(Prod);
2948 } else { // (X / neg) op neg
2949 LoBound = Prod;
2950 LoOverflow = HiOverflow = ProdOV;
2951 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2952 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002953
Chris Lattnera92af962004-10-11 19:40:04 +00002954 // Dividing by a negate swaps the condition.
2955 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002956 }
2957
2958 if (LoBound) {
2959 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002960 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002961 default: assert(0 && "Unhandled setcc opcode!");
2962 case Instruction::SetEQ:
2963 if (LoOverflow && HiOverflow)
2964 return ReplaceInstUsesWith(I, ConstantBool::False);
2965 else if (HiOverflow)
2966 return new SetCondInst(Instruction::SetGE, X, LoBound);
2967 else if (LoOverflow)
2968 return new SetCondInst(Instruction::SetLT, X, HiBound);
2969 else
2970 return InsertRangeTest(X, LoBound, HiBound, true, I);
2971 case Instruction::SetNE:
2972 if (LoOverflow && HiOverflow)
2973 return ReplaceInstUsesWith(I, ConstantBool::True);
2974 else if (HiOverflow)
2975 return new SetCondInst(Instruction::SetLT, X, LoBound);
2976 else if (LoOverflow)
2977 return new SetCondInst(Instruction::SetGE, X, HiBound);
2978 else
2979 return InsertRangeTest(X, LoBound, HiBound, false, I);
2980 case Instruction::SetLT:
2981 if (LoOverflow)
2982 return ReplaceInstUsesWith(I, ConstantBool::False);
2983 return new SetCondInst(Instruction::SetLT, X, LoBound);
2984 case Instruction::SetGT:
2985 if (HiOverflow)
2986 return ReplaceInstUsesWith(I, ConstantBool::False);
2987 return new SetCondInst(Instruction::SetGE, X, HiBound);
2988 }
2989 }
2990 }
2991 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002992 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002993
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002994 // Simplify seteq and setne instructions...
2995 if (I.getOpcode() == Instruction::SetEQ ||
2996 I.getOpcode() == Instruction::SetNE) {
2997 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2998
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002999 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003000 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003001 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3002 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003003 case Instruction::Rem:
3004 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3005 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3006 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003007 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3008 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3009 if (isPowerOf2_64(V)) {
3010 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003011 const Type *UTy = BO->getType()->getUnsignedVersion();
3012 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3013 UTy, "tmp"), I);
3014 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3015 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3016 RHSCst, BO->getName()), I);
3017 return BinaryOperator::create(I.getOpcode(), NewRem,
3018 Constant::getNullValue(UTy));
3019 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003020 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003021 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003022
Chris Lattnerc992add2003-08-13 05:33:12 +00003023 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003024 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3025 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003026 if (BO->hasOneUse())
3027 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3028 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003029 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003030 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3031 // efficiently invertible, or if the add has just this one use.
3032 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003033
Chris Lattnerc992add2003-08-13 05:33:12 +00003034 if (Value *NegVal = dyn_castNegVal(BOp1))
3035 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3036 else if (Value *NegVal = dyn_castNegVal(BOp0))
3037 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003038 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003039 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3040 BO->setName("");
3041 InsertNewInstBefore(Neg, I);
3042 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3043 }
3044 }
3045 break;
3046 case Instruction::Xor:
3047 // For the xor case, we can xor two constants together, eliminating
3048 // the explicit xor.
3049 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3050 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003051 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003052
3053 // FALLTHROUGH
3054 case Instruction::Sub:
3055 // Replace (([sub|xor] A, B) != 0) with (A != B)
3056 if (CI->isNullValue())
3057 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3058 BO->getOperand(1));
3059 break;
3060
3061 case Instruction::Or:
3062 // If bits are being or'd in that are not present in the constant we
3063 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003064 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003065 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003066 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003067 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003068 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003069 break;
3070
3071 case Instruction::And:
3072 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003073 // If bits are being compared against that are and'd out, then the
3074 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003075 if (!ConstantExpr::getAnd(CI,
3076 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003077 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003078
Chris Lattner35167c32004-06-09 07:59:58 +00003079 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003080 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003081 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3082 Instruction::SetNE, Op0,
3083 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003084
Chris Lattnerc992add2003-08-13 05:33:12 +00003085 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3086 // to be a signed value as appropriate.
3087 if (isSignBit(BOC)) {
3088 Value *X = BO->getOperand(0);
3089 // If 'X' is not signed, insert a cast now...
3090 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003091 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003092 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003093 }
3094 return new SetCondInst(isSetNE ? Instruction::SetLT :
3095 Instruction::SetGE, X,
3096 Constant::getNullValue(X->getType()));
3097 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003098
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003099 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003100 if (CI->isNullValue() && isHighOnes(BOC)) {
3101 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003102 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003103
3104 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003105 if (NegX->getType()->isSigned()) {
3106 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3107 X = InsertCastBefore(X, DestTy, I);
3108 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003109 }
3110
3111 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003112 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003113 }
3114
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003115 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003116 default: break;
3117 }
3118 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003119 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003120 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003121 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3122 Value *CastOp = Cast->getOperand(0);
3123 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003124 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003125 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003126 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003127 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003128 "Source and destination signednesses should differ!");
3129 if (Cast->getType()->isSigned()) {
3130 // If this is a signed comparison, check for comparisons in the
3131 // vicinity of zero.
3132 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3133 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003134 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003135 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003136 else if (I.getOpcode() == Instruction::SetGT &&
3137 cast<ConstantSInt>(CI)->getValue() == -1)
3138 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003139 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003140 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003141 } else {
3142 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3143 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003144 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003145 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003146 return BinaryOperator::createSetGT(CastOp,
3147 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003148 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003149 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003150 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003151 return BinaryOperator::createSetLT(CastOp,
3152 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003153 }
3154 }
3155 }
Chris Lattnere967b342003-06-04 05:10:11 +00003156 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003157 }
3158
Chris Lattner77c32c32005-04-23 15:31:55 +00003159 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3160 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3161 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3162 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003163 case Instruction::GetElementPtr:
3164 if (RHSC->isNullValue()) {
3165 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3166 bool isAllZeros = true;
3167 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3168 if (!isa<Constant>(LHSI->getOperand(i)) ||
3169 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3170 isAllZeros = false;
3171 break;
3172 }
3173 if (isAllZeros)
3174 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3175 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3176 }
3177 break;
3178
Chris Lattner77c32c32005-04-23 15:31:55 +00003179 case Instruction::PHI:
3180 if (Instruction *NV = FoldOpIntoPhi(I))
3181 return NV;
3182 break;
3183 case Instruction::Select:
3184 // If either operand of the select is a constant, we can fold the
3185 // comparison into the select arms, which will cause one to be
3186 // constant folded and the select turned into a bitwise or.
3187 Value *Op1 = 0, *Op2 = 0;
3188 if (LHSI->hasOneUse()) {
3189 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3190 // Fold the known value into the constant operand.
3191 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3192 // Insert a new SetCC of the other select operand.
3193 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3194 LHSI->getOperand(2), RHSC,
3195 I.getName()), I);
3196 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3197 // Fold the known value into the constant operand.
3198 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3199 // Insert a new SetCC of the other select operand.
3200 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3201 LHSI->getOperand(1), RHSC,
3202 I.getName()), I);
3203 }
3204 }
Jeff Cohen82639852005-04-23 21:38:35 +00003205
Chris Lattner77c32c32005-04-23 15:31:55 +00003206 if (Op1)
3207 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3208 break;
3209 }
3210 }
3211
Chris Lattner0798af32005-01-13 20:14:25 +00003212 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3213 if (User *GEP = dyn_castGetElementPtr(Op0))
3214 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3215 return NI;
3216 if (User *GEP = dyn_castGetElementPtr(Op1))
3217 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3218 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3219 return NI;
3220
Chris Lattner16930792003-11-03 04:25:02 +00003221 // Test to see if the operands of the setcc are casted versions of other
3222 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003223 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3224 Value *CastOp0 = CI->getOperand(0);
3225 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003226 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003227 (I.getOpcode() == Instruction::SetEQ ||
3228 I.getOpcode() == Instruction::SetNE)) {
3229 // We keep moving the cast from the left operand over to the right
3230 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003231 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003232
Chris Lattner16930792003-11-03 04:25:02 +00003233 // If operand #1 is a cast instruction, see if we can eliminate it as
3234 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003235 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3236 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003237 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003238 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003239
Chris Lattner16930792003-11-03 04:25:02 +00003240 // If Op1 is a constant, we can fold the cast into the constant.
3241 if (Op1->getType() != Op0->getType())
3242 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3243 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3244 } else {
3245 // Otherwise, cast the RHS right before the setcc
3246 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3247 InsertNewInstBefore(cast<Instruction>(Op1), I);
3248 }
3249 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3250 }
3251
Chris Lattner6444c372003-11-03 05:17:03 +00003252 // Handle the special case of: setcc (cast bool to X), <cst>
3253 // This comes up when you have code like
3254 // int X = A < B;
3255 // if (X) ...
3256 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003257 // with a constant or another cast from the same type.
3258 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3259 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3260 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003261 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003262 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003263}
3264
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003265// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3266// We only handle extending casts so far.
3267//
3268Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3269 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3270 const Type *SrcTy = LHSCIOp->getType();
3271 const Type *DestTy = SCI.getOperand(0)->getType();
3272 Value *RHSCIOp;
3273
3274 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003275 return 0;
3276
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003277 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3278 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3279 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3280
3281 // Is this a sign or zero extension?
3282 bool isSignSrc = SrcTy->isSigned();
3283 bool isSignDest = DestTy->isSigned();
3284
3285 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3286 // Not an extension from the same type?
3287 RHSCIOp = CI->getOperand(0);
3288 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3289 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3290 // Compute the constant that would happen if we truncated to SrcTy then
3291 // reextended to DestTy.
3292 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3293
3294 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3295 RHSCIOp = Res;
3296 } else {
3297 // If the value cannot be represented in the shorter type, we cannot emit
3298 // a simple comparison.
3299 if (SCI.getOpcode() == Instruction::SetEQ)
3300 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3301 if (SCI.getOpcode() == Instruction::SetNE)
3302 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3303
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003304 // Evaluate the comparison for LT.
3305 Value *Result;
3306 if (DestTy->isSigned()) {
3307 // We're performing a signed comparison.
3308 if (isSignSrc) {
3309 // Signed extend and signed comparison.
3310 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3311 Result = ConstantBool::False;
3312 else
3313 Result = ConstantBool::True; // X < (large) --> true
3314 } else {
3315 // Unsigned extend and signed comparison.
3316 if (cast<ConstantSInt>(CI)->getValue() < 0)
3317 Result = ConstantBool::False;
3318 else
3319 Result = ConstantBool::True;
3320 }
3321 } else {
3322 // We're performing an unsigned comparison.
3323 if (!isSignSrc) {
3324 // Unsigned extend & compare -> always true.
3325 Result = ConstantBool::True;
3326 } else {
3327 // We're performing an unsigned comp with a sign extended value.
3328 // This is true if the input is >= 0. [aka >s -1]
3329 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3330 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3331 NegOne, SCI.getName()), SCI);
3332 }
Reid Spencer279fa252004-11-28 21:31:15 +00003333 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003334
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003335 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003336 if (SCI.getOpcode() == Instruction::SetLT) {
3337 return ReplaceInstUsesWith(SCI, Result);
3338 } else {
3339 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3340 if (Constant *CI = dyn_cast<Constant>(Result))
3341 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3342 else
3343 return BinaryOperator::createNot(Result);
3344 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003345 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003346 } else {
3347 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003348 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003349
Chris Lattner252a8452005-06-16 03:00:08 +00003350 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003351 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3352}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003353
Chris Lattnere8d6c602003-03-10 19:16:08 +00003354Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003355 assert(I.getOperand(1)->getType() == Type::UByteTy);
3356 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003357 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003358
3359 // shl X, 0 == X and shr X, 0 == X
3360 // shl 0, X == 0 and shr 0, X == 0
3361 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003362 Op0 == Constant::getNullValue(Op0->getType()))
3363 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003364
Chris Lattner81a7a232004-10-16 18:11:37 +00003365 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3366 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003367 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003368 else // undef << X -> 0 AND undef >>u X -> 0
3369 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3370 }
3371 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003372 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003373 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3374 else
3375 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3376 }
3377
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003378 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3379 if (!isLeftShift)
3380 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3381 if (CSI->isAllOnesValue())
3382 return ReplaceInstUsesWith(I, CSI);
3383
Chris Lattner183b3362004-04-09 19:05:30 +00003384 // Try to fold constant and into select arguments.
3385 if (isa<Constant>(Op0))
3386 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003387 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003388 return R;
3389
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003390 // See if we can turn a signed shr into an unsigned shr.
3391 if (!isLeftShift && I.getType()->isSigned()) {
3392 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3393 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3394 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3395 I.getName()), I);
3396 return new CastInst(V, I.getType());
3397 }
3398 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003399
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003400 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003401 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3402 // of a signed value.
3403 //
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003404 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003405 if (CUI->getValue() >= TypeBits) {
3406 if (!Op0->getType()->isSigned() || isLeftShift)
3407 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3408 else {
3409 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3410 return &I;
3411 }
3412 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003413
Chris Lattnerede3fe02003-08-13 04:18:28 +00003414 // ((X*C1) << C2) == (X * (C1 << C2))
3415 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3416 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3417 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003418 return BinaryOperator::createMul(BO->getOperand(0),
3419 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanb1c93172005-04-21 23:48:37 +00003420
Chris Lattner183b3362004-04-09 19:05:30 +00003421 // Try to fold constant and into select arguments.
3422 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003423 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003424 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003425 if (isa<PHINode>(Op0))
3426 if (Instruction *NV = FoldOpIntoPhi(I))
3427 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003428
Chris Lattner86102b82005-01-01 16:22:27 +00003429 if (Op0->hasOneUse()) {
3430 // If this is a SHL of a sign-extending cast, see if we can turn the input
3431 // into a zero extending cast (a simple strength reduction).
3432 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3433 const Type *SrcTy = CI->getOperand(0)->getType();
3434 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003435 SrcTy->getPrimitiveSizeInBits() <
3436 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00003437 // We can change it to a zero extension if we are shifting out all of
3438 // the sign extended bits. To check this, form a mask of all of the
3439 // sign extend bits, then shift them left and see if we have anything
3440 // left.
3441 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3442 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3443 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3444 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3445 // If the shift is nuking all of the sign bits, change this to a
3446 // zero extension cast. To do this, cast the cast input to
3447 // unsigned, then to the requested size.
3448 Value *CastOp = CI->getOperand(0);
3449 Instruction *NC =
3450 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3451 CI->getName()+".uns");
3452 NC = InsertNewInstBefore(NC, I);
3453 // Finally, insert a replacement for CI.
3454 NC = new CastInst(NC, CI->getType(), CI->getName());
3455 CI->setName("");
3456 NC = InsertNewInstBefore(NC, I);
3457 WorkList.push_back(CI); // Delete CI later.
3458 I.setOperand(0, NC);
3459 return &I; // The SHL operand was modified.
3460 }
3461 }
3462 }
3463
Chris Lattner27cb9db2005-09-18 05:12:10 +00003464 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3465 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Jeff Cohen572910c2005-10-07 05:28:29 +00003466 Value *V1, *V2;
Chris Lattner797dee72005-09-18 06:30:59 +00003467 ConstantInt *CC;
Chris Lattner27cb9db2005-09-18 05:12:10 +00003468 switch (Op0BO->getOpcode()) {
3469 default: break;
3470 case Instruction::Add:
3471 case Instruction::And:
3472 case Instruction::Or:
3473 case Instruction::Xor:
3474 // These operators commute.
3475 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003476 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3477 match(Op0BO->getOperand(1),
3478 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3479 Instruction *YS = new ShiftInst(Instruction::Shl,
3480 Op0BO->getOperand(0), CUI,
3481 Op0BO->getName());
3482 InsertNewInstBefore(YS, I); // (Y << C)
3483 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3484 V1,
3485 Op0BO->getOperand(1)->getName());
3486 InsertNewInstBefore(X, I); // (X + (Y << C))
3487 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3488 C2 = ConstantExpr::getShl(C2, CUI);
3489 return BinaryOperator::createAnd(X, C2);
3490 }
3491
3492 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3493 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3494 match(Op0BO->getOperand(1),
3495 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3496 m_ConstantInt(CC))) && V2 == CUI &&
3497 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3498 Instruction *YS = new ShiftInst(Instruction::Shl,
3499 Op0BO->getOperand(0), CUI,
3500 Op0BO->getName());
3501 InsertNewInstBefore(YS, I); // (Y << C)
3502 Instruction *XM =
3503 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3504 V1->getName()+".mask");
3505 InsertNewInstBefore(XM, I); // X & (CC << C)
3506
3507 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3508 }
3509
3510 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00003511 case Instruction::Sub:
3512 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003513 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3514 match(Op0BO->getOperand(0),
3515 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3516 Instruction *YS = new ShiftInst(Instruction::Shl,
3517 Op0BO->getOperand(1), CUI,
3518 Op0BO->getName());
3519 InsertNewInstBefore(YS, I); // (Y << C)
3520 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3521 V1,
3522 Op0BO->getOperand(0)->getName());
3523 InsertNewInstBefore(X, I); // (X + (Y << C))
3524 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3525 C2 = ConstantExpr::getShl(C2, CUI);
3526 return BinaryOperator::createAnd(X, C2);
3527 }
3528
3529 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3530 match(Op0BO->getOperand(0),
3531 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3532 m_ConstantInt(CC))) && V2 == CUI &&
3533 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3534 Instruction *YS = new ShiftInst(Instruction::Shl,
3535 Op0BO->getOperand(1), CUI,
3536 Op0BO->getName());
3537 InsertNewInstBefore(YS, I); // (Y << C)
3538 Instruction *XM =
3539 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3540 V1->getName()+".mask");
3541 InsertNewInstBefore(XM, I); // X & (CC << C)
3542
3543 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3544 }
3545
Chris Lattner27cb9db2005-09-18 05:12:10 +00003546 break;
3547 }
3548
3549
3550 // If the operand is an bitwise operator with a constant RHS, and the
3551 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003552 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3553 bool isValid = true; // Valid only for And, Or, Xor
3554 bool highBitSet = false; // Transform if high bit of constant set?
3555
3556 switch (Op0BO->getOpcode()) {
3557 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003558 case Instruction::Add:
3559 isValid = isLeftShift;
3560 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003561 case Instruction::Or:
3562 case Instruction::Xor:
3563 highBitSet = false;
3564 break;
3565 case Instruction::And:
3566 highBitSet = true;
3567 break;
3568 }
3569
3570 // If this is a signed shift right, and the high bit is modified
3571 // by the logical operation, do not perform the transformation.
3572 // The highBitSet boolean indicates the value of the high bit of
3573 // the constant which would cause it to be modified for this
3574 // operation.
3575 //
3576 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3577 uint64_t Val = Op0C->getRawValue();
3578 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3579 }
3580
3581 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003582 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003583
3584 Instruction *NewShift =
3585 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3586 Op0BO->getName());
3587 Op0BO->setName("");
3588 InsertNewInstBefore(NewShift, I);
3589
3590 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3591 NewRHS);
3592 }
3593 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00003594 }
Chris Lattner86102b82005-01-01 16:22:27 +00003595 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003596
Chris Lattner3204d4e2003-07-24 17:52:58 +00003597 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003598 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003599 if (ConstantUInt *ShiftAmt1C =
3600 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003601 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3602 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003603
Chris Lattner3204d4e2003-07-24 17:52:58 +00003604 // Check for (A << c1) << c2 and (A >> c1) >> c2
3605 if (I.getOpcode() == Op0SI->getOpcode()) {
3606 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003607 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3608 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003609 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3610 ConstantUInt::get(Type::UByteTy, Amt));
3611 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003612
Chris Lattnerab780df2003-07-24 18:38:56 +00003613 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3614 // signed types, we can only support the (A >> c1) << c2 configuration,
3615 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003616 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003617 // Calculate bitmask for what gets shifted off the edge...
3618 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003619 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003620 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003621 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003622 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003623
Chris Lattner3204d4e2003-07-24 17:52:58 +00003624 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003625 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3626 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003627 InsertNewInstBefore(Mask, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003628
Chris Lattner3204d4e2003-07-24 17:52:58 +00003629 // Figure out what flavor of shift we should use...
3630 if (ShiftAmt1 == ShiftAmt2)
3631 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3632 else if (ShiftAmt1 < ShiftAmt2) {
3633 return new ShiftInst(I.getOpcode(), Mask,
3634 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3635 } else {
3636 return new ShiftInst(Op0SI->getOpcode(), Mask,
3637 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3638 }
Chris Lattner0b3557f2005-09-24 23:43:33 +00003639 } else {
3640 // We can handle signed (X << C1) >> C2 if it's a sign extend. In
3641 // this case, C1 == C2 and C1 is 8, 16, or 32.
3642 if (ShiftAmt1 == ShiftAmt2) {
3643 const Type *SExtType = 0;
3644 switch (ShiftAmt1) {
3645 case 8 : SExtType = Type::SByteTy; break;
3646 case 16: SExtType = Type::ShortTy; break;
3647 case 32: SExtType = Type::IntTy; break;
3648 }
3649
3650 if (SExtType) {
3651 Instruction *NewTrunc = new CastInst(Op0SI->getOperand(0),
3652 SExtType, "sext");
3653 InsertNewInstBefore(NewTrunc, I);
3654 return new CastInst(NewTrunc, I.getType());
3655 }
3656 }
Chris Lattner3204d4e2003-07-24 17:52:58 +00003657 }
3658 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003659 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003660
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003661 return 0;
3662}
3663
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003664enum CastType {
3665 Noop = 0,
3666 Truncate = 1,
3667 Signext = 2,
3668 Zeroext = 3
3669};
3670
3671/// getCastType - In the future, we will split the cast instruction into these
3672/// various types. Until then, we have to do the analysis here.
3673static CastType getCastType(const Type *Src, const Type *Dest) {
3674 assert(Src->isIntegral() && Dest->isIntegral() &&
3675 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003676 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3677 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003678
3679 if (SrcSize == DestSize) return Noop;
3680 if (SrcSize > DestSize) return Truncate;
3681 if (Src->isSigned()) return Signext;
3682 return Zeroext;
3683}
3684
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003685
Chris Lattner48a44f72002-05-02 17:06:02 +00003686// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3687// instruction.
3688//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003689static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003690 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003691
Chris Lattner650b6da2002-08-02 20:00:25 +00003692 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003693 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003694 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003695 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003696 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003697
Chris Lattner4fbad962004-07-21 04:27:24 +00003698 // If we are casting between pointer and integer types, treat pointers as
3699 // integers of the appropriate size for the code below.
3700 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3701 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3702 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003703
Chris Lattner48a44f72002-05-02 17:06:02 +00003704 // Allow free casting and conversion of sizes as long as the sign doesn't
3705 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003706 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003707 CastType FirstCast = getCastType(SrcTy, MidTy);
3708 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003709
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003710 // Capture the effect of these two casts. If the result is a legal cast,
3711 // the CastType is stored here, otherwise a special code is used.
3712 static const unsigned CastResult[] = {
3713 // First cast is noop
3714 0, 1, 2, 3,
3715 // First cast is a truncate
3716 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3717 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003718 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003719 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003720 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003721 };
3722
3723 unsigned Result = CastResult[FirstCast*4+SecondCast];
3724 switch (Result) {
3725 default: assert(0 && "Illegal table value!");
3726 case 0:
3727 case 1:
3728 case 2:
3729 case 3:
3730 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3731 // truncates, we could eliminate more casts.
3732 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3733 case 4:
3734 return false; // Not possible to eliminate this here.
3735 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003736 // Sign or zero extend followed by truncate is always ok if the result
3737 // is a truncate or noop.
3738 CastType ResultCast = getCastType(SrcTy, DstTy);
3739 if (ResultCast == Noop || ResultCast == Truncate)
3740 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003741 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003742 // result will match the sign/zeroextendness of the result.
3743 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003744 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003745 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003746 return false;
3747}
3748
Chris Lattner11ffd592004-07-20 05:21:00 +00003749static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003750 if (V->getType() == Ty || isa<Constant>(V)) return false;
3751 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003752 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3753 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003754 return false;
3755 return true;
3756}
3757
3758/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3759/// InsertBefore instruction. This is specialized a bit to avoid inserting
3760/// casts that are known to not do anything...
3761///
3762Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3763 Instruction *InsertBefore) {
3764 if (V->getType() == DestTy) return V;
3765 if (Constant *C = dyn_cast<Constant>(V))
3766 return ConstantExpr::getCast(C, DestTy);
3767
3768 CastInst *CI = new CastInst(V, DestTy, V->getName());
3769 InsertNewInstBefore(CI, *InsertBefore);
3770 return CI;
3771}
Chris Lattner48a44f72002-05-02 17:06:02 +00003772
Chris Lattner8f663e82005-10-29 04:36:15 +00003773/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
3774/// expression. If so, decompose it, returning some value X, such that Val is
3775/// X*Scale+Offset.
3776///
3777static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
3778 unsigned &Offset) {
3779 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
3780 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
3781 Offset = CI->getValue();
3782 Scale = 1;
3783 return ConstantUInt::get(Type::UIntTy, 0);
3784 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
3785 if (I->getNumOperands() == 2) {
3786 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
3787 if (I->getOpcode() == Instruction::Shl) {
3788 // This is a value scaled by '1 << the shift amt'.
3789 Scale = 1U << CUI->getValue();
3790 Offset = 0;
3791 return I->getOperand(0);
3792 } else if (I->getOpcode() == Instruction::Mul) {
3793 // This value is scaled by 'CUI'.
3794 Scale = CUI->getValue();
3795 Offset = 0;
3796 return I->getOperand(0);
3797 } else if (I->getOpcode() == Instruction::Add) {
3798 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
3799 // divisible by C2.
3800 unsigned SubScale;
3801 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
3802 Offset);
3803 Offset += CUI->getValue();
3804 if (SubScale > 1 && (Offset % SubScale == 0)) {
3805 Scale = SubScale;
3806 return SubVal;
3807 }
3808 }
3809 }
3810 }
3811 }
3812
3813 // Otherwise, we can't look past this.
3814 Scale = 1;
3815 Offset = 0;
3816 return Val;
3817}
3818
3819
Chris Lattner216be912005-10-24 06:03:58 +00003820/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
3821/// try to eliminate the cast by moving the type information into the alloc.
3822Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
3823 AllocationInst &AI) {
3824 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00003825 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00003826
Chris Lattnerac87beb2005-10-24 06:22:12 +00003827 // Remove any uses of AI that are dead.
3828 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
3829 std::vector<Instruction*> DeadUsers;
3830 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
3831 Instruction *User = cast<Instruction>(*UI++);
3832 if (isInstructionTriviallyDead(User)) {
3833 while (UI != E && *UI == User)
3834 ++UI; // If this instruction uses AI more than once, don't break UI.
3835
3836 // Add operands to the worklist.
3837 AddUsesToWorkList(*User);
3838 ++NumDeadInst;
3839 DEBUG(std::cerr << "IC: DCE: " << *User);
3840
3841 User->eraseFromParent();
3842 removeFromWorkList(User);
3843 }
3844 }
3845
Chris Lattner216be912005-10-24 06:03:58 +00003846 // Get the type really allocated and the type casted to.
3847 const Type *AllocElTy = AI.getAllocatedType();
3848 const Type *CastElTy = PTy->getElementType();
3849 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003850
3851 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
3852 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
3853 if (CastElTyAlign < AllocElTyAlign) return 0;
3854
Chris Lattner46705b22005-10-24 06:35:18 +00003855 // If the allocation has multiple uses, only promote it if we are strictly
3856 // increasing the alignment of the resultant allocation. If we keep it the
3857 // same, we open the door to infinite loops of various kinds.
3858 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
3859
Chris Lattner216be912005-10-24 06:03:58 +00003860 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3861 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00003862 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003863
Chris Lattner8270c332005-10-29 03:19:53 +00003864 // See if we can satisfy the modulus by pulling a scale out of the array
3865 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00003866 unsigned ArraySizeScale, ArrayOffset;
3867 Value *NumElements = // See if the array size is a decomposable linear expr.
3868 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
3869
Chris Lattner8270c332005-10-29 03:19:53 +00003870 // If we can now satisfy the modulus, by using a non-1 scale, we really can
3871 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00003872 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
3873 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003874
Chris Lattner8270c332005-10-29 03:19:53 +00003875 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
3876 Value *Amt = 0;
3877 if (Scale == 1) {
3878 Amt = NumElements;
3879 } else {
3880 Amt = ConstantUInt::get(Type::UIntTy, Scale);
3881 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
3882 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
3883 else if (Scale != 1) {
3884 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
3885 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003886 }
Chris Lattnerbb171802005-10-27 05:53:56 +00003887 }
3888
Chris Lattner8f663e82005-10-29 04:36:15 +00003889 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
3890 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
3891 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
3892 Amt = InsertNewInstBefore(Tmp, AI);
3893 }
3894
Chris Lattner216be912005-10-24 06:03:58 +00003895 std::string Name = AI.getName(); AI.setName("");
3896 AllocationInst *New;
3897 if (isa<MallocInst>(AI))
3898 New = new MallocInst(CastElTy, Amt, Name);
3899 else
3900 New = new AllocaInst(CastElTy, Amt, Name);
3901 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00003902
3903 // If the allocation has multiple uses, insert a cast and change all things
3904 // that used it to use the new cast. This will also hack on CI, but it will
3905 // die soon.
3906 if (!AI.hasOneUse()) {
3907 AddUsesToWorkList(AI);
3908 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
3909 InsertNewInstBefore(NewCast, AI);
3910 AI.replaceAllUsesWith(NewCast);
3911 }
Chris Lattner216be912005-10-24 06:03:58 +00003912 return ReplaceInstUsesWith(CI, New);
3913}
3914
3915
Chris Lattner48a44f72002-05-02 17:06:02 +00003916// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003917//
Chris Lattner113f4f42002-06-25 16:13:24 +00003918Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003919 Value *Src = CI.getOperand(0);
3920
Chris Lattner48a44f72002-05-02 17:06:02 +00003921 // If the user is casting a value to the same type, eliminate this cast
3922 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003923 if (CI.getType() == Src->getType())
3924 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003925
Chris Lattner81a7a232004-10-16 18:11:37 +00003926 if (isa<UndefValue>(Src)) // cast undef -> undef
3927 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3928
Chris Lattner48a44f72002-05-02 17:06:02 +00003929 // If casting the result of another cast instruction, try to eliminate this
3930 // one!
3931 //
Chris Lattner86102b82005-01-01 16:22:27 +00003932 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3933 Value *A = CSrc->getOperand(0);
3934 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3935 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003936 // This instruction now refers directly to the cast's src operand. This
3937 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003938 CI.setOperand(0, CSrc->getOperand(0));
3939 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003940 }
3941
Chris Lattner650b6da2002-08-02 20:00:25 +00003942 // If this is an A->B->A cast, and we are dealing with integral types, try
3943 // to convert this into a logical 'and' instruction.
3944 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003945 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003946 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003947 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003948 CSrc->getType()->getPrimitiveSizeInBits() <
3949 CI.getType()->getPrimitiveSizeInBits()&&
3950 A->getType()->getPrimitiveSizeInBits() ==
3951 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003952 assert(CSrc->getType() != Type::ULongTy &&
3953 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00003954 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00003955 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3956 AndValue);
3957 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3958 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3959 if (And->getType() != CI.getType()) {
3960 And->setName(CSrc->getName()+".mask");
3961 InsertNewInstBefore(And, CI);
3962 And = new CastInst(And, CI.getType());
3963 }
3964 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003965 }
3966 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003967
Chris Lattner03841652004-05-25 04:29:21 +00003968 // If this is a cast to bool, turn it into the appropriate setne instruction.
3969 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003970 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003971 Constant::getNullValue(CI.getOperand(0)->getType()));
3972
Chris Lattnerd0d51602003-06-21 23:12:02 +00003973 // If casting the result of a getelementptr instruction with no offset, turn
3974 // this into a cast of the original pointer!
3975 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003976 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003977 bool AllZeroOperands = true;
3978 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3979 if (!isa<Constant>(GEP->getOperand(i)) ||
3980 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3981 AllZeroOperands = false;
3982 break;
3983 }
3984 if (AllZeroOperands) {
3985 CI.setOperand(0, GEP->getOperand(0));
3986 return &CI;
3987 }
3988 }
3989
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003990 // If we are casting a malloc or alloca to a pointer to a type of the same
3991 // size, rewrite the allocation instruction to allocate the "right" type.
3992 //
3993 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00003994 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
3995 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003996
Chris Lattner86102b82005-01-01 16:22:27 +00003997 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3998 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3999 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004000 if (isa<PHINode>(Src))
4001 if (Instruction *NV = FoldOpIntoPhi(CI))
4002 return NV;
4003
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004004 // If the source value is an instruction with only this use, we can attempt to
4005 // propagate the cast into the instruction. Also, only handle integral types
4006 // for now.
4007 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004008 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004009 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4010 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004011 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4012 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004013
4014 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4015 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4016
4017 switch (SrcI->getOpcode()) {
4018 case Instruction::Add:
4019 case Instruction::Mul:
4020 case Instruction::And:
4021 case Instruction::Or:
4022 case Instruction::Xor:
4023 // If we are discarding information, or just changing the sign, rewrite.
4024 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4025 // Don't insert two casts if they cannot be eliminated. We allow two
4026 // casts to be inserted if the sizes are the same. This could only be
4027 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004028 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4029 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004030 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4031 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4032 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4033 ->getOpcode(), Op0c, Op1c);
4034 }
4035 }
Chris Lattner72086162005-05-06 02:07:39 +00004036
4037 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4038 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4039 Op1 == ConstantBool::True &&
4040 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4041 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4042 return BinaryOperator::createXor(New,
4043 ConstantInt::get(CI.getType(), 1));
4044 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004045 break;
4046 case Instruction::Shl:
4047 // Allow changing the sign of the source operand. Do not allow changing
4048 // the size of the shift, UNLESS the shift amount is a constant. We
4049 // mush not change variable sized shifts to a smaller size, because it
4050 // is undefined to shift more bits out than exist in the value.
4051 if (DestBitSize == SrcBitSize ||
4052 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4053 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4054 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4055 }
4056 break;
Chris Lattner87380412005-05-06 04:18:52 +00004057 case Instruction::Shr:
4058 // If this is a signed shr, and if all bits shifted in are about to be
4059 // truncated off, turn it into an unsigned shr to allow greater
4060 // simplifications.
4061 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4062 isa<ConstantInt>(Op1)) {
4063 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4064 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4065 // Convert to unsigned.
4066 Value *N1 = InsertOperandCastBefore(Op0,
4067 Op0->getType()->getUnsignedVersion(), &CI);
4068 // Insert the new shift, which is now unsigned.
4069 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4070 Op1, Src->getName()), CI);
4071 return new CastInst(N1, CI.getType());
4072 }
4073 }
4074 break;
4075
Chris Lattner809dfac2005-05-04 19:10:26 +00004076 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004077 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004078 if (Op1C->getRawValue() == 0) {
4079 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004080 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004081 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004082 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00004083 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4084 if (CI.getType() == Op0->getType())
4085 return ReplaceInstUsesWith(CI, Op0);
4086 else
4087 return new CastInst(Op0, CI.getType());
4088 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004089
4090 // If the input is an and with a single bit, shift then simplify.
4091 ConstantInt *AndRHS;
4092 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4093 if (AndRHS->getRawValue() &&
4094 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004095 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004096 // Perform an unsigned shr by shiftamt. Convert input to
4097 // unsigned if it is signed.
4098 Value *In = Op0;
4099 if (In->getType()->isSigned())
4100 In = InsertNewInstBefore(new CastInst(In,
4101 In->getType()->getUnsignedVersion(), In->getName()),CI);
4102 // Insert the shift to put the result in the low bit.
4103 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4104 ConstantInt::get(Type::UByteTy, ShiftAmt),
4105 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004106 if (CI.getType() == In->getType())
4107 return ReplaceInstUsesWith(CI, In);
4108 else
4109 return new CastInst(In, CI.getType());
4110 }
4111 }
4112 }
4113 break;
4114 case Instruction::SetEQ:
4115 // We if we are just checking for a seteq of a single bit and casting it
4116 // to an integer. If so, shift the bit to the appropriate place then
4117 // cast to integer to avoid the comparison.
4118 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4119 // Is Op1C a power of two or zero?
4120 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4121 // cast (X == 1) to int -> X iff X has only the low bit set.
4122 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004123 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004124 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4125 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4126 if (CI.getType() == Op0->getType())
4127 return ReplaceInstUsesWith(CI, Op0);
4128 else
4129 return new CastInst(Op0, CI.getType());
4130 }
4131 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004132 }
4133 }
4134 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004135 }
4136 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004137
Chris Lattner260ab202002-04-18 17:39:14 +00004138 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004139}
4140
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004141/// GetSelectFoldableOperands - We want to turn code that looks like this:
4142/// %C = or %A, %B
4143/// %D = select %cond, %C, %A
4144/// into:
4145/// %C = select %cond, %B, 0
4146/// %D = or %A, %C
4147///
4148/// Assuming that the specified instruction is an operand to the select, return
4149/// a bitmask indicating which operands of this instruction are foldable if they
4150/// equal the other incoming value of the select.
4151///
4152static unsigned GetSelectFoldableOperands(Instruction *I) {
4153 switch (I->getOpcode()) {
4154 case Instruction::Add:
4155 case Instruction::Mul:
4156 case Instruction::And:
4157 case Instruction::Or:
4158 case Instruction::Xor:
4159 return 3; // Can fold through either operand.
4160 case Instruction::Sub: // Can only fold on the amount subtracted.
4161 case Instruction::Shl: // Can only fold on the shift amount.
4162 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004163 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004164 default:
4165 return 0; // Cannot fold
4166 }
4167}
4168
4169/// GetSelectFoldableConstant - For the same transformation as the previous
4170/// function, return the identity constant that goes into the select.
4171static Constant *GetSelectFoldableConstant(Instruction *I) {
4172 switch (I->getOpcode()) {
4173 default: assert(0 && "This cannot happen!"); abort();
4174 case Instruction::Add:
4175 case Instruction::Sub:
4176 case Instruction::Or:
4177 case Instruction::Xor:
4178 return Constant::getNullValue(I->getType());
4179 case Instruction::Shl:
4180 case Instruction::Shr:
4181 return Constant::getNullValue(Type::UByteTy);
4182 case Instruction::And:
4183 return ConstantInt::getAllOnesValue(I->getType());
4184 case Instruction::Mul:
4185 return ConstantInt::get(I->getType(), 1);
4186 }
4187}
4188
Chris Lattner411336f2005-01-19 21:50:18 +00004189/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4190/// have the same opcode and only one use each. Try to simplify this.
4191Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4192 Instruction *FI) {
4193 if (TI->getNumOperands() == 1) {
4194 // If this is a non-volatile load or a cast from the same type,
4195 // merge.
4196 if (TI->getOpcode() == Instruction::Cast) {
4197 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4198 return 0;
4199 } else {
4200 return 0; // unknown unary op.
4201 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004202
Chris Lattner411336f2005-01-19 21:50:18 +00004203 // Fold this by inserting a select from the input values.
4204 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4205 FI->getOperand(0), SI.getName()+".v");
4206 InsertNewInstBefore(NewSI, SI);
4207 return new CastInst(NewSI, TI->getType());
4208 }
4209
4210 // Only handle binary operators here.
4211 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4212 return 0;
4213
4214 // Figure out if the operations have any operands in common.
4215 Value *MatchOp, *OtherOpT, *OtherOpF;
4216 bool MatchIsOpZero;
4217 if (TI->getOperand(0) == FI->getOperand(0)) {
4218 MatchOp = TI->getOperand(0);
4219 OtherOpT = TI->getOperand(1);
4220 OtherOpF = FI->getOperand(1);
4221 MatchIsOpZero = true;
4222 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4223 MatchOp = TI->getOperand(1);
4224 OtherOpT = TI->getOperand(0);
4225 OtherOpF = FI->getOperand(0);
4226 MatchIsOpZero = false;
4227 } else if (!TI->isCommutative()) {
4228 return 0;
4229 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4230 MatchOp = TI->getOperand(0);
4231 OtherOpT = TI->getOperand(1);
4232 OtherOpF = FI->getOperand(0);
4233 MatchIsOpZero = true;
4234 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4235 MatchOp = TI->getOperand(1);
4236 OtherOpT = TI->getOperand(0);
4237 OtherOpF = FI->getOperand(1);
4238 MatchIsOpZero = true;
4239 } else {
4240 return 0;
4241 }
4242
4243 // If we reach here, they do have operations in common.
4244 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4245 OtherOpF, SI.getName()+".v");
4246 InsertNewInstBefore(NewSI, SI);
4247
4248 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4249 if (MatchIsOpZero)
4250 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4251 else
4252 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4253 } else {
4254 if (MatchIsOpZero)
4255 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4256 else
4257 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4258 }
4259}
4260
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004261Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004262 Value *CondVal = SI.getCondition();
4263 Value *TrueVal = SI.getTrueValue();
4264 Value *FalseVal = SI.getFalseValue();
4265
4266 // select true, X, Y -> X
4267 // select false, X, Y -> Y
4268 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004269 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004270 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004271 else {
4272 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004273 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004274 }
Chris Lattner533bc492004-03-30 19:37:13 +00004275
4276 // select C, X, X -> X
4277 if (TrueVal == FalseVal)
4278 return ReplaceInstUsesWith(SI, TrueVal);
4279
Chris Lattner81a7a232004-10-16 18:11:37 +00004280 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4281 return ReplaceInstUsesWith(SI, FalseVal);
4282 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4283 return ReplaceInstUsesWith(SI, TrueVal);
4284 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4285 if (isa<Constant>(TrueVal))
4286 return ReplaceInstUsesWith(SI, TrueVal);
4287 else
4288 return ReplaceInstUsesWith(SI, FalseVal);
4289 }
4290
Chris Lattner1c631e82004-04-08 04:43:23 +00004291 if (SI.getType() == Type::BoolTy)
4292 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4293 if (C == ConstantBool::True) {
4294 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004295 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004296 } else {
4297 // Change: A = select B, false, C --> A = and !B, C
4298 Value *NotCond =
4299 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4300 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004301 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004302 }
4303 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4304 if (C == ConstantBool::False) {
4305 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004306 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004307 } else {
4308 // Change: A = select B, C, true --> A = or !B, C
4309 Value *NotCond =
4310 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4311 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004312 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004313 }
4314 }
4315
Chris Lattner183b3362004-04-09 19:05:30 +00004316 // Selecting between two integer constants?
4317 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4318 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4319 // select C, 1, 0 -> cast C to int
4320 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4321 return new CastInst(CondVal, SI.getType());
4322 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4323 // select C, 0, 1 -> cast !C to int
4324 Value *NotCond =
4325 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004326 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004327 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004328 }
Chris Lattner35167c32004-06-09 07:59:58 +00004329
4330 // If one of the constants is zero (we know they can't both be) and we
4331 // have a setcc instruction with zero, and we have an 'and' with the
4332 // non-constant value, eliminate this whole mess. This corresponds to
4333 // cases like this: ((X & 27) ? 27 : 0)
4334 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4335 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4336 if ((IC->getOpcode() == Instruction::SetEQ ||
4337 IC->getOpcode() == Instruction::SetNE) &&
4338 isa<ConstantInt>(IC->getOperand(1)) &&
4339 cast<Constant>(IC->getOperand(1))->isNullValue())
4340 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4341 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004342 isa<ConstantInt>(ICA->getOperand(1)) &&
4343 (ICA->getOperand(1) == TrueValC ||
4344 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004345 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4346 // Okay, now we know that everything is set up, we just don't
4347 // know whether we have a setne or seteq and whether the true or
4348 // false val is the zero.
4349 bool ShouldNotVal = !TrueValC->isNullValue();
4350 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4351 Value *V = ICA;
4352 if (ShouldNotVal)
4353 V = InsertNewInstBefore(BinaryOperator::create(
4354 Instruction::Xor, V, ICA->getOperand(1)), SI);
4355 return ReplaceInstUsesWith(SI, V);
4356 }
Chris Lattner533bc492004-03-30 19:37:13 +00004357 }
Chris Lattner623fba12004-04-10 22:21:27 +00004358
4359 // See if we are selecting two values based on a comparison of the two values.
4360 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4361 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4362 // Transform (X == Y) ? X : Y -> Y
4363 if (SCI->getOpcode() == Instruction::SetEQ)
4364 return ReplaceInstUsesWith(SI, FalseVal);
4365 // Transform (X != Y) ? X : Y -> X
4366 if (SCI->getOpcode() == Instruction::SetNE)
4367 return ReplaceInstUsesWith(SI, TrueVal);
4368 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4369
4370 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4371 // Transform (X == Y) ? Y : X -> X
4372 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00004373 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004374 // Transform (X != Y) ? Y : X -> Y
4375 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00004376 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004377 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4378 }
4379 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004380
Chris Lattnera04c9042005-01-13 22:52:24 +00004381 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4382 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4383 if (TI->hasOneUse() && FI->hasOneUse()) {
4384 bool isInverse = false;
4385 Instruction *AddOp = 0, *SubOp = 0;
4386
Chris Lattner411336f2005-01-19 21:50:18 +00004387 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4388 if (TI->getOpcode() == FI->getOpcode())
4389 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4390 return IV;
4391
4392 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4393 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00004394 if (TI->getOpcode() == Instruction::Sub &&
4395 FI->getOpcode() == Instruction::Add) {
4396 AddOp = FI; SubOp = TI;
4397 } else if (FI->getOpcode() == Instruction::Sub &&
4398 TI->getOpcode() == Instruction::Add) {
4399 AddOp = TI; SubOp = FI;
4400 }
4401
4402 if (AddOp) {
4403 Value *OtherAddOp = 0;
4404 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4405 OtherAddOp = AddOp->getOperand(1);
4406 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4407 OtherAddOp = AddOp->getOperand(0);
4408 }
4409
4410 if (OtherAddOp) {
4411 // So at this point we know we have:
4412 // select C, (add X, Y), (sub X, ?)
4413 // We can do the transform profitably if either 'Y' = '?' or '?' is
4414 // a constant.
4415 if (SubOp->getOperand(1) == AddOp ||
4416 isa<Constant>(SubOp->getOperand(1))) {
4417 Value *NegVal;
4418 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4419 NegVal = ConstantExpr::getNeg(C);
4420 } else {
4421 NegVal = InsertNewInstBefore(
4422 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4423 }
4424
Chris Lattner51726c42005-01-14 17:35:12 +00004425 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004426 Value *NewFalseOp = NegVal;
4427 if (AddOp != TI)
4428 std::swap(NewTrueOp, NewFalseOp);
4429 Instruction *NewSel =
4430 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004431
Chris Lattnera04c9042005-01-13 22:52:24 +00004432 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004433 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004434 }
4435 }
4436 }
4437 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004438
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004439 // See if we can fold the select into one of our operands.
4440 if (SI.getType()->isInteger()) {
4441 // See the comment above GetSelectFoldableOperands for a description of the
4442 // transformation we are doing here.
4443 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4444 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4445 !isa<Constant>(FalseVal))
4446 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4447 unsigned OpToFold = 0;
4448 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4449 OpToFold = 1;
4450 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4451 OpToFold = 2;
4452 }
4453
4454 if (OpToFold) {
4455 Constant *C = GetSelectFoldableConstant(TVI);
4456 std::string Name = TVI->getName(); TVI->setName("");
4457 Instruction *NewSel =
4458 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4459 Name);
4460 InsertNewInstBefore(NewSel, SI);
4461 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4462 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4463 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4464 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4465 else {
4466 assert(0 && "Unknown instruction!!");
4467 }
4468 }
4469 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004470
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004471 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4472 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4473 !isa<Constant>(TrueVal))
4474 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4475 unsigned OpToFold = 0;
4476 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4477 OpToFold = 1;
4478 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4479 OpToFold = 2;
4480 }
4481
4482 if (OpToFold) {
4483 Constant *C = GetSelectFoldableConstant(FVI);
4484 std::string Name = FVI->getName(); FVI->setName("");
4485 Instruction *NewSel =
4486 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4487 Name);
4488 InsertNewInstBefore(NewSel, SI);
4489 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4490 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4491 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4492 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4493 else {
4494 assert(0 && "Unknown instruction!!");
4495 }
4496 }
4497 }
4498 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004499
4500 if (BinaryOperator::isNot(CondVal)) {
4501 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4502 SI.setOperand(1, FalseVal);
4503 SI.setOperand(2, TrueVal);
4504 return &SI;
4505 }
4506
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004507 return 0;
4508}
4509
4510
Chris Lattner970c33a2003-06-19 17:00:31 +00004511// CallInst simplification
4512//
4513Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00004514 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4515 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00004516 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4517 bool Changed = false;
4518
4519 // memmove/cpy/set of zero bytes is a noop.
4520 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4521 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4522
4523 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004524
Chris Lattner00648e12004-10-12 04:52:52 +00004525 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4526 if (CI->getRawValue() == 1) {
4527 // Replace the instruction with just byte operations. We would
4528 // transform other cases to loads/stores, but we don't know if
4529 // alignment is sufficient.
4530 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004531 }
4532
Chris Lattner00648e12004-10-12 04:52:52 +00004533 // If we have a memmove and the source operation is a constant global,
4534 // then the source and dest pointers can't alias, so we can change this
4535 // into a call to memcpy.
4536 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4537 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4538 if (GVSrc->isConstant()) {
4539 Module *M = CI.getParent()->getParent()->getParent();
4540 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4541 CI.getCalledFunction()->getFunctionType());
4542 CI.setOperand(0, MemCpy);
4543 Changed = true;
4544 }
4545
4546 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00004547 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4548 // If this stoppoint is at the same source location as the previous
4549 // stoppoint in the chain, it is not needed.
4550 if (DbgStopPointInst *PrevSPI =
4551 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4552 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4553 SPI->getColNo() == PrevSPI->getColNo()) {
4554 SPI->replaceAllUsesWith(PrevSPI);
4555 return EraseInstFromFunction(CI);
4556 }
Chris Lattner00648e12004-10-12 04:52:52 +00004557 }
4558
Chris Lattneraec3d942003-10-07 22:32:43 +00004559 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00004560}
4561
4562// InvokeInst simplification
4563//
4564Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004565 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004566}
4567
Chris Lattneraec3d942003-10-07 22:32:43 +00004568// visitCallSite - Improvements for call and invoke instructions.
4569//
4570Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004571 bool Changed = false;
4572
4573 // If the callee is a constexpr cast of a function, attempt to move the cast
4574 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004575 if (transformConstExprCastCall(CS)) return 0;
4576
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004577 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004578
Chris Lattner61d9d812005-05-13 07:09:09 +00004579 if (Function *CalleeF = dyn_cast<Function>(Callee))
4580 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4581 Instruction *OldCall = CS.getInstruction();
4582 // If the call and callee calling conventions don't match, this call must
4583 // be unreachable, as the call is undefined.
4584 new StoreInst(ConstantBool::True,
4585 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4586 if (!OldCall->use_empty())
4587 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4588 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4589 return EraseInstFromFunction(*OldCall);
4590 return 0;
4591 }
4592
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004593 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4594 // This instruction is not reachable, just remove it. We insert a store to
4595 // undef so that we know that this code is not reachable, despite the fact
4596 // that we can't modify the CFG here.
4597 new StoreInst(ConstantBool::True,
4598 UndefValue::get(PointerType::get(Type::BoolTy)),
4599 CS.getInstruction());
4600
4601 if (!CS.getInstruction()->use_empty())
4602 CS.getInstruction()->
4603 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4604
4605 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4606 // Don't break the CFG, insert a dummy cond branch.
4607 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4608 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004609 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004610 return EraseInstFromFunction(*CS.getInstruction());
4611 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004612
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004613 const PointerType *PTy = cast<PointerType>(Callee->getType());
4614 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4615 if (FTy->isVarArg()) {
4616 // See if we can optimize any arguments passed through the varargs area of
4617 // the call.
4618 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4619 E = CS.arg_end(); I != E; ++I)
4620 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4621 // If this cast does not effect the value passed through the varargs
4622 // area, we can eliminate the use of the cast.
4623 Value *Op = CI->getOperand(0);
4624 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4625 *I = Op;
4626 Changed = true;
4627 }
4628 }
4629 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004630
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004631 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004632}
4633
Chris Lattner970c33a2003-06-19 17:00:31 +00004634// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4635// attempt to move the cast to the arguments of the call/invoke.
4636//
4637bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4638 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4639 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004640 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004641 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004642 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004643 Instruction *Caller = CS.getInstruction();
4644
4645 // Okay, this is a cast from a function to a different type. Unless doing so
4646 // would cause a type conversion of one of our arguments, change this call to
4647 // be a direct call with arguments casted to the appropriate types.
4648 //
4649 const FunctionType *FT = Callee->getFunctionType();
4650 const Type *OldRetTy = Caller->getType();
4651
Chris Lattner1f7942f2004-01-14 06:06:08 +00004652 // Check to see if we are changing the return type...
4653 if (OldRetTy != FT->getReturnType()) {
4654 if (Callee->isExternal() &&
4655 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4656 !Caller->use_empty())
4657 return false; // Cannot transform this return value...
4658
4659 // If the callsite is an invoke instruction, and the return value is used by
4660 // a PHI node in a successor, we cannot change the return type of the call
4661 // because there is no place to put the cast instruction (without breaking
4662 // the critical edge). Bail out in this case.
4663 if (!Caller->use_empty())
4664 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4665 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4666 UI != E; ++UI)
4667 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4668 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004669 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004670 return false;
4671 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004672
4673 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4674 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004675
Chris Lattner970c33a2003-06-19 17:00:31 +00004676 CallSite::arg_iterator AI = CS.arg_begin();
4677 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4678 const Type *ParamTy = FT->getParamType(i);
4679 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004680 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004681 }
4682
4683 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4684 Callee->isExternal())
4685 return false; // Do not delete arguments unless we have a function body...
4686
4687 // Okay, we decided that this is a safe thing to do: go ahead and start
4688 // inserting cast instructions as necessary...
4689 std::vector<Value*> Args;
4690 Args.reserve(NumActualArgs);
4691
4692 AI = CS.arg_begin();
4693 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4694 const Type *ParamTy = FT->getParamType(i);
4695 if ((*AI)->getType() == ParamTy) {
4696 Args.push_back(*AI);
4697 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004698 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4699 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004700 }
4701 }
4702
4703 // If the function takes more arguments than the call was taking, add them
4704 // now...
4705 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4706 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4707
4708 // If we are removing arguments to the function, emit an obnoxious warning...
4709 if (FT->getNumParams() < NumActualArgs)
4710 if (!FT->isVarArg()) {
4711 std::cerr << "WARNING: While resolving call to function '"
4712 << Callee->getName() << "' arguments were dropped!\n";
4713 } else {
4714 // Add all of the arguments in their promoted form to the arg list...
4715 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4716 const Type *PTy = getPromotedType((*AI)->getType());
4717 if (PTy != (*AI)->getType()) {
4718 // Must promote to pass through va_arg area!
4719 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4720 InsertNewInstBefore(Cast, *Caller);
4721 Args.push_back(Cast);
4722 } else {
4723 Args.push_back(*AI);
4724 }
4725 }
4726 }
4727
4728 if (FT->getReturnType() == Type::VoidTy)
4729 Caller->setName(""); // Void type should not have a name...
4730
4731 Instruction *NC;
4732 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004733 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004734 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004735 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004736 } else {
4737 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004738 if (cast<CallInst>(Caller)->isTailCall())
4739 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004740 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004741 }
4742
4743 // Insert a cast of the return type as necessary...
4744 Value *NV = NC;
4745 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4746 if (NV->getType() != Type::VoidTy) {
4747 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004748
4749 // If this is an invoke instruction, we should insert it after the first
4750 // non-phi, instruction in the normal successor block.
4751 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4752 BasicBlock::iterator I = II->getNormalDest()->begin();
4753 while (isa<PHINode>(I)) ++I;
4754 InsertNewInstBefore(NC, *I);
4755 } else {
4756 // Otherwise, it's a call, just insert cast right after the call instr
4757 InsertNewInstBefore(NC, *Caller);
4758 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004759 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004760 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004761 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004762 }
4763 }
4764
4765 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4766 Caller->replaceAllUsesWith(NV);
4767 Caller->getParent()->getInstList().erase(Caller);
4768 removeFromWorkList(Caller);
4769 return true;
4770}
4771
4772
Chris Lattner7515cab2004-11-14 19:13:23 +00004773// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4774// operator and they all are only used by the PHI, PHI together their
4775// inputs, and do the operation once, to the result of the PHI.
4776Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4777 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4778
4779 // Scan the instruction, looking for input operations that can be folded away.
4780 // If all input operands to the phi are the same instruction (e.g. a cast from
4781 // the same type or "+42") we can pull the operation through the PHI, reducing
4782 // code size and simplifying code.
4783 Constant *ConstantOp = 0;
4784 const Type *CastSrcTy = 0;
4785 if (isa<CastInst>(FirstInst)) {
4786 CastSrcTy = FirstInst->getOperand(0)->getType();
4787 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4788 // Can fold binop or shift if the RHS is a constant.
4789 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4790 if (ConstantOp == 0) return 0;
4791 } else {
4792 return 0; // Cannot fold this operation.
4793 }
4794
4795 // Check to see if all arguments are the same operation.
4796 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4797 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4798 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4799 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4800 return 0;
4801 if (CastSrcTy) {
4802 if (I->getOperand(0)->getType() != CastSrcTy)
4803 return 0; // Cast operation must match.
4804 } else if (I->getOperand(1) != ConstantOp) {
4805 return 0;
4806 }
4807 }
4808
4809 // Okay, they are all the same operation. Create a new PHI node of the
4810 // correct type, and PHI together all of the LHS's of the instructions.
4811 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4812 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004813 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004814
4815 Value *InVal = FirstInst->getOperand(0);
4816 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004817
4818 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004819 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4820 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4821 if (NewInVal != InVal)
4822 InVal = 0;
4823 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4824 }
4825
4826 Value *PhiVal;
4827 if (InVal) {
4828 // The new PHI unions all of the same values together. This is really
4829 // common, so we handle it intelligently here for compile-time speed.
4830 PhiVal = InVal;
4831 delete NewPN;
4832 } else {
4833 InsertNewInstBefore(NewPN, PN);
4834 PhiVal = NewPN;
4835 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004836
Chris Lattner7515cab2004-11-14 19:13:23 +00004837 // Insert and return the new operation.
4838 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004839 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004840 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004841 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004842 else
4843 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004844 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004845}
Chris Lattner48a44f72002-05-02 17:06:02 +00004846
Chris Lattner71536432005-01-17 05:10:15 +00004847/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4848/// that is dead.
4849static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4850 if (PN->use_empty()) return true;
4851 if (!PN->hasOneUse()) return false;
4852
4853 // Remember this node, and if we find the cycle, return.
4854 if (!PotentiallyDeadPHIs.insert(PN).second)
4855 return true;
4856
4857 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4858 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004859
Chris Lattner71536432005-01-17 05:10:15 +00004860 return false;
4861}
4862
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004863// PHINode simplification
4864//
Chris Lattner113f4f42002-06-25 16:13:24 +00004865Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00004866 if (Value *V = PN.hasConstantValue())
4867 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00004868
4869 // If the only user of this instruction is a cast instruction, and all of the
4870 // incoming values are constants, change this PHI to merge together the casted
4871 // constants.
4872 if (PN.hasOneUse())
4873 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4874 if (CI->getType() != PN.getType()) { // noop casts will be folded
4875 bool AllConstant = true;
4876 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4877 if (!isa<Constant>(PN.getIncomingValue(i))) {
4878 AllConstant = false;
4879 break;
4880 }
4881 if (AllConstant) {
4882 // Make a new PHI with all casted values.
4883 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4884 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4885 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4886 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4887 PN.getIncomingBlock(i));
4888 }
4889
4890 // Update the cast instruction.
4891 CI->setOperand(0, New);
4892 WorkList.push_back(CI); // revisit the cast instruction to fold.
4893 WorkList.push_back(New); // Make sure to revisit the new Phi
4894 return &PN; // PN is now dead!
4895 }
4896 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004897
4898 // If all PHI operands are the same operation, pull them through the PHI,
4899 // reducing code size.
4900 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4901 PN.getIncomingValue(0)->hasOneUse())
4902 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4903 return Result;
4904
Chris Lattner71536432005-01-17 05:10:15 +00004905 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4906 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4907 // PHI)... break the cycle.
4908 if (PN.hasOneUse())
4909 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4910 std::set<PHINode*> PotentiallyDeadPHIs;
4911 PotentiallyDeadPHIs.insert(&PN);
4912 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4913 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4914 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004915
Chris Lattner91daeb52003-12-19 05:58:40 +00004916 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004917}
4918
Chris Lattner69193f92004-04-05 01:30:19 +00004919static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4920 Instruction *InsertPoint,
4921 InstCombiner *IC) {
4922 unsigned PS = IC->getTargetData().getPointerSize();
4923 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004924 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4925 // We must insert a cast to ensure we sign-extend.
4926 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4927 V->getName()), *InsertPoint);
4928 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4929 *InsertPoint);
4930}
4931
Chris Lattner48a44f72002-05-02 17:06:02 +00004932
Chris Lattner113f4f42002-06-25 16:13:24 +00004933Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004934 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004935 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004936 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004937 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004938 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004939
Chris Lattner81a7a232004-10-16 18:11:37 +00004940 if (isa<UndefValue>(GEP.getOperand(0)))
4941 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4942
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004943 bool HasZeroPointerIndex = false;
4944 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4945 HasZeroPointerIndex = C->isNullValue();
4946
4947 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004948 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004949
Chris Lattner69193f92004-04-05 01:30:19 +00004950 // Eliminate unneeded casts for indices.
4951 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004952 gep_type_iterator GTI = gep_type_begin(GEP);
4953 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4954 if (isa<SequentialType>(*GTI)) {
4955 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4956 Value *Src = CI->getOperand(0);
4957 const Type *SrcTy = Src->getType();
4958 const Type *DestTy = CI->getType();
4959 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004960 if (SrcTy->getPrimitiveSizeInBits() ==
4961 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004962 // We can always eliminate a cast from ulong or long to the other.
4963 // We can always eliminate a cast from uint to int or the other on
4964 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004965 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00004966 MadeChange = true;
4967 GEP.setOperand(i, Src);
4968 }
4969 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4970 SrcTy->getPrimitiveSize() == 4) {
4971 // We can always eliminate a cast from int to [u]long. We can
4972 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4973 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004974 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004975 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004976 MadeChange = true;
4977 GEP.setOperand(i, Src);
4978 }
Chris Lattner69193f92004-04-05 01:30:19 +00004979 }
4980 }
4981 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004982 // If we are using a wider index than needed for this platform, shrink it
4983 // to what we need. If the incoming value needs a cast instruction,
4984 // insert it. This explicit cast can make subsequent optimizations more
4985 // obvious.
4986 Value *Op = GEP.getOperand(i);
4987 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004988 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004989 GEP.setOperand(i, ConstantExpr::getCast(C,
4990 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004991 MadeChange = true;
4992 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004993 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4994 Op->getName()), GEP);
4995 GEP.setOperand(i, Op);
4996 MadeChange = true;
4997 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004998
4999 // If this is a constant idx, make sure to canonicalize it to be a signed
5000 // operand, otherwise CSE and other optimizations are pessimized.
5001 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5002 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5003 CUI->getType()->getSignedVersion()));
5004 MadeChange = true;
5005 }
Chris Lattner69193f92004-04-05 01:30:19 +00005006 }
5007 if (MadeChange) return &GEP;
5008
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005009 // Combine Indices - If the source pointer to this getelementptr instruction
5010 // is a getelementptr instruction, combine the indices of the two
5011 // getelementptr instructions into a single instruction.
5012 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005013 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005014 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005015 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005016
5017 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005018 // Note that if our source is a gep chain itself that we wait for that
5019 // chain to be resolved before we perform this transformation. This
5020 // avoids us creating a TON of code in some cases.
5021 //
5022 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5023 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5024 return 0; // Wait until our source is folded to completion.
5025
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005026 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005027
5028 // Find out whether the last index in the source GEP is a sequential idx.
5029 bool EndsWithSequential = false;
5030 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5031 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005032 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005033
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005034 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005035 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005036 // Replace: gep (gep %P, long B), long A, ...
5037 // With: T = long A+B; gep %P, T, ...
5038 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005039 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005040 if (SO1 == Constant::getNullValue(SO1->getType())) {
5041 Sum = GO1;
5042 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5043 Sum = SO1;
5044 } else {
5045 // If they aren't the same type, convert both to an integer of the
5046 // target's pointer size.
5047 if (SO1->getType() != GO1->getType()) {
5048 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5049 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5050 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5051 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5052 } else {
5053 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005054 if (SO1->getType()->getPrimitiveSize() == PS) {
5055 // Convert GO1 to SO1's type.
5056 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5057
5058 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5059 // Convert SO1 to GO1's type.
5060 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5061 } else {
5062 const Type *PT = TD->getIntPtrType();
5063 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5064 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5065 }
5066 }
5067 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005068 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5069 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5070 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005071 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5072 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005073 }
Chris Lattner69193f92004-04-05 01:30:19 +00005074 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005075
5076 // Recycle the GEP we already have if possible.
5077 if (SrcGEPOperands.size() == 2) {
5078 GEP.setOperand(0, SrcGEPOperands[0]);
5079 GEP.setOperand(1, Sum);
5080 return &GEP;
5081 } else {
5082 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5083 SrcGEPOperands.end()-1);
5084 Indices.push_back(Sum);
5085 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5086 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005087 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005088 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005089 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005090 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005091 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5092 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005093 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5094 }
5095
5096 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005097 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005098
Chris Lattner5f667a62004-05-07 22:09:22 +00005099 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005100 // GEP of global variable. If all of the indices for this GEP are
5101 // constants, we can promote this to a constexpr instead of an instruction.
5102
5103 // Scan for nonconstants...
5104 std::vector<Constant*> Indices;
5105 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5106 for (; I != E && isa<Constant>(*I); ++I)
5107 Indices.push_back(cast<Constant>(*I));
5108
5109 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005110 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005111
5112 // Replace all uses of the GEP with the new constexpr...
5113 return ReplaceInstUsesWith(GEP, CE);
5114 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005115 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5116 if (!isa<PointerType>(X->getType())) {
5117 // Not interesting. Source pointer must be a cast from pointer.
5118 } else if (HasZeroPointerIndex) {
5119 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5120 // into : GEP [10 x ubyte]* X, long 0, ...
5121 //
5122 // This occurs when the program declares an array extern like "int X[];"
5123 //
5124 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5125 const PointerType *XTy = cast<PointerType>(X->getType());
5126 if (const ArrayType *XATy =
5127 dyn_cast<ArrayType>(XTy->getElementType()))
5128 if (const ArrayType *CATy =
5129 dyn_cast<ArrayType>(CPTy->getElementType()))
5130 if (CATy->getElementType() == XATy->getElementType()) {
5131 // At this point, we know that the cast source type is a pointer
5132 // to an array of the same type as the destination pointer
5133 // array. Because the array type is never stepped over (there
5134 // is a leading zero) we can fold the cast into this GEP.
5135 GEP.setOperand(0, X);
5136 return &GEP;
5137 }
5138 } else if (GEP.getNumOperands() == 2) {
5139 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005140 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5141 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005142 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5143 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5144 if (isa<ArrayType>(SrcElTy) &&
5145 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5146 TD->getTypeSize(ResElTy)) {
5147 Value *V = InsertNewInstBefore(
5148 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5149 GEP.getOperand(1), GEP.getName()), GEP);
5150 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005151 }
Chris Lattner2a893292005-09-13 18:36:04 +00005152
5153 // Transform things like:
5154 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5155 // (where tmp = 8*tmp2) into:
5156 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5157
5158 if (isa<ArrayType>(SrcElTy) &&
5159 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5160 uint64_t ArrayEltSize =
5161 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5162
5163 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5164 // allow either a mul, shift, or constant here.
5165 Value *NewIdx = 0;
5166 ConstantInt *Scale = 0;
5167 if (ArrayEltSize == 1) {
5168 NewIdx = GEP.getOperand(1);
5169 Scale = ConstantInt::get(NewIdx->getType(), 1);
5170 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005171 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005172 Scale = CI;
5173 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5174 if (Inst->getOpcode() == Instruction::Shl &&
5175 isa<ConstantInt>(Inst->getOperand(1))) {
5176 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5177 if (Inst->getType()->isSigned())
5178 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5179 else
5180 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5181 NewIdx = Inst->getOperand(0);
5182 } else if (Inst->getOpcode() == Instruction::Mul &&
5183 isa<ConstantInt>(Inst->getOperand(1))) {
5184 Scale = cast<ConstantInt>(Inst->getOperand(1));
5185 NewIdx = Inst->getOperand(0);
5186 }
5187 }
5188
5189 // If the index will be to exactly the right offset with the scale taken
5190 // out, perform the transformation.
5191 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5192 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5193 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005194 (int64_t)C->getRawValue() /
5195 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005196 else
5197 Scale = ConstantUInt::get(Scale->getType(),
5198 Scale->getRawValue() / ArrayEltSize);
5199 if (Scale->getRawValue() != 1) {
5200 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5201 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5202 NewIdx = InsertNewInstBefore(Sc, GEP);
5203 }
5204
5205 // Insert the new GEP instruction.
5206 Instruction *Idx =
5207 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5208 NewIdx, GEP.getName());
5209 Idx = InsertNewInstBefore(Idx, GEP);
5210 return new CastInst(Idx, GEP.getType());
5211 }
5212 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005213 }
Chris Lattnerca081252001-12-14 16:52:21 +00005214 }
5215
Chris Lattnerca081252001-12-14 16:52:21 +00005216 return 0;
5217}
5218
Chris Lattner1085bdf2002-11-04 16:18:53 +00005219Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5220 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5221 if (AI.isArrayAllocation()) // Check C != 1
5222 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5223 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005224 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005225
5226 // Create and insert the replacement instruction...
5227 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00005228 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005229 else {
5230 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00005231 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005232 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005233
5234 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005235
Chris Lattner1085bdf2002-11-04 16:18:53 +00005236 // Scan to the end of the allocation instructions, to skip over a block of
5237 // allocas if possible...
5238 //
5239 BasicBlock::iterator It = New;
5240 while (isa<AllocationInst>(*It)) ++It;
5241
5242 // Now that I is pointing to the first non-allocation-inst in the block,
5243 // insert our getelementptr instruction...
5244 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005245 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5246 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5247 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005248
5249 // Now make everything use the getelementptr instead of the original
5250 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005251 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005252 } else if (isa<UndefValue>(AI.getArraySize())) {
5253 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005254 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005255
5256 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5257 // Note that we only do this for alloca's, because malloc should allocate and
5258 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005259 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005260 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005261 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5262
Chris Lattner1085bdf2002-11-04 16:18:53 +00005263 return 0;
5264}
5265
Chris Lattner8427bff2003-12-07 01:24:23 +00005266Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5267 Value *Op = FI.getOperand(0);
5268
5269 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5270 if (CastInst *CI = dyn_cast<CastInst>(Op))
5271 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5272 FI.setOperand(0, CI->getOperand(0));
5273 return &FI;
5274 }
5275
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005276 // free undef -> unreachable.
5277 if (isa<UndefValue>(Op)) {
5278 // Insert a new store to null because we cannot modify the CFG here.
5279 new StoreInst(ConstantBool::True,
5280 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5281 return EraseInstFromFunction(FI);
5282 }
5283
Chris Lattnerf3a36602004-02-28 04:57:37 +00005284 // If we have 'free null' delete the instruction. This can happen in stl code
5285 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005286 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005287 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005288
Chris Lattner8427bff2003-12-07 01:24:23 +00005289 return 0;
5290}
5291
5292
Chris Lattner72684fe2005-01-31 05:51:45 +00005293/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005294static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5295 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005296 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005297
5298 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005299 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005300 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005301
5302 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5303 // If the source is an array, the code below will not succeed. Check to
5304 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5305 // constants.
5306 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5307 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5308 if (ASrcTy->getNumElements() != 0) {
5309 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5310 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5311 SrcTy = cast<PointerType>(CastOp->getType());
5312 SrcPTy = SrcTy->getElementType();
5313 }
5314
5315 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005316 // Do not allow turning this into a load of an integer, which is then
5317 // casted to a pointer, this pessimizes pointer analysis a lot.
5318 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005319 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005320 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005321
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005322 // Okay, we are casting from one integer or pointer type to another of
5323 // the same size. Instead of casting the pointer before the load, cast
5324 // the result of the loaded value.
5325 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5326 CI->getName(),
5327 LI.isVolatile()),LI);
5328 // Now cast the result of the load.
5329 return new CastInst(NewLoad, LI.getType());
5330 }
Chris Lattner35e24772004-07-13 01:49:43 +00005331 }
5332 }
5333 return 0;
5334}
5335
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005336/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00005337/// from this value cannot trap. If it is not obviously safe to load from the
5338/// specified pointer, we do a quick local scan of the basic block containing
5339/// ScanFrom, to determine if the address is already accessed.
5340static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5341 // If it is an alloca or global variable, it is always safe to load from.
5342 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5343
5344 // Otherwise, be a little bit agressive by scanning the local block where we
5345 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005346 // from/to. If so, the previous load or store would have already trapped,
5347 // so there is no harm doing an extra load (also, CSE will later eliminate
5348 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00005349 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5350
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005351 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00005352 --BBI;
5353
5354 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5355 if (LI->getOperand(0) == V) return true;
5356 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5357 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005358
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005359 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005360 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005361}
5362
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005363Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5364 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005365
Chris Lattnera9d84e32005-05-01 04:24:53 +00005366 // load (cast X) --> cast (load X) iff safe
5367 if (CastInst *CI = dyn_cast<CastInst>(Op))
5368 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5369 return Res;
5370
5371 // None of the following transforms are legal for volatile loads.
5372 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005373
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005374 if (&LI.getParent()->front() != &LI) {
5375 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005376 // If the instruction immediately before this is a store to the same
5377 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005378 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5379 if (SI->getOperand(1) == LI.getOperand(0))
5380 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005381 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5382 if (LIB->getOperand(0) == LI.getOperand(0))
5383 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005384 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005385
5386 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5387 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5388 isa<UndefValue>(GEPI->getOperand(0))) {
5389 // Insert a new store to null instruction before the load to indicate
5390 // that this code is not reachable. We do this instead of inserting
5391 // an unreachable instruction directly because we cannot modify the
5392 // CFG.
5393 new StoreInst(UndefValue::get(LI.getType()),
5394 Constant::getNullValue(Op->getType()), &LI);
5395 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5396 }
5397
Chris Lattner81a7a232004-10-16 18:11:37 +00005398 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005399 // load null/undef -> undef
5400 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005401 // Insert a new store to null instruction before the load to indicate that
5402 // this code is not reachable. We do this instead of inserting an
5403 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005404 new StoreInst(UndefValue::get(LI.getType()),
5405 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005406 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005407 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005408
Chris Lattner81a7a232004-10-16 18:11:37 +00005409 // Instcombine load (constant global) into the value loaded.
5410 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5411 if (GV->isConstant() && !GV->isExternal())
5412 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005413
Chris Lattner81a7a232004-10-16 18:11:37 +00005414 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5415 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5416 if (CE->getOpcode() == Instruction::GetElementPtr) {
5417 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5418 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00005419 if (Constant *V =
5420 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00005421 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005422 if (CE->getOperand(0)->isNullValue()) {
5423 // Insert a new store to null instruction before the load to indicate
5424 // that this code is not reachable. We do this instead of inserting
5425 // an unreachable instruction directly because we cannot modify the
5426 // CFG.
5427 new StoreInst(UndefValue::get(LI.getType()),
5428 Constant::getNullValue(Op->getType()), &LI);
5429 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5430 }
5431
Chris Lattner81a7a232004-10-16 18:11:37 +00005432 } else if (CE->getOpcode() == Instruction::Cast) {
5433 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5434 return Res;
5435 }
5436 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005437
Chris Lattnera9d84e32005-05-01 04:24:53 +00005438 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005439 // Change select and PHI nodes to select values instead of addresses: this
5440 // helps alias analysis out a lot, allows many others simplifications, and
5441 // exposes redundancy in the code.
5442 //
5443 // Note that we cannot do the transformation unless we know that the
5444 // introduced loads cannot trap! Something like this is valid as long as
5445 // the condition is always false: load (select bool %C, int* null, int* %G),
5446 // but it would not be valid if we transformed it to load from null
5447 // unconditionally.
5448 //
5449 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5450 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005451 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5452 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005453 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005454 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005455 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005456 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005457 return new SelectInst(SI->getCondition(), V1, V2);
5458 }
5459
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005460 // load (select (cond, null, P)) -> load P
5461 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5462 if (C->isNullValue()) {
5463 LI.setOperand(0, SI->getOperand(2));
5464 return &LI;
5465 }
5466
5467 // load (select (cond, P, null)) -> load P
5468 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5469 if (C->isNullValue()) {
5470 LI.setOperand(0, SI->getOperand(1));
5471 return &LI;
5472 }
5473
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005474 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5475 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005476 bool Safe = PN->getParent() == LI.getParent();
5477
5478 // Scan all of the instructions between the PHI and the load to make
5479 // sure there are no instructions that might possibly alter the value
5480 // loaded from the PHI.
5481 if (Safe) {
5482 BasicBlock::iterator I = &LI;
5483 for (--I; !isa<PHINode>(I); --I)
5484 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5485 Safe = false;
5486 break;
5487 }
5488 }
5489
5490 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005491 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005492 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005493 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005494
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005495 if (Safe) {
5496 // Create the PHI.
5497 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5498 InsertNewInstBefore(NewPN, *PN);
5499 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5500
5501 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5502 BasicBlock *BB = PN->getIncomingBlock(i);
5503 Value *&TheLoad = LoadMap[BB];
5504 if (TheLoad == 0) {
5505 Value *InVal = PN->getIncomingValue(i);
5506 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5507 InVal->getName()+".val"),
5508 *BB->getTerminator());
5509 }
5510 NewPN->addIncoming(TheLoad, BB);
5511 }
5512 return ReplaceInstUsesWith(LI, NewPN);
5513 }
5514 }
5515 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005516 return 0;
5517}
5518
Chris Lattner72684fe2005-01-31 05:51:45 +00005519/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5520/// when possible.
5521static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5522 User *CI = cast<User>(SI.getOperand(1));
5523 Value *CastOp = CI->getOperand(0);
5524
5525 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5526 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5527 const Type *SrcPTy = SrcTy->getElementType();
5528
5529 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5530 // If the source is an array, the code below will not succeed. Check to
5531 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5532 // constants.
5533 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5534 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5535 if (ASrcTy->getNumElements() != 0) {
5536 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5537 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5538 SrcTy = cast<PointerType>(CastOp->getType());
5539 SrcPTy = SrcTy->getElementType();
5540 }
5541
5542 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005543 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005544 IC.getTargetData().getTypeSize(DestPTy)) {
5545
5546 // Okay, we are casting from one integer or pointer type to another of
5547 // the same size. Instead of casting the pointer before the store, cast
5548 // the value to be stored.
5549 Value *NewCast;
5550 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5551 NewCast = ConstantExpr::getCast(C, SrcPTy);
5552 else
5553 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5554 SrcPTy,
5555 SI.getOperand(0)->getName()+".c"), SI);
5556
5557 return new StoreInst(NewCast, CastOp);
5558 }
5559 }
5560 }
5561 return 0;
5562}
5563
Chris Lattner31f486c2005-01-31 05:36:43 +00005564Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5565 Value *Val = SI.getOperand(0);
5566 Value *Ptr = SI.getOperand(1);
5567
5568 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5569 removeFromWorkList(&SI);
5570 SI.eraseFromParent();
5571 ++NumCombined;
5572 return 0;
5573 }
5574
5575 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5576
5577 // store X, null -> turns into 'unreachable' in SimplifyCFG
5578 if (isa<ConstantPointerNull>(Ptr)) {
5579 if (!isa<UndefValue>(Val)) {
5580 SI.setOperand(0, UndefValue::get(Val->getType()));
5581 if (Instruction *U = dyn_cast<Instruction>(Val))
5582 WorkList.push_back(U); // Dropped a use.
5583 ++NumCombined;
5584 }
5585 return 0; // Do not modify these!
5586 }
5587
5588 // store undef, Ptr -> noop
5589 if (isa<UndefValue>(Val)) {
5590 removeFromWorkList(&SI);
5591 SI.eraseFromParent();
5592 ++NumCombined;
5593 return 0;
5594 }
5595
Chris Lattner72684fe2005-01-31 05:51:45 +00005596 // If the pointer destination is a cast, see if we can fold the cast into the
5597 // source instead.
5598 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5599 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5600 return Res;
5601 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5602 if (CE->getOpcode() == Instruction::Cast)
5603 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5604 return Res;
5605
Chris Lattner219175c2005-09-12 23:23:25 +00005606
5607 // If this store is the last instruction in the basic block, and if the block
5608 // ends with an unconditional branch, try to move it to the successor block.
5609 BasicBlock::iterator BBI = &SI; ++BBI;
5610 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5611 if (BI->isUnconditional()) {
5612 // Check to see if the successor block has exactly two incoming edges. If
5613 // so, see if the other predecessor contains a store to the same location.
5614 // if so, insert a PHI node (if needed) and move the stores down.
5615 BasicBlock *Dest = BI->getSuccessor(0);
5616
5617 pred_iterator PI = pred_begin(Dest);
5618 BasicBlock *Other = 0;
5619 if (*PI != BI->getParent())
5620 Other = *PI;
5621 ++PI;
5622 if (PI != pred_end(Dest)) {
5623 if (*PI != BI->getParent())
5624 if (Other)
5625 Other = 0;
5626 else
5627 Other = *PI;
5628 if (++PI != pred_end(Dest))
5629 Other = 0;
5630 }
5631 if (Other) { // If only one other pred...
5632 BBI = Other->getTerminator();
5633 // Make sure this other block ends in an unconditional branch and that
5634 // there is an instruction before the branch.
5635 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5636 BBI != Other->begin()) {
5637 --BBI;
5638 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5639
5640 // If this instruction is a store to the same location.
5641 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5642 // Okay, we know we can perform this transformation. Insert a PHI
5643 // node now if we need it.
5644 Value *MergedVal = OtherStore->getOperand(0);
5645 if (MergedVal != SI.getOperand(0)) {
5646 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5647 PN->reserveOperandSpace(2);
5648 PN->addIncoming(SI.getOperand(0), SI.getParent());
5649 PN->addIncoming(OtherStore->getOperand(0), Other);
5650 MergedVal = InsertNewInstBefore(PN, Dest->front());
5651 }
5652
5653 // Advance to a place where it is safe to insert the new store and
5654 // insert it.
5655 BBI = Dest->begin();
5656 while (isa<PHINode>(BBI)) ++BBI;
5657 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5658 OtherStore->isVolatile()), *BBI);
5659
5660 // Nuke the old stores.
5661 removeFromWorkList(&SI);
5662 removeFromWorkList(OtherStore);
5663 SI.eraseFromParent();
5664 OtherStore->eraseFromParent();
5665 ++NumCombined;
5666 return 0;
5667 }
5668 }
5669 }
5670 }
5671
Chris Lattner31f486c2005-01-31 05:36:43 +00005672 return 0;
5673}
5674
5675
Chris Lattner9eef8a72003-06-04 04:46:00 +00005676Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5677 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005678 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005679 BasicBlock *TrueDest;
5680 BasicBlock *FalseDest;
5681 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5682 !isa<Constant>(X)) {
5683 // Swap Destinations and condition...
5684 BI.setCondition(X);
5685 BI.setSuccessor(0, FalseDest);
5686 BI.setSuccessor(1, TrueDest);
5687 return &BI;
5688 }
5689
5690 // Cannonicalize setne -> seteq
5691 Instruction::BinaryOps Op; Value *Y;
5692 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5693 TrueDest, FalseDest)))
5694 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5695 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5696 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5697 std::string Name = I->getName(); I->setName("");
5698 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5699 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005700 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005701 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005702 BI.setSuccessor(0, FalseDest);
5703 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005704 removeFromWorkList(I);
5705 I->getParent()->getInstList().erase(I);
5706 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005707 return &BI;
5708 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005709
Chris Lattner9eef8a72003-06-04 04:46:00 +00005710 return 0;
5711}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005712
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005713Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5714 Value *Cond = SI.getCondition();
5715 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5716 if (I->getOpcode() == Instruction::Add)
5717 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5718 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5719 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005720 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005721 AddRHS));
5722 SI.setOperand(0, I->getOperand(0));
5723 WorkList.push_back(I);
5724 return &SI;
5725 }
5726 }
5727 return 0;
5728}
5729
Chris Lattner99f48c62002-09-02 04:59:56 +00005730void InstCombiner::removeFromWorkList(Instruction *I) {
5731 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5732 WorkList.end());
5733}
5734
Chris Lattner39c98bb2004-12-08 23:43:58 +00005735
5736/// TryToSinkInstruction - Try to move the specified instruction from its
5737/// current block into the beginning of DestBlock, which can only happen if it's
5738/// safe to move the instruction past all of the instructions between it and the
5739/// end of its block.
5740static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5741 assert(I->hasOneUse() && "Invariants didn't hold!");
5742
Chris Lattnerc4f67e62005-10-27 17:13:11 +00005743 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5744 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005745
Chris Lattner39c98bb2004-12-08 23:43:58 +00005746 // Do not sink alloca instructions out of the entry block.
5747 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5748 return false;
5749
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005750 // We can only sink load instructions if there is nothing between the load and
5751 // the end of block that could change the value.
5752 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005753 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5754 Scan != E; ++Scan)
5755 if (Scan->mayWriteToMemory())
5756 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005757 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005758
5759 BasicBlock::iterator InsertPos = DestBlock->begin();
5760 while (isa<PHINode>(InsertPos)) ++InsertPos;
5761
Chris Lattner9f269e42005-08-08 19:11:57 +00005762 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005763 ++NumSunkInst;
5764 return true;
5765}
5766
Chris Lattner113f4f42002-06-25 16:13:24 +00005767bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005768 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005769 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005770
Chris Lattner4ed40f72005-07-07 20:40:38 +00005771 {
5772 // Populate the worklist with the reachable instructions.
5773 std::set<BasicBlock*> Visited;
5774 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5775 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5776 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5777 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005778
Chris Lattner4ed40f72005-07-07 20:40:38 +00005779 // Do a quick scan over the function. If we find any blocks that are
5780 // unreachable, remove any instructions inside of them. This prevents
5781 // the instcombine code from having to deal with some bad special cases.
5782 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5783 if (!Visited.count(BB)) {
5784 Instruction *Term = BB->getTerminator();
5785 while (Term != BB->begin()) { // Remove instrs bottom-up
5786 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005787
Chris Lattner4ed40f72005-07-07 20:40:38 +00005788 DEBUG(std::cerr << "IC: DCE: " << *I);
5789 ++NumDeadInst;
5790
5791 if (!I->use_empty())
5792 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5793 I->eraseFromParent();
5794 }
5795 }
5796 }
Chris Lattnerca081252001-12-14 16:52:21 +00005797
5798 while (!WorkList.empty()) {
5799 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5800 WorkList.pop_back();
5801
Misha Brukman632df282002-10-29 23:06:16 +00005802 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005803 // Check to see if we can DIE the instruction...
5804 if (isInstructionTriviallyDead(I)) {
5805 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005806 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005807 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005808 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005809
Chris Lattnercd517ff2005-01-28 19:32:01 +00005810 DEBUG(std::cerr << "IC: DCE: " << *I);
5811
5812 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005813 removeFromWorkList(I);
5814 continue;
5815 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005816
Misha Brukman632df282002-10-29 23:06:16 +00005817 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005818 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005819 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005820 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005821 cast<Constant>(Ptr)->isNullValue() &&
5822 !isa<ConstantPointerNull>(C) &&
5823 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005824 // If this is a constant expr gep that is effectively computing an
5825 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5826 bool isFoldableGEP = true;
5827 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5828 if (!isa<ConstantInt>(I->getOperand(i)))
5829 isFoldableGEP = false;
5830 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005831 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005832 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5833 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005834 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005835 C = ConstantExpr::getCast(C, I->getType());
5836 }
5837 }
5838
Chris Lattnercd517ff2005-01-28 19:32:01 +00005839 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5840
Chris Lattner99f48c62002-09-02 04:59:56 +00005841 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005842 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005843 ReplaceInstUsesWith(*I, C);
5844
Chris Lattner99f48c62002-09-02 04:59:56 +00005845 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005846 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005847 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005848 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005849 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005850
Chris Lattner39c98bb2004-12-08 23:43:58 +00005851 // See if we can trivially sink this instruction to a successor basic block.
5852 if (I->hasOneUse()) {
5853 BasicBlock *BB = I->getParent();
5854 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5855 if (UserParent != BB) {
5856 bool UserIsSuccessor = false;
5857 // See if the user is one of our successors.
5858 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5859 if (*SI == UserParent) {
5860 UserIsSuccessor = true;
5861 break;
5862 }
5863
5864 // If the user is one of our immediate successors, and if that successor
5865 // only has us as a predecessors (we'd have to split the critical edge
5866 // otherwise), we can keep going.
5867 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5868 next(pred_begin(UserParent)) == pred_end(UserParent))
5869 // Okay, the CFG is simple enough, try to sink this instruction.
5870 Changed |= TryToSinkInstruction(I, UserParent);
5871 }
5872 }
5873
Chris Lattnerca081252001-12-14 16:52:21 +00005874 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005875 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005876 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005877 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005878 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005879 DEBUG(std::cerr << "IC: Old = " << *I
5880 << " New = " << *Result);
5881
Chris Lattner396dbfe2004-06-09 05:08:07 +00005882 // Everything uses the new instruction now.
5883 I->replaceAllUsesWith(Result);
5884
5885 // Push the new instruction and any users onto the worklist.
5886 WorkList.push_back(Result);
5887 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005888
5889 // Move the name to the new instruction first...
5890 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005891 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005892
5893 // Insert the new instruction into the basic block...
5894 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005895 BasicBlock::iterator InsertPos = I;
5896
5897 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5898 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5899 ++InsertPos;
5900
5901 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005902
Chris Lattner63d75af2004-05-01 23:27:23 +00005903 // Make sure that we reprocess all operands now that we reduced their
5904 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005905 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5906 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5907 WorkList.push_back(OpI);
5908
Chris Lattner396dbfe2004-06-09 05:08:07 +00005909 // Instructions can end up on the worklist more than once. Make sure
5910 // we do not process an instruction that has been deleted.
5911 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005912
5913 // Erase the old instruction.
5914 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005915 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005916 DEBUG(std::cerr << "IC: MOD = " << *I);
5917
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005918 // If the instruction was modified, it's possible that it is now dead.
5919 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005920 if (isInstructionTriviallyDead(I)) {
5921 // Make sure we process all operands now that we are reducing their
5922 // use counts.
5923 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5924 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5925 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005926
Chris Lattner63d75af2004-05-01 23:27:23 +00005927 // Instructions may end up in the worklist more than once. Erase all
5928 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005929 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005930 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005931 } else {
5932 WorkList.push_back(Result);
5933 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005934 }
Chris Lattner053c0932002-05-14 15:24:07 +00005935 }
Chris Lattner260ab202002-04-18 17:39:14 +00005936 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005937 }
5938 }
5939
Chris Lattner260ab202002-04-18 17:39:14 +00005940 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005941}
5942
Brian Gaeke38b79e82004-07-27 17:43:21 +00005943FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005944 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005945}
Brian Gaeke960707c2003-11-11 22:41:34 +00005946