blob: adafccddf003a9604934a2b5b3d5db6b82e17c34 [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.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000392static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask,
393 unsigned Depth = 0) {
Chris Lattner0b3557f2005-09-24 23:43:33 +0000394 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
395 // we cannot optimize based on the assumption that it is zero without changing
396 // to to an explicit zero. If we don't change it to zero, other code could
397 // optimized based on the contradictory assumption that it is non-zero.
398 // Because instcombine aggressively folds operations with undef args anyway,
399 // this won't lose us code quality.
400 if (Mask->isNullValue())
401 return true;
402 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
403 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Chris Lattner09efd4e2005-10-31 18:35:52 +0000404
405 if (Depth == 6) return false; // Limit search depth.
Chris Lattner0b3557f2005-09-24 23:43:33 +0000406
407 if (Instruction *I = dyn_cast<Instruction>(V)) {
408 switch (I->getOpcode()) {
Chris Lattner62010c42005-10-09 06:36:35 +0000409 case Instruction::And:
410 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
Chris Lattner03b9eb52005-10-09 22:08:50 +0000411 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
412 ConstantIntegral *C1C2 =
413 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
Chris Lattner09efd4e2005-10-31 18:35:52 +0000414 if (MaskedValueIsZero(I->getOperand(0), C1C2, Depth+1))
Chris Lattner62010c42005-10-09 06:36:35 +0000415 return true;
Chris Lattner03b9eb52005-10-09 22:08:50 +0000416 }
417 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000418 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
419 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000420 case Instruction::Or:
Chris Lattner03b9eb52005-10-09 22:08:50 +0000421 case Instruction::Xor:
Chris Lattner62010c42005-10-09 06:36:35 +0000422 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000423 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
424 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000425 case Instruction::Select:
426 // If the T and F values are MaskedValueIsZero, the result is also zero.
Chris Lattner09efd4e2005-10-31 18:35:52 +0000427 return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
428 MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000429 case Instruction::Cast: {
430 const Type *SrcTy = I->getOperand(0)->getType();
431 if (SrcTy == Type::BoolTy)
432 return (Mask->getRawValue() & 1) == 0;
433
434 if (SrcTy->isInteger()) {
435 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
436 if (SrcTy->isUnsigned() && // Only handle zero ext.
437 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
438 return true;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000439
Chris Lattner62010c42005-10-09 06:36:35 +0000440 // If this is a noop cast, recurse.
441 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
442 SrcTy->getSignedVersion() == I->getType()) {
443 Constant *NewMask =
444 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +0000445 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner09efd4e2005-10-31 18:35:52 +0000446 cast<ConstantIntegral>(NewMask), Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000447 }
448 }
449 break;
450 }
451 case Instruction::Shl:
452 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
453 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
454 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner09efd4e2005-10-31 18:35:52 +0000455 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)),
456 Depth+1);
Chris Lattner62010c42005-10-09 06:36:35 +0000457 break;
458 case Instruction::Shr:
459 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
460 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
461 if (I->getType()->isUnsigned()) {
462 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
463 C1 = ConstantExpr::getShr(C1, SA);
464 C1 = ConstantExpr::getAnd(C1, Mask);
465 if (C1->isNullValue())
466 return true;
467 }
468 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000469 }
470 }
471
472 return false;
473}
474
Chris Lattner623826c2004-09-28 21:48:02 +0000475// isTrueWhenEqual - Return true if the specified setcondinst instruction is
476// true when both operands are equal...
477//
478static bool isTrueWhenEqual(Instruction &I) {
479 return I.getOpcode() == Instruction::SetEQ ||
480 I.getOpcode() == Instruction::SetGE ||
481 I.getOpcode() == Instruction::SetLE;
482}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000483
484/// AssociativeOpt - Perform an optimization on an associative operator. This
485/// function is designed to check a chain of associative operators for a
486/// potential to apply a certain optimization. Since the optimization may be
487/// applicable if the expression was reassociated, this checks the chain, then
488/// reassociates the expression as necessary to expose the optimization
489/// opportunity. This makes use of a special Functor, which must define
490/// 'shouldApply' and 'apply' methods.
491///
492template<typename Functor>
493Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
494 unsigned Opcode = Root.getOpcode();
495 Value *LHS = Root.getOperand(0);
496
497 // Quick check, see if the immediate LHS matches...
498 if (F.shouldApply(LHS))
499 return F.apply(Root);
500
501 // Otherwise, if the LHS is not of the same opcode as the root, return.
502 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000503 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000504 // Should we apply this transform to the RHS?
505 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
506
507 // If not to the RHS, check to see if we should apply to the LHS...
508 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
509 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
510 ShouldApply = true;
511 }
512
513 // If the functor wants to apply the optimization to the RHS of LHSI,
514 // reassociate the expression from ((? op A) op B) to (? op (A op B))
515 if (ShouldApply) {
516 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000517
Chris Lattnerb8b97502003-08-13 19:01:45 +0000518 // Now all of the instructions are in the current basic block, go ahead
519 // and perform the reassociation.
520 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
521
522 // First move the selected RHS to the LHS of the root...
523 Root.setOperand(0, LHSI->getOperand(1));
524
525 // Make what used to be the LHS of the root be the user of the root...
526 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000527 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000528 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
529 return 0;
530 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000531 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000532 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000533 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
534 BasicBlock::iterator ARI = &Root; ++ARI;
535 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
536 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000537
538 // Now propagate the ExtraOperand down the chain of instructions until we
539 // get to LHSI.
540 while (TmpLHSI != LHSI) {
541 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000542 // Move the instruction to immediately before the chain we are
543 // constructing to avoid breaking dominance properties.
544 NextLHSI->getParent()->getInstList().remove(NextLHSI);
545 BB->getInstList().insert(ARI, NextLHSI);
546 ARI = NextLHSI;
547
Chris Lattnerb8b97502003-08-13 19:01:45 +0000548 Value *NextOp = NextLHSI->getOperand(1);
549 NextLHSI->setOperand(1, ExtraOperand);
550 TmpLHSI = NextLHSI;
551 ExtraOperand = NextOp;
552 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000553
Chris Lattnerb8b97502003-08-13 19:01:45 +0000554 // Now that the instructions are reassociated, have the functor perform
555 // the transformation...
556 return F.apply(Root);
557 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000558
Chris Lattnerb8b97502003-08-13 19:01:45 +0000559 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
560 }
561 return 0;
562}
563
564
565// AddRHS - Implements: X + X --> X << 1
566struct AddRHS {
567 Value *RHS;
568 AddRHS(Value *rhs) : RHS(rhs) {}
569 bool shouldApply(Value *LHS) const { return LHS == RHS; }
570 Instruction *apply(BinaryOperator &Add) const {
571 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
572 ConstantInt::get(Type::UByteTy, 1));
573 }
574};
575
576// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
577// iff C1&C2 == 0
578struct AddMaskingAnd {
579 Constant *C2;
580 AddMaskingAnd(Constant *c) : C2(c) {}
581 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000582 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000583 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000584 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000585 }
586 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000587 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000588 }
589};
590
Chris Lattner86102b82005-01-01 16:22:27 +0000591static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000592 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000593 if (isa<CastInst>(I)) {
594 if (Constant *SOC = dyn_cast<Constant>(SO))
595 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000596
Chris Lattner86102b82005-01-01 16:22:27 +0000597 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
598 SO->getName() + ".cast"), I);
599 }
600
Chris Lattner183b3362004-04-09 19:05:30 +0000601 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000602 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
603 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000604
Chris Lattner183b3362004-04-09 19:05:30 +0000605 if (Constant *SOC = dyn_cast<Constant>(SO)) {
606 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000607 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
608 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000609 }
610
611 Value *Op0 = SO, *Op1 = ConstOperand;
612 if (!ConstIsRHS)
613 std::swap(Op0, Op1);
614 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000615 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
616 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
617 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
618 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000619 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000620 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000621 abort();
622 }
Chris Lattner86102b82005-01-01 16:22:27 +0000623 return IC->InsertNewInstBefore(New, I);
624}
625
626// FoldOpIntoSelect - Given an instruction with a select as one operand and a
627// constant as the other operand, try to fold the binary operator into the
628// select arguments. This also works for Cast instructions, which obviously do
629// not have a second operand.
630static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
631 InstCombiner *IC) {
632 // Don't modify shared select instructions
633 if (!SI->hasOneUse()) return 0;
634 Value *TV = SI->getOperand(1);
635 Value *FV = SI->getOperand(2);
636
637 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000638 // Bool selects with constant operands can be folded to logical ops.
639 if (SI->getType() == Type::BoolTy) return 0;
640
Chris Lattner86102b82005-01-01 16:22:27 +0000641 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
642 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
643
644 return new SelectInst(SI->getCondition(), SelectTrueVal,
645 SelectFalseVal);
646 }
647 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000648}
649
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000650
651/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
652/// node as operand #0, see if we can fold the instruction into the PHI (which
653/// is only possible if all operands to the PHI are constants).
654Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
655 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000656 unsigned NumPHIValues = PN->getNumIncomingValues();
657 if (!PN->hasOneUse() || NumPHIValues == 0 ||
658 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000659
660 // Check to see if all of the operands of the PHI are constants. If not, we
661 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000662 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000663 if (!isa<Constant>(PN->getIncomingValue(i)))
664 return 0;
665
666 // Okay, we can do the transformation: create the new PHI node.
667 PHINode *NewPN = new PHINode(I.getType(), I.getName());
668 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000669 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000670 InsertNewInstBefore(NewPN, *PN);
671
672 // Next, add all of the operands to the PHI.
673 if (I.getNumOperands() == 2) {
674 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000675 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000676 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
677 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
678 PN->getIncomingBlock(i));
679 }
680 } else {
681 assert(isa<CastInst>(I) && "Unary op should be a cast!");
682 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000683 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000684 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
685 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
686 PN->getIncomingBlock(i));
687 }
688 }
689 return ReplaceInstUsesWith(I, NewPN);
690}
691
Chris Lattner113f4f42002-06-25 16:13:24 +0000692Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000693 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000694 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000695
Chris Lattnercf4a9962004-04-10 22:01:55 +0000696 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000697 // X + undef -> undef
698 if (isa<UndefValue>(RHS))
699 return ReplaceInstUsesWith(I, RHS);
700
Chris Lattnercf4a9962004-04-10 22:01:55 +0000701 // X + 0 --> X
Chris Lattner7fde91e2005-10-17 17:56:38 +0000702 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
703 if (RHSC->isNullValue())
704 return ReplaceInstUsesWith(I, LHS);
Chris Lattnerda1b1522005-10-17 20:18:38 +0000705 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
706 if (CFP->isExactlyValue(-0.0))
707 return ReplaceInstUsesWith(I, LHS);
Chris Lattner7fde91e2005-10-17 17:56:38 +0000708 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000709
Chris Lattnercf4a9962004-04-10 22:01:55 +0000710 // X + (signbit) --> X ^ signbit
711 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000712 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnercf4a9962004-04-10 22:01:55 +0000713 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000714 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000715 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000716 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000717
718 if (isa<PHINode>(LHS))
719 if (Instruction *NV = FoldOpIntoPhi(I))
720 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000721
722 ConstantInt *XorRHS;
723 Value *XorLHS;
724 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
725 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
726 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
727 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
728
729 uint64_t C0080Val = 1ULL << 31;
730 int64_t CFF80Val = -C0080Val;
731 unsigned Size = 32;
732 do {
733 if (TySizeBits > Size) {
734 bool Found = false;
735 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
736 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
737 if (RHSSExt == CFF80Val) {
738 if (XorRHS->getZExtValue() == C0080Val)
739 Found = true;
740 } else if (RHSZExt == C0080Val) {
741 if (XorRHS->getSExtValue() == CFF80Val)
742 Found = true;
743 }
744 if (Found) {
745 // This is a sign extend if the top bits are known zero.
746 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
747 Mask = ConstantExpr::getShl(Mask,
748 ConstantInt::get(Type::UByteTy, 64-TySizeBits-Size));
749 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
750 Size = 0; // Not a sign ext, but can't be any others either.
751 goto FoundSExt;
752 }
753 }
754 Size >>= 1;
755 C0080Val >>= Size;
756 CFF80Val >>= Size;
757 } while (Size >= 8);
758
759FoundSExt:
760 const Type *MiddleType = 0;
761 switch (Size) {
762 default: break;
763 case 32: MiddleType = Type::IntTy; break;
764 case 16: MiddleType = Type::ShortTy; break;
765 case 8: MiddleType = Type::SByteTy; break;
766 }
767 if (MiddleType) {
768 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
769 InsertNewInstBefore(NewTrunc, I);
770 return new CastInst(NewTrunc, I.getType());
771 }
772 }
Chris Lattnercf4a9962004-04-10 22:01:55 +0000773 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000774
Chris Lattnerb8b97502003-08-13 19:01:45 +0000775 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000776 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000777 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000778
779 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
780 if (RHSI->getOpcode() == Instruction::Sub)
781 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
782 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
783 }
784 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
785 if (LHSI->getOpcode() == Instruction::Sub)
786 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
787 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
788 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000789 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000790
Chris Lattner147e9752002-05-08 22:46:53 +0000791 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000792 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000793 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000794
795 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000796 if (!isa<Constant>(RHS))
797 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000798 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000799
Misha Brukmanb1c93172005-04-21 23:48:37 +0000800
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000801 ConstantInt *C2;
802 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
803 if (X == RHS) // X*C + X --> X * (C+1)
804 return BinaryOperator::createMul(RHS, AddOne(C2));
805
806 // X*C1 + X*C2 --> X * (C1+C2)
807 ConstantInt *C1;
808 if (X == dyn_castFoldableMul(RHS, C1))
809 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000810 }
811
812 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000813 if (dyn_castFoldableMul(RHS, C2) == LHS)
814 return BinaryOperator::createMul(LHS, AddOne(C2));
815
Chris Lattner57c8d992003-02-18 19:57:07 +0000816
Chris Lattnerb8b97502003-08-13 19:01:45 +0000817 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000818 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000819 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000820
Chris Lattnerb9cde762003-10-02 15:11:26 +0000821 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000822 Value *X;
823 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
824 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
825 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000826 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000827
Chris Lattnerbff91d92004-10-08 05:07:56 +0000828 // (X & FF00) + xx00 -> (X+xx00) & FF00
829 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
830 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
831 if (Anded == CRHS) {
832 // See if all bits from the first bit set in the Add RHS up are included
833 // in the mask. First, get the rightmost bit.
834 uint64_t AddRHSV = CRHS->getRawValue();
835
836 // Form a mask of all bits from the lowest bit added through the top.
837 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner2f1457f2005-04-24 17:46:05 +0000838 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerbff91d92004-10-08 05:07:56 +0000839
840 // See if the and mask includes all of these bits.
841 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000842
Chris Lattnerbff91d92004-10-08 05:07:56 +0000843 if (AddRHSHighBits == AddRHSHighBitsAnd) {
844 // Okay, the xform is safe. Insert the new add pronto.
845 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
846 LHS->getName()), I);
847 return BinaryOperator::createAnd(NewAdd, C2);
848 }
849 }
850 }
851
Chris Lattnerd4252a72004-07-30 07:50:03 +0000852 // Try to fold constant add into select arguments.
853 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000854 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000855 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000856 }
857
Chris Lattner113f4f42002-06-25 16:13:24 +0000858 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000859}
860
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000861// isSignBit - Return true if the value represented by the constant only has the
862// highest order bit set.
863static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000864 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000865 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000866}
867
Chris Lattner022167f2004-03-13 00:11:49 +0000868/// RemoveNoopCast - Strip off nonconverting casts from the value.
869///
870static Value *RemoveNoopCast(Value *V) {
871 if (CastInst *CI = dyn_cast<CastInst>(V)) {
872 const Type *CTy = CI->getType();
873 const Type *OpTy = CI->getOperand(0)->getType();
874 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000875 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000876 return RemoveNoopCast(CI->getOperand(0));
877 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
878 return RemoveNoopCast(CI->getOperand(0));
879 }
880 return V;
881}
882
Chris Lattner113f4f42002-06-25 16:13:24 +0000883Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000884 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000885
Chris Lattnere6794492002-08-12 21:17:25 +0000886 if (Op0 == Op1) // sub X, X -> 0
887 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000888
Chris Lattnere6794492002-08-12 21:17:25 +0000889 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000890 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000891 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000892
Chris Lattner81a7a232004-10-16 18:11:37 +0000893 if (isa<UndefValue>(Op0))
894 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
895 if (isa<UndefValue>(Op1))
896 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
897
Chris Lattner8f2f5982003-11-05 01:06:05 +0000898 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
899 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000900 if (C->isAllOnesValue())
901 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000902
Chris Lattner8f2f5982003-11-05 01:06:05 +0000903 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000904 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000905 if (match(Op1, m_Not(m_Value(X))))
906 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000907 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000908 // -((uint)X >> 31) -> ((int)X >> 31)
909 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000910 if (C->isNullValue()) {
911 Value *NoopCastedRHS = RemoveNoopCast(Op1);
912 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000913 if (SI->getOpcode() == Instruction::Shr)
914 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
915 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000916 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000917 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000918 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000919 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000920 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000921 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000922 // Ok, the transformation is safe. Insert a cast of the incoming
923 // value, then the new shift, then the new cast.
924 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
925 SI->getOperand(0)->getName());
926 Value *InV = InsertNewInstBefore(FirstCast, I);
927 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
928 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000929 if (NewShift->getType() == I.getType())
930 return NewShift;
931 else {
932 InV = InsertNewInstBefore(NewShift, I);
933 return new CastInst(NewShift, I.getType());
934 }
Chris Lattner92295c52004-03-12 23:53:13 +0000935 }
936 }
Chris Lattner022167f2004-03-13 00:11:49 +0000937 }
Chris Lattner183b3362004-04-09 19:05:30 +0000938
939 // Try to fold constant sub into select arguments.
940 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000941 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000942 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000943
944 if (isa<PHINode>(Op0))
945 if (Instruction *NV = FoldOpIntoPhi(I))
946 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000947 }
948
Chris Lattnera9be4492005-04-07 16:15:25 +0000949 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
950 if (Op1I->getOpcode() == Instruction::Add &&
951 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000952 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000953 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000954 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000955 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000956 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
957 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
958 // C1-(X+C2) --> (C1-C2)-X
959 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
960 Op1I->getOperand(0));
961 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000962 }
963
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000964 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000965 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
966 // is not used by anyone else...
967 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000968 if (Op1I->getOpcode() == Instruction::Sub &&
969 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000970 // Swap the two operands of the subexpr...
971 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
972 Op1I->setOperand(0, IIOp1);
973 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000974
Chris Lattner3082c5a2003-02-18 19:28:33 +0000975 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000976 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000977 }
978
979 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
980 //
981 if (Op1I->getOpcode() == Instruction::And &&
982 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
983 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
984
Chris Lattner396dbfe2004-06-09 05:08:07 +0000985 Value *NewNot =
986 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000987 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000988 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000989
Chris Lattner0aee4b72004-10-06 15:08:25 +0000990 // -(X sdiv C) -> (X sdiv -C)
991 if (Op1I->getOpcode() == Instruction::Div)
992 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000993 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000994 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000995 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000996 ConstantExpr::getNeg(DivRHS));
997
Chris Lattner57c8d992003-02-18 19:57:07 +0000998 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000999 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001000 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00001001 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001002 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001003 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +00001004 }
Chris Lattnerad3c4952002-05-09 01:29:19 +00001005 }
Chris Lattnera9be4492005-04-07 16:15:25 +00001006 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001007
Chris Lattner47060462005-04-07 17:14:51 +00001008 if (!Op0->getType()->isFloatingPoint())
1009 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1010 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001011 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1012 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1013 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1014 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001015 } else if (Op0I->getOpcode() == Instruction::Sub) {
1016 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1017 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001018 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001019
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001020 ConstantInt *C1;
1021 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1022 if (X == Op1) { // X*C - X --> X * (C-1)
1023 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1024 return BinaryOperator::createMul(Op1, CP1);
1025 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001026
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001027 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1028 if (X == dyn_castFoldableMul(Op1, C2))
1029 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1030 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001031 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001032}
1033
Chris Lattnere79e8542004-02-23 06:38:22 +00001034/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1035/// really just returns true if the most significant (sign) bit is set.
1036static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1037 if (RHS->getType()->isSigned()) {
1038 // True if source is LHS < 0 or LHS <= -1
1039 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1040 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1041 } else {
1042 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1043 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1044 // the size of the integer type.
1045 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001046 return RHSC->getValue() ==
1047 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001048 if (Opcode == Instruction::SetGT)
1049 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001050 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001051 }
1052 return false;
1053}
1054
Chris Lattner113f4f42002-06-25 16:13:24 +00001055Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001056 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001057 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001058
Chris Lattner81a7a232004-10-16 18:11:37 +00001059 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1060 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1061
Chris Lattnere6794492002-08-12 21:17:25 +00001062 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001063 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1064 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001065
1066 // ((X << C1)*C2) == (X * (C2 << C1))
1067 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1068 if (SI->getOpcode() == Instruction::Shl)
1069 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001070 return BinaryOperator::createMul(SI->getOperand(0),
1071 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001072
Chris Lattnercce81be2003-09-11 22:24:54 +00001073 if (CI->isNullValue())
1074 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1075 if (CI->equalsInt(1)) // X * 1 == X
1076 return ReplaceInstUsesWith(I, Op0);
1077 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001078 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001079
Chris Lattnercce81be2003-09-11 22:24:54 +00001080 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001081 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1082 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001083 return new ShiftInst(Instruction::Shl, Op0,
1084 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001085 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001086 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001087 if (Op1F->isNullValue())
1088 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001089
Chris Lattner3082c5a2003-02-18 19:28:33 +00001090 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1091 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1092 if (Op1F->getValue() == 1.0)
1093 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1094 }
Chris Lattner183b3362004-04-09 19:05:30 +00001095
1096 // Try to fold constant mul into select arguments.
1097 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001098 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001099 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001100
1101 if (isa<PHINode>(Op0))
1102 if (Instruction *NV = FoldOpIntoPhi(I))
1103 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001104 }
1105
Chris Lattner934a64cf2003-03-10 23:23:04 +00001106 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1107 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001108 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001109
Chris Lattner2635b522004-02-23 05:39:21 +00001110 // If one of the operands of the multiply is a cast from a boolean value, then
1111 // we know the bool is either zero or one, so this is a 'masking' multiply.
1112 // See if we can simplify things based on how the boolean was originally
1113 // formed.
1114 CastInst *BoolCast = 0;
1115 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1116 if (CI->getOperand(0)->getType() == Type::BoolTy)
1117 BoolCast = CI;
1118 if (!BoolCast)
1119 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1120 if (CI->getOperand(0)->getType() == Type::BoolTy)
1121 BoolCast = CI;
1122 if (BoolCast) {
1123 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1124 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1125 const Type *SCOpTy = SCIOp0->getType();
1126
Chris Lattnere79e8542004-02-23 06:38:22 +00001127 // If the setcc is true iff the sign bit of X is set, then convert this
1128 // multiply into a shift/and combination.
1129 if (isa<ConstantInt>(SCIOp1) &&
1130 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001131 // Shift the X value right to turn it into "all signbits".
1132 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001133 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001134 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001135 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001136 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1137 SCIOp0->getName()), I);
1138 }
1139
1140 Value *V =
1141 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1142 BoolCast->getOperand(0)->getName()+
1143 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001144
1145 // If the multiply type is not the same as the source type, sign extend
1146 // or truncate to the multiply type.
1147 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001148 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001149
Chris Lattner2635b522004-02-23 05:39:21 +00001150 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001151 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001152 }
1153 }
1154 }
1155
Chris Lattner113f4f42002-06-25 16:13:24 +00001156 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001157}
1158
Chris Lattner113f4f42002-06-25 16:13:24 +00001159Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001160 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001161
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001162 if (isa<UndefValue>(Op0)) // undef / X -> 0
1163 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1164 if (isa<UndefValue>(Op1))
1165 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1166
1167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001168 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001169 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001170 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001171
Chris Lattnere20c3342004-04-26 14:01:59 +00001172 // div X, -1 == -X
1173 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001174 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001175
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001176 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001177 if (LHS->getOpcode() == Instruction::Div)
1178 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001179 // (X / C1) / C2 -> X / (C1*C2)
1180 return BinaryOperator::createDiv(LHS->getOperand(0),
1181 ConstantExpr::getMul(RHS, LHSRHS));
1182 }
1183
Chris Lattner3082c5a2003-02-18 19:28:33 +00001184 // Check to see if this is an unsigned division with an exact power of 2,
1185 // if so, convert to a right shift.
1186 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1187 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001188 if (isPowerOf2_64(Val)) {
1189 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001190 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001191 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001192 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001193
Chris Lattner4ad08352004-10-09 02:50:40 +00001194 // -X/C -> X/-C
1195 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001196 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001197 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1198
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001199 if (!RHS->isNullValue()) {
1200 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001201 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001202 return R;
1203 if (isa<PHINode>(Op0))
1204 if (Instruction *NV = FoldOpIntoPhi(I))
1205 return NV;
1206 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001207 }
1208
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001209 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1210 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1211 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1212 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1213 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1214 if (STO->getValue() == 0) { // Couldn't be this argument.
1215 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001216 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001217 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001218 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001219 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001220 }
1221
Chris Lattner42362612005-04-08 04:03:26 +00001222 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001223 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1224 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001225 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1226 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1227 TC, SI->getName()+".t");
1228 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001229
Chris Lattner42362612005-04-08 04:03:26 +00001230 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1231 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1232 FC, SI->getName()+".f");
1233 FSI = InsertNewInstBefore(FSI, I);
1234 return new SelectInst(SI->getOperand(0), TSI, FSI);
1235 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001236 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001237
Chris Lattner3082c5a2003-02-18 19:28:33 +00001238 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001239 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001240 if (LHS->equalsInt(0))
1241 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1242
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001243 return 0;
1244}
1245
1246
Chris Lattner113f4f42002-06-25 16:13:24 +00001247Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001248 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001249 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001250 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001251 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001252 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001253 // X % -Y -> X % Y
1254 AddUsesToWorkList(I);
1255 I.setOperand(1, RHSNeg);
1256 return &I;
1257 }
1258
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001259 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001260 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001261 if (isa<UndefValue>(Op1))
1262 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001263
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001264 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001265 if (RHS->equalsInt(1)) // X % 1 == 0
1266 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1267
1268 // Check to see if this is an unsigned remainder with an exact power of 2,
1269 // if so, convert to a bitwise and.
1270 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1271 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001272 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001273 return BinaryOperator::createAnd(Op0,
1274 ConstantUInt::get(I.getType(), Val-1));
1275
1276 if (!RHS->isNullValue()) {
1277 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001278 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001279 return R;
1280 if (isa<PHINode>(Op0))
1281 if (Instruction *NV = FoldOpIntoPhi(I))
1282 return NV;
1283 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001284 }
1285
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001286 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1287 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1288 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1289 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1290 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1291 if (STO->getValue() == 0) { // Couldn't be this argument.
1292 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001293 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001294 } else if (SFO->getValue() == 0) {
1295 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001296 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001297 }
1298
1299 if (!(STO->getValue() & (STO->getValue()-1)) &&
1300 !(SFO->getValue() & (SFO->getValue()-1))) {
1301 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1302 SubOne(STO), SI->getName()+".t"), I);
1303 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1304 SubOne(SFO), SI->getName()+".f"), I);
1305 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1306 }
1307 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001308
Chris Lattner3082c5a2003-02-18 19:28:33 +00001309 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001310 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001311 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001312 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1313
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001314 return 0;
1315}
1316
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001317// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001318static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001319 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1320 // Calculate -1 casted to the right type...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001321 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001322 uint64_t Val = ~0ULL; // All ones
1323 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1324 return CU->getValue() == Val-1;
1325 }
1326
1327 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001328
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001329 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001330 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001331 int64_t Val = INT64_MAX; // All ones
1332 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1333 return CS->getValue() == Val-1;
1334}
1335
1336// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001337static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001338 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1339 return CU->getValue() == 1;
1340
1341 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001342
1343 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001344 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001345 int64_t Val = -1; // All ones
1346 Val <<= TypeBits-1; // Shift over to the right spot
1347 return CS->getValue() == Val+1;
1348}
1349
Chris Lattner35167c32004-06-09 07:59:58 +00001350// isOneBitSet - Return true if there is exactly one bit set in the specified
1351// constant.
1352static bool isOneBitSet(const ConstantInt *CI) {
1353 uint64_t V = CI->getRawValue();
1354 return V && (V & (V-1)) == 0;
1355}
1356
Chris Lattner8fc5af42004-09-23 21:46:38 +00001357#if 0 // Currently unused
1358// isLowOnes - Return true if the constant is of the form 0+1+.
1359static bool isLowOnes(const ConstantInt *CI) {
1360 uint64_t V = CI->getRawValue();
1361
1362 // There won't be bits set in parts that the type doesn't contain.
1363 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1364
1365 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1366 return U && V && (U & V) == 0;
1367}
1368#endif
1369
1370// isHighOnes - Return true if the constant is of the form 1+0+.
1371// This is the same as lowones(~X).
1372static bool isHighOnes(const ConstantInt *CI) {
1373 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001374 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001375
1376 // There won't be bits set in parts that the type doesn't contain.
1377 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1378
1379 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1380 return U && V && (U & V) == 0;
1381}
1382
1383
Chris Lattner3ac7c262003-08-13 20:16:26 +00001384/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1385/// are carefully arranged to allow folding of expressions such as:
1386///
1387/// (A < B) | (A > B) --> (A != B)
1388///
1389/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1390/// represents that the comparison is true if A == B, and bit value '1' is true
1391/// if A < B.
1392///
1393static unsigned getSetCondCode(const SetCondInst *SCI) {
1394 switch (SCI->getOpcode()) {
1395 // False -> 0
1396 case Instruction::SetGT: return 1;
1397 case Instruction::SetEQ: return 2;
1398 case Instruction::SetGE: return 3;
1399 case Instruction::SetLT: return 4;
1400 case Instruction::SetNE: return 5;
1401 case Instruction::SetLE: return 6;
1402 // True -> 7
1403 default:
1404 assert(0 && "Invalid SetCC opcode!");
1405 return 0;
1406 }
1407}
1408
1409/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1410/// opcode and two operands into either a constant true or false, or a brand new
1411/// SetCC instruction.
1412static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1413 switch (Opcode) {
1414 case 0: return ConstantBool::False;
1415 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1416 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1417 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1418 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1419 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1420 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1421 case 7: return ConstantBool::True;
1422 default: assert(0 && "Illegal SetCCCode!"); return 0;
1423 }
1424}
1425
1426// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1427struct FoldSetCCLogical {
1428 InstCombiner &IC;
1429 Value *LHS, *RHS;
1430 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1431 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1432 bool shouldApply(Value *V) const {
1433 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1434 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1435 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1436 return false;
1437 }
1438 Instruction *apply(BinaryOperator &Log) const {
1439 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1440 if (SCI->getOperand(0) != LHS) {
1441 assert(SCI->getOperand(1) == LHS);
1442 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1443 }
1444
1445 unsigned LHSCode = getSetCondCode(SCI);
1446 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1447 unsigned Code;
1448 switch (Log.getOpcode()) {
1449 case Instruction::And: Code = LHSCode & RHSCode; break;
1450 case Instruction::Or: Code = LHSCode | RHSCode; break;
1451 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001452 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001453 }
1454
1455 Value *RV = getSetCCValue(Code, LHS, RHS);
1456 if (Instruction *I = dyn_cast<Instruction>(RV))
1457 return I;
1458 // Otherwise, it's a constant boolean value...
1459 return IC.ReplaceInstUsesWith(Log, RV);
1460 }
1461};
1462
Chris Lattnerba1cb382003-09-19 17:17:26 +00001463// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1464// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1465// guaranteed to be either a shift instruction or a binary operator.
1466Instruction *InstCombiner::OptAndOp(Instruction *Op,
1467 ConstantIntegral *OpRHS,
1468 ConstantIntegral *AndRHS,
1469 BinaryOperator &TheAnd) {
1470 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001471 Constant *Together = 0;
1472 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001473 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001474
Chris Lattnerba1cb382003-09-19 17:17:26 +00001475 switch (Op->getOpcode()) {
1476 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001477 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001478 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1479 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001480 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001481 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001482 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001483 }
1484 break;
1485 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001486 if (Together == AndRHS) // (X | C) & C --> C
1487 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001488
Chris Lattner86102b82005-01-01 16:22:27 +00001489 if (Op->hasOneUse() && Together != OpRHS) {
1490 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1491 std::string Op0Name = Op->getName(); Op->setName("");
1492 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1493 InsertNewInstBefore(Or, TheAnd);
1494 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001495 }
1496 break;
1497 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001498 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001499 // Adding a one to a single bit bit-field should be turned into an XOR
1500 // of the bit. First thing to check is to see if this AND is with a
1501 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001502 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001503
1504 // Clear bits that are not part of the constant.
Chris Lattner2f1457f2005-04-24 17:46:05 +00001505 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerba1cb382003-09-19 17:17:26 +00001506
1507 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001508 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001509 // Ok, at this point, we know that we are masking the result of the
1510 // ADD down to exactly one bit. If the constant we are adding has
1511 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001512 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001513
Chris Lattnerba1cb382003-09-19 17:17:26 +00001514 // Check to see if any bits below the one bit set in AndRHSV are set.
1515 if ((AddRHS & (AndRHSV-1)) == 0) {
1516 // If not, the only thing that can effect the output of the AND is
1517 // the bit specified by AndRHSV. If that bit is set, the effect of
1518 // the XOR is to toggle the bit. If it is clear, then the ADD has
1519 // no effect.
1520 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1521 TheAnd.setOperand(0, X);
1522 return &TheAnd;
1523 } else {
1524 std::string Name = Op->getName(); Op->setName("");
1525 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001526 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001527 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001528 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001529 }
1530 }
1531 }
1532 }
1533 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001534
1535 case Instruction::Shl: {
1536 // We know that the AND will not produce any of the bits shifted in, so if
1537 // the anded constant includes them, clear them now!
1538 //
1539 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001540 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1541 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001542
Chris Lattner7e794272004-09-24 15:21:34 +00001543 if (CI == ShlMask) { // Masking out bits that the shift already masks
1544 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1545 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001546 TheAnd.setOperand(1, CI);
1547 return &TheAnd;
1548 }
1549 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001550 }
Chris Lattner2da29172003-09-19 19:05:02 +00001551 case Instruction::Shr:
1552 // We know that the AND will not produce any of the bits shifted in, so if
1553 // the anded constant includes them, clear them now! This only applies to
1554 // unsigned shifts, because a signed shr may bring in set bits!
1555 //
1556 if (AndRHS->getType()->isUnsigned()) {
1557 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001558 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1559 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1560
1561 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1562 return ReplaceInstUsesWith(TheAnd, Op);
1563 } else if (CI != AndRHS) {
1564 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001565 return &TheAnd;
1566 }
Chris Lattner7e794272004-09-24 15:21:34 +00001567 } else { // Signed shr.
1568 // See if this is shifting in some sign extension, then masking it out
1569 // with an and.
1570 if (Op->hasOneUse()) {
1571 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1572 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1573 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001574 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001575 // Make the argument unsigned.
1576 Value *ShVal = Op->getOperand(0);
1577 ShVal = InsertCastBefore(ShVal,
1578 ShVal->getType()->getUnsignedVersion(),
1579 TheAnd);
1580 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1581 OpRHS, Op->getName()),
1582 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001583 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1584 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1585 TheAnd.getName()),
1586 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001587 return new CastInst(ShVal, Op->getType());
1588 }
1589 }
Chris Lattner2da29172003-09-19 19:05:02 +00001590 }
1591 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001592 }
1593 return 0;
1594}
1595
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001596
Chris Lattner6862fbd2004-09-29 17:40:11 +00001597/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1598/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1599/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1600/// insert new instructions.
1601Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1602 bool Inside, Instruction &IB) {
1603 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1604 "Lo is not <= Hi in range emission code!");
1605 if (Inside) {
1606 if (Lo == Hi) // Trivially false.
1607 return new SetCondInst(Instruction::SetNE, V, V);
1608 if (cast<ConstantIntegral>(Lo)->isMinValue())
1609 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001610
Chris Lattner6862fbd2004-09-29 17:40:11 +00001611 Constant *AddCST = ConstantExpr::getNeg(Lo);
1612 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1613 InsertNewInstBefore(Add, IB);
1614 // Convert to unsigned for the comparison.
1615 const Type *UnsType = Add->getType()->getUnsignedVersion();
1616 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1617 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1618 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1619 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1620 }
1621
1622 if (Lo == Hi) // Trivially true.
1623 return new SetCondInst(Instruction::SetEQ, V, V);
1624
1625 Hi = SubOne(cast<ConstantInt>(Hi));
1626 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1627 return new SetCondInst(Instruction::SetGT, V, Hi);
1628
1629 // Emit X-Lo > Hi-Lo-1
1630 Constant *AddCST = ConstantExpr::getNeg(Lo);
1631 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1632 InsertNewInstBefore(Add, IB);
1633 // Convert to unsigned for the comparison.
1634 const Type *UnsType = Add->getType()->getUnsignedVersion();
1635 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1636 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1637 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1638 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1639}
1640
Chris Lattnerb4b25302005-09-18 07:22:02 +00001641// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1642// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1643// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1644// not, since all 1s are not contiguous.
1645static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1646 uint64_t V = Val->getRawValue();
1647 if (!isShiftedMask_64(V)) return false;
1648
1649 // look for the first zero bit after the run of ones
1650 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1651 // look for the first non-zero bit
1652 ME = 64-CountLeadingZeros_64(V);
1653 return true;
1654}
1655
1656
1657
1658/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1659/// where isSub determines whether the operator is a sub. If we can fold one of
1660/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00001661///
1662/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1663/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1664/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1665///
1666/// return (A +/- B).
1667///
1668Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1669 ConstantIntegral *Mask, bool isSub,
1670 Instruction &I) {
1671 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1672 if (!LHSI || LHSI->getNumOperands() != 2 ||
1673 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1674
1675 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1676
1677 switch (LHSI->getOpcode()) {
1678 default: return 0;
1679 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001680 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1681 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1682 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1683 break;
1684
1685 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1686 // part, we don't need any explicit masks to take them out of A. If that
1687 // is all N is, ignore it.
1688 unsigned MB, ME;
1689 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1690 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1691 Mask = ConstantExpr::getUShr(Mask,
1692 ConstantInt::get(Type::UByteTy,
1693 (64-MB+1)));
1694 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1695 break;
1696 }
1697 }
Chris Lattneraf517572005-09-18 04:24:45 +00001698 return 0;
1699 case Instruction::Or:
1700 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001701 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1702 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1703 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00001704 break;
1705 return 0;
1706 }
1707
1708 Instruction *New;
1709 if (isSub)
1710 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1711 else
1712 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1713 return InsertNewInstBefore(New, I);
1714}
1715
Chris Lattner113f4f42002-06-25 16:13:24 +00001716Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001717 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001718 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001719
Chris Lattner81a7a232004-10-16 18:11:37 +00001720 if (isa<UndefValue>(Op1)) // X & undef -> 0
1721 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1722
Chris Lattner86102b82005-01-01 16:22:27 +00001723 // and X, X = X
1724 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001725 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001726
Chris Lattner86102b82005-01-01 16:22:27 +00001727 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001728 // and X, -1 == X
1729 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001730 return ReplaceInstUsesWith(I, Op0);
Chris Lattner38a1b002005-10-26 17:18:16 +00001731
1732 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1733 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1734 // through many levels of ands.
1735 {
1736 Value *X; ConstantInt *C1;
1737 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1738 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1739 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001740
Chris Lattner86102b82005-01-01 16:22:27 +00001741 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1742 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1743
1744 // If the mask is not masking out any bits, there is no reason to do the
1745 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001746 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001747 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001748 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001749 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001750
Chris Lattnerba1cb382003-09-19 17:17:26 +00001751 // Optimize a variety of ((val OP C1) & C2) combinations...
1752 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1753 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001754 Value *Op0LHS = Op0I->getOperand(0);
1755 Value *Op0RHS = Op0I->getOperand(1);
1756 switch (Op0I->getOpcode()) {
1757 case Instruction::Xor:
1758 case Instruction::Or:
1759 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1760 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1761 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001762 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001763 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001764 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001765
1766 // If the mask is only needed on one incoming arm, push it up.
1767 if (Op0I->hasOneUse()) {
1768 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1769 // Not masking anything out for the LHS, move to RHS.
1770 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1771 Op0RHS->getName()+".masked");
1772 InsertNewInstBefore(NewRHS, I);
1773 return BinaryOperator::create(
1774 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001775 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001776 if (!isa<Constant>(NotAndRHS) &&
1777 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1778 // Not masking anything out for the RHS, move to LHS.
1779 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1780 Op0LHS->getName()+".masked");
1781 InsertNewInstBefore(NewLHS, I);
1782 return BinaryOperator::create(
1783 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1784 }
1785 }
1786
Chris Lattner86102b82005-01-01 16:22:27 +00001787 break;
1788 case Instruction::And:
1789 // (X & V) & C2 --> 0 iff (V & C2) == 0
1790 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1791 MaskedValueIsZero(Op0RHS, AndRHS))
1792 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1793 break;
Chris Lattneraf517572005-09-18 04:24:45 +00001794 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001795 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1796 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1797 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1798 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1799 return BinaryOperator::createAnd(V, AndRHS);
1800 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1801 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00001802 break;
1803
1804 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001805 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1806 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1807 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1808 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1809 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00001810 break;
Chris Lattner86102b82005-01-01 16:22:27 +00001811 }
1812
Chris Lattner16464b32003-07-23 19:25:52 +00001813 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001814 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001815 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001816 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1817 const Type *SrcTy = CI->getOperand(0)->getType();
1818
Chris Lattner2c14cf72005-08-07 07:03:10 +00001819 // If this is an integer truncation or change from signed-to-unsigned, and
1820 // if the source is an and/or with immediate, transform it. This
1821 // frequently occurs for bitfield accesses.
1822 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1823 if (SrcTy->getPrimitiveSizeInBits() >=
1824 I.getType()->getPrimitiveSizeInBits() &&
1825 CastOp->getNumOperands() == 2)
1826 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1827 if (CastOp->getOpcode() == Instruction::And) {
1828 // Change: and (cast (and X, C1) to T), C2
1829 // into : and (cast X to T), trunc(C1)&C2
1830 // This will folds the two ands together, which may allow other
1831 // simplifications.
1832 Instruction *NewCast =
1833 new CastInst(CastOp->getOperand(0), I.getType(),
1834 CastOp->getName()+".shrunk");
1835 NewCast = InsertNewInstBefore(NewCast, I);
1836
1837 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1838 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1839 return BinaryOperator::createAnd(NewCast, C3);
1840 } else if (CastOp->getOpcode() == Instruction::Or) {
1841 // Change: and (cast (or X, C1) to T), C2
1842 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1843 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1844 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1845 return ReplaceInstUsesWith(I, AndRHS);
1846 }
1847 }
1848
1849
Chris Lattner86102b82005-01-01 16:22:27 +00001850 // If this is an integer sign or zero extension instruction.
1851 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001852 SrcTy->getPrimitiveSizeInBits() <
1853 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001854
1855 if (SrcTy->isUnsigned()) {
1856 // See if this and is clearing out bits that are known to be zero
1857 // anyway (due to the zero extension).
1858 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1859 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1860 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1861 if (Result == Mask) // The "and" isn't doing anything, remove it.
1862 return ReplaceInstUsesWith(I, CI);
1863 if (Result != AndRHS) { // Reduce the and RHS constant.
1864 I.setOperand(1, Result);
1865 return &I;
1866 }
1867
1868 } else {
1869 if (CI->hasOneUse() && SrcTy->isInteger()) {
1870 // We can only do this if all of the sign bits brought in are masked
1871 // out. Compute this by first getting 0000011111, then inverting
1872 // it.
1873 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1874 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1875 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1876 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1877 // If the and is clearing all of the sign bits, change this to a
1878 // zero extension cast. To do this, cast the cast input to
1879 // unsigned, then to the requested size.
1880 Value *CastOp = CI->getOperand(0);
1881 Instruction *NC =
1882 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1883 CI->getName()+".uns");
1884 NC = InsertNewInstBefore(NC, I);
1885 // Finally, insert a replacement for CI.
1886 NC = new CastInst(NC, CI->getType(), CI->getName());
1887 CI->setName("");
1888 NC = InsertNewInstBefore(NC, I);
1889 WorkList.push_back(CI); // Delete CI later.
1890 I.setOperand(0, NC);
1891 return &I; // The AND operand was modified.
1892 }
1893 }
1894 }
1895 }
Chris Lattner33217db2003-07-23 19:36:21 +00001896 }
Chris Lattner183b3362004-04-09 19:05:30 +00001897
1898 // Try to fold constant and into select arguments.
1899 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001900 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001901 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001902 if (isa<PHINode>(Op0))
1903 if (Instruction *NV = FoldOpIntoPhi(I))
1904 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001905 }
1906
Chris Lattnerbb74e222003-03-10 23:06:50 +00001907 Value *Op0NotVal = dyn_castNotVal(Op0);
1908 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001909
Chris Lattner023a4832004-06-18 06:07:51 +00001910 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1911 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1912
Misha Brukman9c003d82004-07-30 12:50:08 +00001913 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001914 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001915 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1916 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001917 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001918 return BinaryOperator::createNot(Or);
1919 }
1920
Chris Lattner623826c2004-09-28 21:48:02 +00001921 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1922 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001923 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1924 return R;
1925
Chris Lattner623826c2004-09-28 21:48:02 +00001926 Value *LHSVal, *RHSVal;
1927 ConstantInt *LHSCst, *RHSCst;
1928 Instruction::BinaryOps LHSCC, RHSCC;
1929 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1930 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1931 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1932 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001933 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001934 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1935 // Ensure that the larger constant is on the RHS.
1936 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1937 SetCondInst *LHS = cast<SetCondInst>(Op0);
1938 if (cast<ConstantBool>(Cmp)->getValue()) {
1939 std::swap(LHS, RHS);
1940 std::swap(LHSCst, RHSCst);
1941 std::swap(LHSCC, RHSCC);
1942 }
1943
1944 // At this point, we know we have have two setcc instructions
1945 // comparing a value against two constants and and'ing the result
1946 // together. Because of the above check, we know that we only have
1947 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1948 // FoldSetCCLogical check above), that the two constants are not
1949 // equal.
1950 assert(LHSCst != RHSCst && "Compares not folded above?");
1951
1952 switch (LHSCC) {
1953 default: assert(0 && "Unknown integer condition code!");
1954 case Instruction::SetEQ:
1955 switch (RHSCC) {
1956 default: assert(0 && "Unknown integer condition code!");
1957 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1958 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1959 return ReplaceInstUsesWith(I, ConstantBool::False);
1960 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1961 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1962 return ReplaceInstUsesWith(I, LHS);
1963 }
1964 case Instruction::SetNE:
1965 switch (RHSCC) {
1966 default: assert(0 && "Unknown integer condition code!");
1967 case Instruction::SetLT:
1968 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1969 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1970 break; // (X != 13 & X < 15) -> no change
1971 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1972 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1973 return ReplaceInstUsesWith(I, RHS);
1974 case Instruction::SetNE:
1975 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1976 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1977 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1978 LHSVal->getName()+".off");
1979 InsertNewInstBefore(Add, I);
1980 const Type *UnsType = Add->getType()->getUnsignedVersion();
1981 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1982 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1983 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1984 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1985 }
1986 break; // (X != 13 & X != 15) -> no change
1987 }
1988 break;
1989 case Instruction::SetLT:
1990 switch (RHSCC) {
1991 default: assert(0 && "Unknown integer condition code!");
1992 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1993 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1994 return ReplaceInstUsesWith(I, ConstantBool::False);
1995 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1996 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1997 return ReplaceInstUsesWith(I, LHS);
1998 }
1999 case Instruction::SetGT:
2000 switch (RHSCC) {
2001 default: assert(0 && "Unknown integer condition code!");
2002 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2003 return ReplaceInstUsesWith(I, LHS);
2004 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2005 return ReplaceInstUsesWith(I, RHS);
2006 case Instruction::SetNE:
2007 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2008 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2009 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00002010 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2011 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00002012 }
2013 }
2014 }
2015 }
2016
Chris Lattner113f4f42002-06-25 16:13:24 +00002017 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002018}
2019
Chris Lattner113f4f42002-06-25 16:13:24 +00002020Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002021 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002022 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002023
Chris Lattner81a7a232004-10-16 18:11:37 +00002024 if (isa<UndefValue>(Op1))
2025 return ReplaceInstUsesWith(I, // X | undef -> -1
2026 ConstantIntegral::getAllOnesValue(I.getType()));
2027
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002028 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002029 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2030 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002031
2032 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002033 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002034 // If X is known to only contain bits that already exist in RHS, just
2035 // replace this instruction with RHS directly.
2036 if (MaskedValueIsZero(Op0,
2037 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2038 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002039
Chris Lattnerd4252a72004-07-30 07:50:03 +00002040 ConstantInt *C1; Value *X;
2041 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2042 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002043 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2044 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002045 InsertNewInstBefore(Or, I);
2046 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2047 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002048
Chris Lattnerd4252a72004-07-30 07:50:03 +00002049 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2050 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2051 std::string Op0Name = Op0->getName(); Op0->setName("");
2052 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2053 InsertNewInstBefore(Or, I);
2054 return BinaryOperator::createXor(Or,
2055 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002056 }
Chris Lattner183b3362004-04-09 19:05:30 +00002057
2058 // Try to fold constant and into select arguments.
2059 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002060 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002061 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002062 if (isa<PHINode>(Op0))
2063 if (Instruction *NV = FoldOpIntoPhi(I))
2064 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002065 }
2066
Chris Lattnerd4252a72004-07-30 07:50:03 +00002067 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattner4294cec2005-05-07 23:49:08 +00002068
2069 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2070 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2071 return ReplaceInstUsesWith(I, Op1);
2072 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2073 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2074 return ReplaceInstUsesWith(I, Op0);
2075
Chris Lattnerb62f5082005-05-09 04:58:36 +00002076 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2077 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2078 MaskedValueIsZero(Op1, C1)) {
2079 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2080 Op0->setName("");
2081 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2082 }
2083
2084 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2085 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2086 MaskedValueIsZero(Op0, C1)) {
2087 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2088 Op0->setName("");
2089 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2090 }
2091
Chris Lattner15212982005-09-18 03:42:07 +00002092 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002093 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002094 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2095
2096 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2097 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2098
2099
Chris Lattner01f56c62005-09-18 06:02:59 +00002100 // If we have: ((V + N) & C1) | (V & C2)
2101 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2102 // replace with V+N.
2103 if (C1 == ConstantExpr::getNot(C2)) {
2104 Value *V1, *V2;
2105 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2106 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2107 // Add commutes, try both ways.
2108 if (V1 == B && MaskedValueIsZero(V2, C2))
2109 return ReplaceInstUsesWith(I, A);
2110 if (V2 == B && MaskedValueIsZero(V1, C2))
2111 return ReplaceInstUsesWith(I, A);
2112 }
2113 // Or commutes, try both ways.
2114 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2115 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2116 // Add commutes, try both ways.
2117 if (V1 == A && MaskedValueIsZero(V2, C1))
2118 return ReplaceInstUsesWith(I, B);
2119 if (V2 == A && MaskedValueIsZero(V1, C1))
2120 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002121 }
2122 }
2123 }
Chris Lattner812aab72003-08-12 19:11:07 +00002124
Chris Lattnerd4252a72004-07-30 07:50:03 +00002125 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2126 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002127 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002128 ConstantIntegral::getAllOnesValue(I.getType()));
2129 } else {
2130 A = 0;
2131 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002132 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002133 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2134 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002135 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002136 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002137
Misha Brukman9c003d82004-07-30 12:50:08 +00002138 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002139 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2140 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2141 I.getName()+".demorgan"), I);
2142 return BinaryOperator::createNot(And);
2143 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002144 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002145
Chris Lattner3ac7c262003-08-13 20:16:26 +00002146 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002147 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002148 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2149 return R;
2150
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002151 Value *LHSVal, *RHSVal;
2152 ConstantInt *LHSCst, *RHSCst;
2153 Instruction::BinaryOps LHSCC, RHSCC;
2154 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2155 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2156 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2157 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002158 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002159 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2160 // Ensure that the larger constant is on the RHS.
2161 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2162 SetCondInst *LHS = cast<SetCondInst>(Op0);
2163 if (cast<ConstantBool>(Cmp)->getValue()) {
2164 std::swap(LHS, RHS);
2165 std::swap(LHSCst, RHSCst);
2166 std::swap(LHSCC, RHSCC);
2167 }
2168
2169 // At this point, we know we have have two setcc instructions
2170 // comparing a value against two constants and or'ing the result
2171 // together. Because of the above check, we know that we only have
2172 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2173 // FoldSetCCLogical check above), that the two constants are not
2174 // equal.
2175 assert(LHSCst != RHSCst && "Compares not folded above?");
2176
2177 switch (LHSCC) {
2178 default: assert(0 && "Unknown integer condition code!");
2179 case Instruction::SetEQ:
2180 switch (RHSCC) {
2181 default: assert(0 && "Unknown integer condition code!");
2182 case Instruction::SetEQ:
2183 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2184 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2185 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2186 LHSVal->getName()+".off");
2187 InsertNewInstBefore(Add, I);
2188 const Type *UnsType = Add->getType()->getUnsignedVersion();
2189 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2190 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2191 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2192 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2193 }
2194 break; // (X == 13 | X == 15) -> no change
2195
Chris Lattner5c219462005-04-19 06:04:18 +00002196 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2197 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002198 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2199 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2200 return ReplaceInstUsesWith(I, RHS);
2201 }
2202 break;
2203 case Instruction::SetNE:
2204 switch (RHSCC) {
2205 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002206 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2207 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2208 return ReplaceInstUsesWith(I, LHS);
2209 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002210 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002211 return ReplaceInstUsesWith(I, ConstantBool::True);
2212 }
2213 break;
2214 case Instruction::SetLT:
2215 switch (RHSCC) {
2216 default: assert(0 && "Unknown integer condition code!");
2217 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2218 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002219 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2220 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002221 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2222 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2223 return ReplaceInstUsesWith(I, RHS);
2224 }
2225 break;
2226 case Instruction::SetGT:
2227 switch (RHSCC) {
2228 default: assert(0 && "Unknown integer condition code!");
2229 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2230 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2231 return ReplaceInstUsesWith(I, LHS);
2232 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2233 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2234 return ReplaceInstUsesWith(I, ConstantBool::True);
2235 }
2236 }
2237 }
2238 }
Chris Lattner15212982005-09-18 03:42:07 +00002239
Chris Lattner113f4f42002-06-25 16:13:24 +00002240 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002241}
2242
Chris Lattnerc2076352004-02-16 01:20:27 +00002243// XorSelf - Implements: X ^ X --> 0
2244struct XorSelf {
2245 Value *RHS;
2246 XorSelf(Value *rhs) : RHS(rhs) {}
2247 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2248 Instruction *apply(BinaryOperator &Xor) const {
2249 return &Xor;
2250 }
2251};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002252
2253
Chris Lattner113f4f42002-06-25 16:13:24 +00002254Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002255 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002256 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002257
Chris Lattner81a7a232004-10-16 18:11:37 +00002258 if (isa<UndefValue>(Op1))
2259 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2260
Chris Lattnerc2076352004-02-16 01:20:27 +00002261 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2262 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2263 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002264 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002265 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002266
Chris Lattner97638592003-07-23 21:37:07 +00002267 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002268 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002269 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002270 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002271
Chris Lattner97638592003-07-23 21:37:07 +00002272 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002273 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002274 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002275 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002276 return new SetCondInst(SCI->getInverseCondition(),
2277 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002278
Chris Lattner8f2f5982003-11-05 01:06:05 +00002279 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002280 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2281 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002282 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2283 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002284 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002285 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002286 }
Chris Lattner023a4832004-06-18 06:07:51 +00002287
2288 // ~(~X & Y) --> (X | ~Y)
2289 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2290 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2291 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2292 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002293 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002294 Op0I->getOperand(1)->getName()+".not");
2295 InsertNewInstBefore(NotY, I);
2296 return BinaryOperator::createOr(Op0NotVal, NotY);
2297 }
2298 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002299
Chris Lattner97638592003-07-23 21:37:07 +00002300 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002301 switch (Op0I->getOpcode()) {
2302 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002303 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002304 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002305 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2306 return BinaryOperator::createSub(
2307 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002308 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002309 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002310 }
Chris Lattnere5806662003-11-04 23:50:51 +00002311 break;
2312 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002313 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002314 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2315 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002316 break;
2317 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002318 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002319 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002320 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002321 break;
2322 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002323 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002324 }
Chris Lattner183b3362004-04-09 19:05:30 +00002325
2326 // Try to fold constant and into select arguments.
2327 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002328 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002329 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002330 if (isa<PHINode>(Op0))
2331 if (Instruction *NV = FoldOpIntoPhi(I))
2332 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002333 }
2334
Chris Lattnerbb74e222003-03-10 23:06:50 +00002335 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002336 if (X == Op1)
2337 return ReplaceInstUsesWith(I,
2338 ConstantIntegral::getAllOnesValue(I.getType()));
2339
Chris Lattnerbb74e222003-03-10 23:06:50 +00002340 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002341 if (X == Op0)
2342 return ReplaceInstUsesWith(I,
2343 ConstantIntegral::getAllOnesValue(I.getType()));
2344
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002345 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002346 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002347 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2348 cast<BinaryOperator>(Op1I)->swapOperands();
2349 I.swapOperands();
2350 std::swap(Op0, Op1);
2351 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2352 I.swapOperands();
2353 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002354 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002355 } else if (Op1I->getOpcode() == Instruction::Xor) {
2356 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2357 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2358 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2359 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2360 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002361
2362 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002363 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002364 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2365 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002366 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002367 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2368 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002369 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002370 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002371 } else if (Op0I->getOpcode() == Instruction::Xor) {
2372 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2373 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2374 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2375 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002376 }
2377
Chris Lattner7aa2d472004-08-01 19:42:59 +00002378 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002379 Value *A, *B; ConstantInt *C1, *C2;
2380 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2381 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002382 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002383 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002384
Chris Lattner3ac7c262003-08-13 20:16:26 +00002385 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2386 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2387 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2388 return R;
2389
Chris Lattner113f4f42002-06-25 16:13:24 +00002390 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002391}
2392
Chris Lattner6862fbd2004-09-29 17:40:11 +00002393/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2394/// overflowed for this type.
2395static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2396 ConstantInt *In2) {
2397 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2398 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2399}
2400
2401static bool isPositive(ConstantInt *C) {
2402 return cast<ConstantSInt>(C)->getValue() >= 0;
2403}
2404
2405/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2406/// overflowed for this type.
2407static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2408 ConstantInt *In2) {
2409 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2410
2411 if (In1->getType()->isUnsigned())
2412 return cast<ConstantUInt>(Result)->getValue() <
2413 cast<ConstantUInt>(In1)->getValue();
2414 if (isPositive(In1) != isPositive(In2))
2415 return false;
2416 if (isPositive(In1))
2417 return cast<ConstantSInt>(Result)->getValue() <
2418 cast<ConstantSInt>(In1)->getValue();
2419 return cast<ConstantSInt>(Result)->getValue() >
2420 cast<ConstantSInt>(In1)->getValue();
2421}
2422
Chris Lattner0798af32005-01-13 20:14:25 +00002423/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2424/// code necessary to compute the offset from the base pointer (without adding
2425/// in the base pointer). Return the result as a signed integer of intptr size.
2426static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2427 TargetData &TD = IC.getTargetData();
2428 gep_type_iterator GTI = gep_type_begin(GEP);
2429 const Type *UIntPtrTy = TD.getIntPtrType();
2430 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2431 Value *Result = Constant::getNullValue(SIntPtrTy);
2432
2433 // Build a mask for high order bits.
2434 uint64_t PtrSizeMask = ~0ULL;
2435 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2436
Chris Lattner0798af32005-01-13 20:14:25 +00002437 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2438 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002439 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002440 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2441 SIntPtrTy);
2442 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2443 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002444 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002445 Scale = ConstantExpr::getMul(OpC, Scale);
2446 if (Constant *RC = dyn_cast<Constant>(Result))
2447 Result = ConstantExpr::getAdd(RC, Scale);
2448 else {
2449 // Emit an add instruction.
2450 Result = IC.InsertNewInstBefore(
2451 BinaryOperator::createAdd(Result, Scale,
2452 GEP->getName()+".offs"), I);
2453 }
2454 }
2455 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002456 // Convert to correct type.
2457 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2458 Op->getName()+".c"), I);
2459 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002460 // We'll let instcombine(mul) convert this to a shl if possible.
2461 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2462 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002463
2464 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002465 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002466 GEP->getName()+".offs"), I);
2467 }
2468 }
2469 return Result;
2470}
2471
2472/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2473/// else. At this point we know that the GEP is on the LHS of the comparison.
2474Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2475 Instruction::BinaryOps Cond,
2476 Instruction &I) {
2477 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002478
2479 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2480 if (isa<PointerType>(CI->getOperand(0)->getType()))
2481 RHS = CI->getOperand(0);
2482
Chris Lattner0798af32005-01-13 20:14:25 +00002483 Value *PtrBase = GEPLHS->getOperand(0);
2484 if (PtrBase == RHS) {
2485 // As an optimization, we don't actually have to compute the actual value of
2486 // OFFSET if this is a seteq or setne comparison, just return whether each
2487 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002488 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2489 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002490 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2491 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002492 bool EmitIt = true;
2493 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2494 if (isa<UndefValue>(C)) // undef index -> undef.
2495 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2496 if (C->isNullValue())
2497 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002498 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2499 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002500 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002501 return ReplaceInstUsesWith(I, // No comparison is needed here.
2502 ConstantBool::get(Cond == Instruction::SetNE));
2503 }
2504
2505 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002506 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002507 new SetCondInst(Cond, GEPLHS->getOperand(i),
2508 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2509 if (InVal == 0)
2510 InVal = Comp;
2511 else {
2512 InVal = InsertNewInstBefore(InVal, I);
2513 InsertNewInstBefore(Comp, I);
2514 if (Cond == Instruction::SetNE) // True if any are unequal
2515 InVal = BinaryOperator::createOr(InVal, Comp);
2516 else // True if all are equal
2517 InVal = BinaryOperator::createAnd(InVal, Comp);
2518 }
2519 }
2520 }
2521
2522 if (InVal)
2523 return InVal;
2524 else
2525 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2526 ConstantBool::get(Cond == Instruction::SetEQ));
2527 }
Chris Lattner0798af32005-01-13 20:14:25 +00002528
2529 // Only lower this if the setcc is the only user of the GEP or if we expect
2530 // the result to fold to a constant!
2531 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2532 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2533 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2534 return new SetCondInst(Cond, Offset,
2535 Constant::getNullValue(Offset->getType()));
2536 }
2537 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002538 // If the base pointers are different, but the indices are the same, just
2539 // compare the base pointer.
2540 if (PtrBase != GEPRHS->getOperand(0)) {
2541 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002542 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002543 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002544 if (IndicesTheSame)
2545 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2546 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2547 IndicesTheSame = false;
2548 break;
2549 }
2550
2551 // If all indices are the same, just compare the base pointers.
2552 if (IndicesTheSame)
2553 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2554 GEPRHS->getOperand(0));
2555
2556 // Otherwise, the base pointers are different and the indices are
2557 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002558 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002559 }
Chris Lattner0798af32005-01-13 20:14:25 +00002560
Chris Lattner81e84172005-01-13 22:25:21 +00002561 // If one of the GEPs has all zero indices, recurse.
2562 bool AllZeros = true;
2563 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2564 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2565 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2566 AllZeros = false;
2567 break;
2568 }
2569 if (AllZeros)
2570 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2571 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002572
2573 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002574 AllZeros = true;
2575 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2576 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2577 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2578 AllZeros = false;
2579 break;
2580 }
2581 if (AllZeros)
2582 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2583
Chris Lattner4fa89822005-01-14 00:20:05 +00002584 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2585 // If the GEPs only differ by one index, compare it.
2586 unsigned NumDifferences = 0; // Keep track of # differences.
2587 unsigned DiffOperand = 0; // The operand that differs.
2588 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2589 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002590 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2591 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002592 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002593 NumDifferences = 2;
2594 break;
2595 } else {
2596 if (NumDifferences++) break;
2597 DiffOperand = i;
2598 }
2599 }
2600
2601 if (NumDifferences == 0) // SAME GEP?
2602 return ReplaceInstUsesWith(I, // No comparison is needed here.
2603 ConstantBool::get(Cond == Instruction::SetEQ));
2604 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002605 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2606 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002607
2608 // Convert the operands to signed values to make sure to perform a
2609 // signed comparison.
2610 const Type *NewTy = LHSV->getType()->getSignedVersion();
2611 if (LHSV->getType() != NewTy)
2612 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2613 LHSV->getName()), I);
2614 if (RHSV->getType() != NewTy)
2615 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2616 RHSV->getName()), I);
2617 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002618 }
2619 }
2620
Chris Lattner0798af32005-01-13 20:14:25 +00002621 // Only lower this if the setcc is the only user of the GEP or if we expect
2622 // the result to fold to a constant!
2623 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2624 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2625 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2626 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2627 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2628 return new SetCondInst(Cond, L, R);
2629 }
2630 }
2631 return 0;
2632}
2633
2634
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002635Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002636 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002637 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2638 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002639
2640 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002641 if (Op0 == Op1)
2642 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002643
Chris Lattner81a7a232004-10-16 18:11:37 +00002644 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2645 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2646
Chris Lattner15ff1e12004-11-14 07:33:16 +00002647 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2648 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002649 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2650 isa<ConstantPointerNull>(Op0)) &&
2651 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002652 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002653 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2654
2655 // setcc's with boolean values can always be turned into bitwise operations
2656 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002657 switch (I.getOpcode()) {
2658 default: assert(0 && "Invalid setcc instruction!");
2659 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002660 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002661 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002662 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002663 }
Chris Lattner4456da62004-08-11 00:50:51 +00002664 case Instruction::SetNE:
2665 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002666
Chris Lattner4456da62004-08-11 00:50:51 +00002667 case Instruction::SetGT:
2668 std::swap(Op0, Op1); // Change setgt -> setlt
2669 // FALL THROUGH
2670 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2671 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2672 InsertNewInstBefore(Not, I);
2673 return BinaryOperator::createAnd(Not, Op1);
2674 }
2675 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002676 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002677 // FALL THROUGH
2678 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2679 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2680 InsertNewInstBefore(Not, I);
2681 return BinaryOperator::createOr(Not, Op1);
2682 }
2683 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002684 }
2685
Chris Lattner2dd01742004-06-09 04:24:29 +00002686 // See if we are doing a comparison between a constant and an instruction that
2687 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002688 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002689 // Check to see if we are comparing against the minimum or maximum value...
2690 if (CI->isMinValue()) {
2691 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2692 return ReplaceInstUsesWith(I, ConstantBool::False);
2693 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2694 return ReplaceInstUsesWith(I, ConstantBool::True);
2695 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2696 return BinaryOperator::createSetEQ(Op0, Op1);
2697 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2698 return BinaryOperator::createSetNE(Op0, Op1);
2699
2700 } else if (CI->isMaxValue()) {
2701 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2702 return ReplaceInstUsesWith(I, ConstantBool::False);
2703 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2704 return ReplaceInstUsesWith(I, ConstantBool::True);
2705 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2706 return BinaryOperator::createSetEQ(Op0, Op1);
2707 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2708 return BinaryOperator::createSetNE(Op0, Op1);
2709
2710 // Comparing against a value really close to min or max?
2711 } else if (isMinValuePlusOne(CI)) {
2712 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2713 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2714 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2715 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2716
2717 } else if (isMaxValueMinusOne(CI)) {
2718 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2719 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2720 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2721 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2722 }
2723
2724 // If we still have a setle or setge instruction, turn it into the
2725 // appropriate setlt or setgt instruction. Since the border cases have
2726 // already been handled above, this requires little checking.
2727 //
2728 if (I.getOpcode() == Instruction::SetLE)
2729 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2730 if (I.getOpcode() == Instruction::SetGE)
2731 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2732
Chris Lattnere1e10e12004-05-25 06:32:08 +00002733 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002734 switch (LHSI->getOpcode()) {
2735 case Instruction::And:
2736 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2737 LHSI->getOperand(0)->hasOneUse()) {
2738 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2739 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2740 // happens a LOT in code produced by the C front-end, for bitfield
2741 // access.
2742 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2743 ConstantUInt *ShAmt;
2744 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2745 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2746 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002747
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002748 // We can fold this as long as we can't shift unknown bits
2749 // into the mask. This can only happen with signed shift
2750 // rights, as they sign-extend.
2751 if (ShAmt) {
2752 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002753 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002754 if (!CanFold) {
2755 // To test for the bad case of the signed shr, see if any
2756 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002757 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2758 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2759
2760 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002761 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002762 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2763 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2764 CanFold = true;
2765 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002766
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002767 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002768 Constant *NewCst;
2769 if (Shift->getOpcode() == Instruction::Shl)
2770 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2771 else
2772 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002773
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002774 // Check to see if we are shifting out any of the bits being
2775 // compared.
2776 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2777 // If we shifted bits out, the fold is not going to work out.
2778 // As a special case, check to see if this means that the
2779 // result is always true or false now.
2780 if (I.getOpcode() == Instruction::SetEQ)
2781 return ReplaceInstUsesWith(I, ConstantBool::False);
2782 if (I.getOpcode() == Instruction::SetNE)
2783 return ReplaceInstUsesWith(I, ConstantBool::True);
2784 } else {
2785 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002786 Constant *NewAndCST;
2787 if (Shift->getOpcode() == Instruction::Shl)
2788 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2789 else
2790 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2791 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002792 LHSI->setOperand(0, Shift->getOperand(0));
2793 WorkList.push_back(Shift); // Shift is dead.
2794 AddUsesToWorkList(I);
2795 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002796 }
2797 }
Chris Lattner35167c32004-06-09 07:59:58 +00002798 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002799 }
2800 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002801
Chris Lattner272d5ca2004-09-28 18:22:15 +00002802 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2803 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2804 switch (I.getOpcode()) {
2805 default: break;
2806 case Instruction::SetEQ:
2807 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002808 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2809
2810 // Check that the shift amount is in range. If not, don't perform
2811 // undefined shifts. When the shift is visited it will be
2812 // simplified.
2813 if (ShAmt->getValue() >= TypeBits)
2814 break;
2815
Chris Lattner272d5ca2004-09-28 18:22:15 +00002816 // If we are comparing against bits always shifted out, the
2817 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002818 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002819 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2820 if (Comp != CI) {// Comparing against a bit that we know is zero.
2821 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2822 Constant *Cst = ConstantBool::get(IsSetNE);
2823 return ReplaceInstUsesWith(I, Cst);
2824 }
2825
2826 if (LHSI->hasOneUse()) {
2827 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002828 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002829 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2830
2831 Constant *Mask;
2832 if (CI->getType()->isUnsigned()) {
2833 Mask = ConstantUInt::get(CI->getType(), Val);
2834 } else if (ShAmtVal != 0) {
2835 Mask = ConstantSInt::get(CI->getType(), Val);
2836 } else {
2837 Mask = ConstantInt::getAllOnesValue(CI->getType());
2838 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002839
Chris Lattner272d5ca2004-09-28 18:22:15 +00002840 Instruction *AndI =
2841 BinaryOperator::createAnd(LHSI->getOperand(0),
2842 Mask, LHSI->getName()+".mask");
2843 Value *And = InsertNewInstBefore(AndI, I);
2844 return new SetCondInst(I.getOpcode(), And,
2845 ConstantExpr::getUShr(CI, ShAmt));
2846 }
2847 }
2848 }
2849 }
2850 break;
2851
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002852 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002853 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002854 switch (I.getOpcode()) {
2855 default: break;
2856 case Instruction::SetEQ:
2857 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002858
2859 // Check that the shift amount is in range. If not, don't perform
2860 // undefined shifts. When the shift is visited it will be
2861 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002862 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002863 if (ShAmt->getValue() >= TypeBits)
2864 break;
2865
Chris Lattner1023b872004-09-27 16:18:50 +00002866 // If we are comparing against bits always shifted out, the
2867 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002868 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002869 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002870
Chris Lattner1023b872004-09-27 16:18:50 +00002871 if (Comp != CI) {// Comparing against a bit that we know is zero.
2872 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2873 Constant *Cst = ConstantBool::get(IsSetNE);
2874 return ReplaceInstUsesWith(I, Cst);
2875 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002876
Chris Lattner1023b872004-09-27 16:18:50 +00002877 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002878 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002879
Chris Lattner1023b872004-09-27 16:18:50 +00002880 // Otherwise strength reduce the shift into an and.
2881 uint64_t Val = ~0ULL; // All ones.
2882 Val <<= ShAmtVal; // Shift over to the right spot.
2883
2884 Constant *Mask;
2885 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002886 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002887 Mask = ConstantUInt::get(CI->getType(), Val);
2888 } else {
2889 Mask = ConstantSInt::get(CI->getType(), Val);
2890 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002891
Chris Lattner1023b872004-09-27 16:18:50 +00002892 Instruction *AndI =
2893 BinaryOperator::createAnd(LHSI->getOperand(0),
2894 Mask, LHSI->getName()+".mask");
2895 Value *And = InsertNewInstBefore(AndI, I);
2896 return new SetCondInst(I.getOpcode(), And,
2897 ConstantExpr::getShl(CI, ShAmt));
2898 }
2899 break;
2900 }
2901 }
2902 }
2903 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002904
Chris Lattner6862fbd2004-09-29 17:40:11 +00002905 case Instruction::Div:
2906 // Fold: (div X, C1) op C2 -> range check
2907 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2908 // Fold this div into the comparison, producing a range check.
2909 // Determine, based on the divide type, what the range is being
2910 // checked. If there is an overflow on the low or high side, remember
2911 // it, otherwise compute the range [low, hi) bounding the new value.
2912 bool LoOverflow = false, HiOverflow = 0;
2913 ConstantInt *LoBound = 0, *HiBound = 0;
2914
2915 ConstantInt *Prod;
2916 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2917
Chris Lattnera92af962004-10-11 19:40:04 +00002918 Instruction::BinaryOps Opcode = I.getOpcode();
2919
Chris Lattner6862fbd2004-09-29 17:40:11 +00002920 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2921 } else if (LHSI->getType()->isUnsigned()) { // udiv
2922 LoBound = Prod;
2923 LoOverflow = ProdOV;
2924 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2925 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2926 if (CI->isNullValue()) { // (X / pos) op 0
2927 // Can't overflow.
2928 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2929 HiBound = DivRHS;
2930 } else if (isPositive(CI)) { // (X / pos) op pos
2931 LoBound = Prod;
2932 LoOverflow = ProdOV;
2933 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2934 } else { // (X / pos) op neg
2935 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2936 LoOverflow = AddWithOverflow(LoBound, Prod,
2937 cast<ConstantInt>(DivRHSH));
2938 HiBound = Prod;
2939 HiOverflow = ProdOV;
2940 }
2941 } else { // Divisor is < 0.
2942 if (CI->isNullValue()) { // (X / neg) op 0
2943 LoBound = AddOne(DivRHS);
2944 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002945 if (HiBound == DivRHS)
2946 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002947 } else if (isPositive(CI)) { // (X / neg) op pos
2948 HiOverflow = LoOverflow = ProdOV;
2949 if (!LoOverflow)
2950 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2951 HiBound = AddOne(Prod);
2952 } else { // (X / neg) op neg
2953 LoBound = Prod;
2954 LoOverflow = HiOverflow = ProdOV;
2955 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2956 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002957
Chris Lattnera92af962004-10-11 19:40:04 +00002958 // Dividing by a negate swaps the condition.
2959 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002960 }
2961
2962 if (LoBound) {
2963 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002964 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002965 default: assert(0 && "Unhandled setcc opcode!");
2966 case Instruction::SetEQ:
2967 if (LoOverflow && HiOverflow)
2968 return ReplaceInstUsesWith(I, ConstantBool::False);
2969 else if (HiOverflow)
2970 return new SetCondInst(Instruction::SetGE, X, LoBound);
2971 else if (LoOverflow)
2972 return new SetCondInst(Instruction::SetLT, X, HiBound);
2973 else
2974 return InsertRangeTest(X, LoBound, HiBound, true, I);
2975 case Instruction::SetNE:
2976 if (LoOverflow && HiOverflow)
2977 return ReplaceInstUsesWith(I, ConstantBool::True);
2978 else if (HiOverflow)
2979 return new SetCondInst(Instruction::SetLT, X, LoBound);
2980 else if (LoOverflow)
2981 return new SetCondInst(Instruction::SetGE, X, HiBound);
2982 else
2983 return InsertRangeTest(X, LoBound, HiBound, false, I);
2984 case Instruction::SetLT:
2985 if (LoOverflow)
2986 return ReplaceInstUsesWith(I, ConstantBool::False);
2987 return new SetCondInst(Instruction::SetLT, X, LoBound);
2988 case Instruction::SetGT:
2989 if (HiOverflow)
2990 return ReplaceInstUsesWith(I, ConstantBool::False);
2991 return new SetCondInst(Instruction::SetGE, X, HiBound);
2992 }
2993 }
2994 }
2995 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002996 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002997
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002998 // Simplify seteq and setne instructions...
2999 if (I.getOpcode() == Instruction::SetEQ ||
3000 I.getOpcode() == Instruction::SetNE) {
3001 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3002
Chris Lattnercfbce7c2003-07-23 17:26:36 +00003003 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003004 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00003005 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3006 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00003007 case Instruction::Rem:
3008 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3009 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3010 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00003011 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3012 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3013 if (isPowerOf2_64(V)) {
3014 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00003015 const Type *UTy = BO->getType()->getUnsignedVersion();
3016 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3017 UTy, "tmp"), I);
3018 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3019 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3020 RHSCst, BO->getName()), I);
3021 return BinaryOperator::create(I.getOpcode(), NewRem,
3022 Constant::getNullValue(UTy));
3023 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003024 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003025 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003026
Chris Lattnerc992add2003-08-13 05:33:12 +00003027 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003028 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3029 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003030 if (BO->hasOneUse())
3031 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3032 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003033 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003034 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3035 // efficiently invertible, or if the add has just this one use.
3036 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003037
Chris Lattnerc992add2003-08-13 05:33:12 +00003038 if (Value *NegVal = dyn_castNegVal(BOp1))
3039 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3040 else if (Value *NegVal = dyn_castNegVal(BOp0))
3041 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003042 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003043 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3044 BO->setName("");
3045 InsertNewInstBefore(Neg, I);
3046 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3047 }
3048 }
3049 break;
3050 case Instruction::Xor:
3051 // For the xor case, we can xor two constants together, eliminating
3052 // the explicit xor.
3053 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3054 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003055 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003056
3057 // FALLTHROUGH
3058 case Instruction::Sub:
3059 // Replace (([sub|xor] A, B) != 0) with (A != B)
3060 if (CI->isNullValue())
3061 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3062 BO->getOperand(1));
3063 break;
3064
3065 case Instruction::Or:
3066 // If bits are being or'd in that are not present in the constant we
3067 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003068 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003069 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003070 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003071 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003072 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003073 break;
3074
3075 case Instruction::And:
3076 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003077 // If bits are being compared against that are and'd out, then the
3078 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003079 if (!ConstantExpr::getAnd(CI,
3080 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003081 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003082
Chris Lattner35167c32004-06-09 07:59:58 +00003083 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003084 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003085 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3086 Instruction::SetNE, Op0,
3087 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003088
Chris Lattnerc992add2003-08-13 05:33:12 +00003089 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3090 // to be a signed value as appropriate.
3091 if (isSignBit(BOC)) {
3092 Value *X = BO->getOperand(0);
3093 // If 'X' is not signed, insert a cast now...
3094 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003095 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003096 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003097 }
3098 return new SetCondInst(isSetNE ? Instruction::SetLT :
3099 Instruction::SetGE, X,
3100 Constant::getNullValue(X->getType()));
3101 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003102
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003103 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003104 if (CI->isNullValue() && isHighOnes(BOC)) {
3105 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003106 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003107
3108 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003109 if (NegX->getType()->isSigned()) {
3110 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3111 X = InsertCastBefore(X, DestTy, I);
3112 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003113 }
3114
3115 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003116 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003117 }
3118
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003119 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003120 default: break;
3121 }
3122 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003123 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003124 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003125 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3126 Value *CastOp = Cast->getOperand(0);
3127 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003128 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003129 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003130 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003131 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003132 "Source and destination signednesses should differ!");
3133 if (Cast->getType()->isSigned()) {
3134 // If this is a signed comparison, check for comparisons in the
3135 // vicinity of zero.
3136 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3137 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003138 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003139 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003140 else if (I.getOpcode() == Instruction::SetGT &&
3141 cast<ConstantSInt>(CI)->getValue() == -1)
3142 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003143 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003144 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003145 } else {
3146 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3147 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003148 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003149 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003150 return BinaryOperator::createSetGT(CastOp,
3151 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003152 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003153 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003154 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003155 return BinaryOperator::createSetLT(CastOp,
3156 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003157 }
3158 }
3159 }
Chris Lattnere967b342003-06-04 05:10:11 +00003160 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003161 }
3162
Chris Lattner77c32c32005-04-23 15:31:55 +00003163 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3164 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3165 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3166 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003167 case Instruction::GetElementPtr:
3168 if (RHSC->isNullValue()) {
3169 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3170 bool isAllZeros = true;
3171 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3172 if (!isa<Constant>(LHSI->getOperand(i)) ||
3173 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3174 isAllZeros = false;
3175 break;
3176 }
3177 if (isAllZeros)
3178 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3179 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3180 }
3181 break;
3182
Chris Lattner77c32c32005-04-23 15:31:55 +00003183 case Instruction::PHI:
3184 if (Instruction *NV = FoldOpIntoPhi(I))
3185 return NV;
3186 break;
3187 case Instruction::Select:
3188 // If either operand of the select is a constant, we can fold the
3189 // comparison into the select arms, which will cause one to be
3190 // constant folded and the select turned into a bitwise or.
3191 Value *Op1 = 0, *Op2 = 0;
3192 if (LHSI->hasOneUse()) {
3193 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3194 // Fold the known value into the constant operand.
3195 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3196 // Insert a new SetCC of the other select operand.
3197 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3198 LHSI->getOperand(2), RHSC,
3199 I.getName()), I);
3200 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3201 // Fold the known value into the constant operand.
3202 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3203 // Insert a new SetCC of the other select operand.
3204 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3205 LHSI->getOperand(1), RHSC,
3206 I.getName()), I);
3207 }
3208 }
Jeff Cohen82639852005-04-23 21:38:35 +00003209
Chris Lattner77c32c32005-04-23 15:31:55 +00003210 if (Op1)
3211 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3212 break;
3213 }
3214 }
3215
Chris Lattner0798af32005-01-13 20:14:25 +00003216 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3217 if (User *GEP = dyn_castGetElementPtr(Op0))
3218 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3219 return NI;
3220 if (User *GEP = dyn_castGetElementPtr(Op1))
3221 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3222 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3223 return NI;
3224
Chris Lattner16930792003-11-03 04:25:02 +00003225 // Test to see if the operands of the setcc are casted versions of other
3226 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003227 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3228 Value *CastOp0 = CI->getOperand(0);
3229 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003230 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003231 (I.getOpcode() == Instruction::SetEQ ||
3232 I.getOpcode() == Instruction::SetNE)) {
3233 // We keep moving the cast from the left operand over to the right
3234 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003235 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003236
Chris Lattner16930792003-11-03 04:25:02 +00003237 // If operand #1 is a cast instruction, see if we can eliminate it as
3238 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003239 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3240 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003241 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003242 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003243
Chris Lattner16930792003-11-03 04:25:02 +00003244 // If Op1 is a constant, we can fold the cast into the constant.
3245 if (Op1->getType() != Op0->getType())
3246 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3247 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3248 } else {
3249 // Otherwise, cast the RHS right before the setcc
3250 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3251 InsertNewInstBefore(cast<Instruction>(Op1), I);
3252 }
3253 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3254 }
3255
Chris Lattner6444c372003-11-03 05:17:03 +00003256 // Handle the special case of: setcc (cast bool to X), <cst>
3257 // This comes up when you have code like
3258 // int X = A < B;
3259 // if (X) ...
3260 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003261 // with a constant or another cast from the same type.
3262 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3263 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3264 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003265 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003266 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003267}
3268
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003269// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3270// We only handle extending casts so far.
3271//
3272Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3273 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3274 const Type *SrcTy = LHSCIOp->getType();
3275 const Type *DestTy = SCI.getOperand(0)->getType();
3276 Value *RHSCIOp;
3277
3278 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003279 return 0;
3280
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003281 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3282 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3283 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3284
3285 // Is this a sign or zero extension?
3286 bool isSignSrc = SrcTy->isSigned();
3287 bool isSignDest = DestTy->isSigned();
3288
3289 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3290 // Not an extension from the same type?
3291 RHSCIOp = CI->getOperand(0);
3292 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3293 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3294 // Compute the constant that would happen if we truncated to SrcTy then
3295 // reextended to DestTy.
3296 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3297
3298 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3299 RHSCIOp = Res;
3300 } else {
3301 // If the value cannot be represented in the shorter type, we cannot emit
3302 // a simple comparison.
3303 if (SCI.getOpcode() == Instruction::SetEQ)
3304 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3305 if (SCI.getOpcode() == Instruction::SetNE)
3306 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3307
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003308 // Evaluate the comparison for LT.
3309 Value *Result;
3310 if (DestTy->isSigned()) {
3311 // We're performing a signed comparison.
3312 if (isSignSrc) {
3313 // Signed extend and signed comparison.
3314 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3315 Result = ConstantBool::False;
3316 else
3317 Result = ConstantBool::True; // X < (large) --> true
3318 } else {
3319 // Unsigned extend and signed comparison.
3320 if (cast<ConstantSInt>(CI)->getValue() < 0)
3321 Result = ConstantBool::False;
3322 else
3323 Result = ConstantBool::True;
3324 }
3325 } else {
3326 // We're performing an unsigned comparison.
3327 if (!isSignSrc) {
3328 // Unsigned extend & compare -> always true.
3329 Result = ConstantBool::True;
3330 } else {
3331 // We're performing an unsigned comp with a sign extended value.
3332 // This is true if the input is >= 0. [aka >s -1]
3333 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3334 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3335 NegOne, SCI.getName()), SCI);
3336 }
Reid Spencer279fa252004-11-28 21:31:15 +00003337 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003338
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003339 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003340 if (SCI.getOpcode() == Instruction::SetLT) {
3341 return ReplaceInstUsesWith(SCI, Result);
3342 } else {
3343 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3344 if (Constant *CI = dyn_cast<Constant>(Result))
3345 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3346 else
3347 return BinaryOperator::createNot(Result);
3348 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003349 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003350 } else {
3351 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003352 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003353
Chris Lattner252a8452005-06-16 03:00:08 +00003354 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003355 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3356}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003357
Chris Lattnere8d6c602003-03-10 19:16:08 +00003358Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003359 assert(I.getOperand(1)->getType() == Type::UByteTy);
3360 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003361 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003362
3363 // shl X, 0 == X and shr X, 0 == X
3364 // shl 0, X == 0 and shr 0, X == 0
3365 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003366 Op0 == Constant::getNullValue(Op0->getType()))
3367 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003368
Chris Lattner81a7a232004-10-16 18:11:37 +00003369 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3370 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003371 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003372 else // undef << X -> 0 AND undef >>u X -> 0
3373 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3374 }
3375 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003376 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003377 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3378 else
3379 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3380 }
3381
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003382 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3383 if (!isLeftShift)
3384 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3385 if (CSI->isAllOnesValue())
3386 return ReplaceInstUsesWith(I, CSI);
3387
Chris Lattner183b3362004-04-09 19:05:30 +00003388 // Try to fold constant and into select arguments.
3389 if (isa<Constant>(Op0))
3390 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003391 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003392 return R;
3393
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003394 // See if we can turn a signed shr into an unsigned shr.
3395 if (!isLeftShift && I.getType()->isSigned()) {
3396 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3397 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3398 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3399 I.getName()), I);
3400 return new CastInst(V, I.getType());
3401 }
3402 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003403
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003404 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003405 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3406 // of a signed value.
3407 //
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003408 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003409 if (CUI->getValue() >= TypeBits) {
3410 if (!Op0->getType()->isSigned() || isLeftShift)
3411 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3412 else {
3413 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3414 return &I;
3415 }
3416 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003417
Chris Lattnerede3fe02003-08-13 04:18:28 +00003418 // ((X*C1) << C2) == (X * (C1 << C2))
3419 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3420 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3421 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003422 return BinaryOperator::createMul(BO->getOperand(0),
3423 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanb1c93172005-04-21 23:48:37 +00003424
Chris Lattner183b3362004-04-09 19:05:30 +00003425 // Try to fold constant and into select arguments.
3426 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003427 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003428 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003429 if (isa<PHINode>(Op0))
3430 if (Instruction *NV = FoldOpIntoPhi(I))
3431 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003432
Chris Lattner86102b82005-01-01 16:22:27 +00003433 if (Op0->hasOneUse()) {
3434 // If this is a SHL of a sign-extending cast, see if we can turn the input
3435 // into a zero extending cast (a simple strength reduction).
3436 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3437 const Type *SrcTy = CI->getOperand(0)->getType();
3438 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003439 SrcTy->getPrimitiveSizeInBits() <
3440 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00003441 // We can change it to a zero extension if we are shifting out all of
3442 // the sign extended bits. To check this, form a mask of all of the
3443 // sign extend bits, then shift them left and see if we have anything
3444 // left.
3445 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3446 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3447 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3448 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3449 // If the shift is nuking all of the sign bits, change this to a
3450 // zero extension cast. To do this, cast the cast input to
3451 // unsigned, then to the requested size.
3452 Value *CastOp = CI->getOperand(0);
3453 Instruction *NC =
3454 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3455 CI->getName()+".uns");
3456 NC = InsertNewInstBefore(NC, I);
3457 // Finally, insert a replacement for CI.
3458 NC = new CastInst(NC, CI->getType(), CI->getName());
3459 CI->setName("");
3460 NC = InsertNewInstBefore(NC, I);
3461 WorkList.push_back(CI); // Delete CI later.
3462 I.setOperand(0, NC);
3463 return &I; // The SHL operand was modified.
3464 }
3465 }
3466 }
3467
Chris Lattner27cb9db2005-09-18 05:12:10 +00003468 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3469 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Jeff Cohen572910c2005-10-07 05:28:29 +00003470 Value *V1, *V2;
Chris Lattner797dee72005-09-18 06:30:59 +00003471 ConstantInt *CC;
Chris Lattner27cb9db2005-09-18 05:12:10 +00003472 switch (Op0BO->getOpcode()) {
3473 default: break;
3474 case Instruction::Add:
3475 case Instruction::And:
3476 case Instruction::Or:
3477 case Instruction::Xor:
3478 // These operators commute.
3479 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003480 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3481 match(Op0BO->getOperand(1),
3482 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3483 Instruction *YS = new ShiftInst(Instruction::Shl,
3484 Op0BO->getOperand(0), CUI,
3485 Op0BO->getName());
3486 InsertNewInstBefore(YS, I); // (Y << C)
3487 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3488 V1,
3489 Op0BO->getOperand(1)->getName());
3490 InsertNewInstBefore(X, I); // (X + (Y << C))
3491 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3492 C2 = ConstantExpr::getShl(C2, CUI);
3493 return BinaryOperator::createAnd(X, C2);
3494 }
3495
3496 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3497 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3498 match(Op0BO->getOperand(1),
3499 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3500 m_ConstantInt(CC))) && V2 == CUI &&
3501 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3502 Instruction *YS = new ShiftInst(Instruction::Shl,
3503 Op0BO->getOperand(0), CUI,
3504 Op0BO->getName());
3505 InsertNewInstBefore(YS, I); // (Y << C)
3506 Instruction *XM =
3507 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3508 V1->getName()+".mask");
3509 InsertNewInstBefore(XM, I); // X & (CC << C)
3510
3511 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3512 }
3513
3514 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00003515 case Instruction::Sub:
3516 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003517 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3518 match(Op0BO->getOperand(0),
3519 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3520 Instruction *YS = new ShiftInst(Instruction::Shl,
3521 Op0BO->getOperand(1), CUI,
3522 Op0BO->getName());
3523 InsertNewInstBefore(YS, I); // (Y << C)
3524 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3525 V1,
3526 Op0BO->getOperand(0)->getName());
3527 InsertNewInstBefore(X, I); // (X + (Y << C))
3528 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3529 C2 = ConstantExpr::getShl(C2, CUI);
3530 return BinaryOperator::createAnd(X, C2);
3531 }
3532
3533 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3534 match(Op0BO->getOperand(0),
3535 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3536 m_ConstantInt(CC))) && V2 == CUI &&
3537 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3538 Instruction *YS = new ShiftInst(Instruction::Shl,
3539 Op0BO->getOperand(1), CUI,
3540 Op0BO->getName());
3541 InsertNewInstBefore(YS, I); // (Y << C)
3542 Instruction *XM =
3543 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3544 V1->getName()+".mask");
3545 InsertNewInstBefore(XM, I); // X & (CC << C)
3546
3547 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3548 }
3549
Chris Lattner27cb9db2005-09-18 05:12:10 +00003550 break;
3551 }
3552
3553
3554 // If the operand is an bitwise operator with a constant RHS, and the
3555 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003556 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3557 bool isValid = true; // Valid only for And, Or, Xor
3558 bool highBitSet = false; // Transform if high bit of constant set?
3559
3560 switch (Op0BO->getOpcode()) {
3561 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003562 case Instruction::Add:
3563 isValid = isLeftShift;
3564 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003565 case Instruction::Or:
3566 case Instruction::Xor:
3567 highBitSet = false;
3568 break;
3569 case Instruction::And:
3570 highBitSet = true;
3571 break;
3572 }
3573
3574 // If this is a signed shift right, and the high bit is modified
3575 // by the logical operation, do not perform the transformation.
3576 // The highBitSet boolean indicates the value of the high bit of
3577 // the constant which would cause it to be modified for this
3578 // operation.
3579 //
3580 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3581 uint64_t Val = Op0C->getRawValue();
3582 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3583 }
3584
3585 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003586 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003587
3588 Instruction *NewShift =
3589 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3590 Op0BO->getName());
3591 Op0BO->setName("");
3592 InsertNewInstBefore(NewShift, I);
3593
3594 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3595 NewRHS);
3596 }
3597 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00003598 }
Chris Lattner86102b82005-01-01 16:22:27 +00003599 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003600
Chris Lattner3204d4e2003-07-24 17:52:58 +00003601 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003602 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003603 if (ConstantUInt *ShiftAmt1C =
3604 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003605 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3606 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003607
Chris Lattner3204d4e2003-07-24 17:52:58 +00003608 // Check for (A << c1) << c2 and (A >> c1) >> c2
3609 if (I.getOpcode() == Op0SI->getOpcode()) {
3610 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003611 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3612 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003613 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3614 ConstantUInt::get(Type::UByteTy, Amt));
3615 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003616
Chris Lattnerab780df2003-07-24 18:38:56 +00003617 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3618 // signed types, we can only support the (A >> c1) << c2 configuration,
3619 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003620 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003621 // Calculate bitmask for what gets shifted off the edge...
3622 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003623 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003624 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003625 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003626 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003627
Chris Lattner3204d4e2003-07-24 17:52:58 +00003628 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003629 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3630 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003631 InsertNewInstBefore(Mask, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003632
Chris Lattner3204d4e2003-07-24 17:52:58 +00003633 // Figure out what flavor of shift we should use...
3634 if (ShiftAmt1 == ShiftAmt2)
3635 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3636 else if (ShiftAmt1 < ShiftAmt2) {
3637 return new ShiftInst(I.getOpcode(), Mask,
3638 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3639 } else {
3640 return new ShiftInst(Op0SI->getOpcode(), Mask,
3641 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3642 }
Chris Lattner0b3557f2005-09-24 23:43:33 +00003643 } else {
3644 // We can handle signed (X << C1) >> C2 if it's a sign extend. In
3645 // this case, C1 == C2 and C1 is 8, 16, or 32.
3646 if (ShiftAmt1 == ShiftAmt2) {
3647 const Type *SExtType = 0;
3648 switch (ShiftAmt1) {
3649 case 8 : SExtType = Type::SByteTy; break;
3650 case 16: SExtType = Type::ShortTy; break;
3651 case 32: SExtType = Type::IntTy; break;
3652 }
3653
3654 if (SExtType) {
3655 Instruction *NewTrunc = new CastInst(Op0SI->getOperand(0),
3656 SExtType, "sext");
3657 InsertNewInstBefore(NewTrunc, I);
3658 return new CastInst(NewTrunc, I.getType());
3659 }
3660 }
Chris Lattner3204d4e2003-07-24 17:52:58 +00003661 }
3662 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003663 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003664
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003665 return 0;
3666}
3667
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003668enum CastType {
3669 Noop = 0,
3670 Truncate = 1,
3671 Signext = 2,
3672 Zeroext = 3
3673};
3674
3675/// getCastType - In the future, we will split the cast instruction into these
3676/// various types. Until then, we have to do the analysis here.
3677static CastType getCastType(const Type *Src, const Type *Dest) {
3678 assert(Src->isIntegral() && Dest->isIntegral() &&
3679 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003680 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3681 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003682
3683 if (SrcSize == DestSize) return Noop;
3684 if (SrcSize > DestSize) return Truncate;
3685 if (Src->isSigned()) return Signext;
3686 return Zeroext;
3687}
3688
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003689
Chris Lattner48a44f72002-05-02 17:06:02 +00003690// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3691// instruction.
3692//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003693static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003694 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003695
Chris Lattner650b6da2002-08-02 20:00:25 +00003696 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003697 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003698 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003699 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003700 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003701
Chris Lattner4fbad962004-07-21 04:27:24 +00003702 // If we are casting between pointer and integer types, treat pointers as
3703 // integers of the appropriate size for the code below.
3704 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3705 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3706 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003707
Chris Lattner48a44f72002-05-02 17:06:02 +00003708 // Allow free casting and conversion of sizes as long as the sign doesn't
3709 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003710 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003711 CastType FirstCast = getCastType(SrcTy, MidTy);
3712 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003713
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003714 // Capture the effect of these two casts. If the result is a legal cast,
3715 // the CastType is stored here, otherwise a special code is used.
3716 static const unsigned CastResult[] = {
3717 // First cast is noop
3718 0, 1, 2, 3,
3719 // First cast is a truncate
3720 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3721 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003722 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003723 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003724 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003725 };
3726
3727 unsigned Result = CastResult[FirstCast*4+SecondCast];
3728 switch (Result) {
3729 default: assert(0 && "Illegal table value!");
3730 case 0:
3731 case 1:
3732 case 2:
3733 case 3:
3734 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3735 // truncates, we could eliminate more casts.
3736 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3737 case 4:
3738 return false; // Not possible to eliminate this here.
3739 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003740 // Sign or zero extend followed by truncate is always ok if the result
3741 // is a truncate or noop.
3742 CastType ResultCast = getCastType(SrcTy, DstTy);
3743 if (ResultCast == Noop || ResultCast == Truncate)
3744 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003745 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003746 // result will match the sign/zeroextendness of the result.
3747 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003748 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003749 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003750 return false;
3751}
3752
Chris Lattner11ffd592004-07-20 05:21:00 +00003753static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003754 if (V->getType() == Ty || isa<Constant>(V)) return false;
3755 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003756 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3757 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003758 return false;
3759 return true;
3760}
3761
3762/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3763/// InsertBefore instruction. This is specialized a bit to avoid inserting
3764/// casts that are known to not do anything...
3765///
3766Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3767 Instruction *InsertBefore) {
3768 if (V->getType() == DestTy) return V;
3769 if (Constant *C = dyn_cast<Constant>(V))
3770 return ConstantExpr::getCast(C, DestTy);
3771
3772 CastInst *CI = new CastInst(V, DestTy, V->getName());
3773 InsertNewInstBefore(CI, *InsertBefore);
3774 return CI;
3775}
Chris Lattner48a44f72002-05-02 17:06:02 +00003776
Chris Lattner8f663e82005-10-29 04:36:15 +00003777/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
3778/// expression. If so, decompose it, returning some value X, such that Val is
3779/// X*Scale+Offset.
3780///
3781static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
3782 unsigned &Offset) {
3783 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
3784 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
3785 Offset = CI->getValue();
3786 Scale = 1;
3787 return ConstantUInt::get(Type::UIntTy, 0);
3788 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
3789 if (I->getNumOperands() == 2) {
3790 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
3791 if (I->getOpcode() == Instruction::Shl) {
3792 // This is a value scaled by '1 << the shift amt'.
3793 Scale = 1U << CUI->getValue();
3794 Offset = 0;
3795 return I->getOperand(0);
3796 } else if (I->getOpcode() == Instruction::Mul) {
3797 // This value is scaled by 'CUI'.
3798 Scale = CUI->getValue();
3799 Offset = 0;
3800 return I->getOperand(0);
3801 } else if (I->getOpcode() == Instruction::Add) {
3802 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
3803 // divisible by C2.
3804 unsigned SubScale;
3805 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
3806 Offset);
3807 Offset += CUI->getValue();
3808 if (SubScale > 1 && (Offset % SubScale == 0)) {
3809 Scale = SubScale;
3810 return SubVal;
3811 }
3812 }
3813 }
3814 }
3815 }
3816
3817 // Otherwise, we can't look past this.
3818 Scale = 1;
3819 Offset = 0;
3820 return Val;
3821}
3822
3823
Chris Lattner216be912005-10-24 06:03:58 +00003824/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
3825/// try to eliminate the cast by moving the type information into the alloc.
3826Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
3827 AllocationInst &AI) {
3828 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattnerbb171802005-10-27 05:53:56 +00003829 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattner216be912005-10-24 06:03:58 +00003830
Chris Lattnerac87beb2005-10-24 06:22:12 +00003831 // Remove any uses of AI that are dead.
3832 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
3833 std::vector<Instruction*> DeadUsers;
3834 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
3835 Instruction *User = cast<Instruction>(*UI++);
3836 if (isInstructionTriviallyDead(User)) {
3837 while (UI != E && *UI == User)
3838 ++UI; // If this instruction uses AI more than once, don't break UI.
3839
3840 // Add operands to the worklist.
3841 AddUsesToWorkList(*User);
3842 ++NumDeadInst;
3843 DEBUG(std::cerr << "IC: DCE: " << *User);
3844
3845 User->eraseFromParent();
3846 removeFromWorkList(User);
3847 }
3848 }
3849
Chris Lattner216be912005-10-24 06:03:58 +00003850 // Get the type really allocated and the type casted to.
3851 const Type *AllocElTy = AI.getAllocatedType();
3852 const Type *CastElTy = PTy->getElementType();
3853 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003854
3855 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
3856 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
3857 if (CastElTyAlign < AllocElTyAlign) return 0;
3858
Chris Lattner46705b22005-10-24 06:35:18 +00003859 // If the allocation has multiple uses, only promote it if we are strictly
3860 // increasing the alignment of the resultant allocation. If we keep it the
3861 // same, we open the door to infinite loops of various kinds.
3862 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
3863
Chris Lattner216be912005-10-24 06:03:58 +00003864 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3865 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattnerbb171802005-10-27 05:53:56 +00003866 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner355ecc02005-10-24 06:26:18 +00003867
Chris Lattner8270c332005-10-29 03:19:53 +00003868 // See if we can satisfy the modulus by pulling a scale out of the array
3869 // size argument.
Chris Lattner8f663e82005-10-29 04:36:15 +00003870 unsigned ArraySizeScale, ArrayOffset;
3871 Value *NumElements = // See if the array size is a decomposable linear expr.
3872 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
3873
Chris Lattner8270c332005-10-29 03:19:53 +00003874 // If we can now satisfy the modulus, by using a non-1 scale, we really can
3875 // do the xform.
Chris Lattner8f663e82005-10-29 04:36:15 +00003876 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
3877 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003878
Chris Lattner8270c332005-10-29 03:19:53 +00003879 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
3880 Value *Amt = 0;
3881 if (Scale == 1) {
3882 Amt = NumElements;
3883 } else {
3884 Amt = ConstantUInt::get(Type::UIntTy, Scale);
3885 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
3886 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
3887 else if (Scale != 1) {
3888 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
3889 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattnerb3ecf962005-10-27 06:12:00 +00003890 }
Chris Lattnerbb171802005-10-27 05:53:56 +00003891 }
3892
Chris Lattner8f663e82005-10-29 04:36:15 +00003893 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
3894 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
3895 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
3896 Amt = InsertNewInstBefore(Tmp, AI);
3897 }
3898
Chris Lattner216be912005-10-24 06:03:58 +00003899 std::string Name = AI.getName(); AI.setName("");
3900 AllocationInst *New;
3901 if (isa<MallocInst>(AI))
3902 New = new MallocInst(CastElTy, Amt, Name);
3903 else
3904 New = new AllocaInst(CastElTy, Amt, Name);
3905 InsertNewInstBefore(New, AI);
Chris Lattner46705b22005-10-24 06:35:18 +00003906
3907 // If the allocation has multiple uses, insert a cast and change all things
3908 // that used it to use the new cast. This will also hack on CI, but it will
3909 // die soon.
3910 if (!AI.hasOneUse()) {
3911 AddUsesToWorkList(AI);
3912 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
3913 InsertNewInstBefore(NewCast, AI);
3914 AI.replaceAllUsesWith(NewCast);
3915 }
Chris Lattner216be912005-10-24 06:03:58 +00003916 return ReplaceInstUsesWith(CI, New);
3917}
3918
3919
Chris Lattner48a44f72002-05-02 17:06:02 +00003920// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003921//
Chris Lattner113f4f42002-06-25 16:13:24 +00003922Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003923 Value *Src = CI.getOperand(0);
3924
Chris Lattner48a44f72002-05-02 17:06:02 +00003925 // If the user is casting a value to the same type, eliminate this cast
3926 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003927 if (CI.getType() == Src->getType())
3928 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003929
Chris Lattner81a7a232004-10-16 18:11:37 +00003930 if (isa<UndefValue>(Src)) // cast undef -> undef
3931 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3932
Chris Lattner48a44f72002-05-02 17:06:02 +00003933 // If casting the result of another cast instruction, try to eliminate this
3934 // one!
3935 //
Chris Lattner86102b82005-01-01 16:22:27 +00003936 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3937 Value *A = CSrc->getOperand(0);
3938 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3939 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003940 // This instruction now refers directly to the cast's src operand. This
3941 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003942 CI.setOperand(0, CSrc->getOperand(0));
3943 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003944 }
3945
Chris Lattner650b6da2002-08-02 20:00:25 +00003946 // If this is an A->B->A cast, and we are dealing with integral types, try
3947 // to convert this into a logical 'and' instruction.
3948 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003949 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003950 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003951 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003952 CSrc->getType()->getPrimitiveSizeInBits() <
3953 CI.getType()->getPrimitiveSizeInBits()&&
3954 A->getType()->getPrimitiveSizeInBits() ==
3955 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003956 assert(CSrc->getType() != Type::ULongTy &&
3957 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00003958 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00003959 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3960 AndValue);
3961 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3962 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3963 if (And->getType() != CI.getType()) {
3964 And->setName(CSrc->getName()+".mask");
3965 InsertNewInstBefore(And, CI);
3966 And = new CastInst(And, CI.getType());
3967 }
3968 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003969 }
3970 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003971
Chris Lattner03841652004-05-25 04:29:21 +00003972 // If this is a cast to bool, turn it into the appropriate setne instruction.
3973 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003974 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003975 Constant::getNullValue(CI.getOperand(0)->getType()));
3976
Chris Lattnerd0d51602003-06-21 23:12:02 +00003977 // If casting the result of a getelementptr instruction with no offset, turn
3978 // this into a cast of the original pointer!
3979 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003980 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003981 bool AllZeroOperands = true;
3982 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3983 if (!isa<Constant>(GEP->getOperand(i)) ||
3984 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3985 AllZeroOperands = false;
3986 break;
3987 }
3988 if (AllZeroOperands) {
3989 CI.setOperand(0, GEP->getOperand(0));
3990 return &CI;
3991 }
3992 }
3993
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003994 // If we are casting a malloc or alloca to a pointer to a type of the same
3995 // size, rewrite the allocation instruction to allocate the "right" type.
3996 //
3997 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattner216be912005-10-24 06:03:58 +00003998 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
3999 return V;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004000
Chris Lattner86102b82005-01-01 16:22:27 +00004001 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4002 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4003 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00004004 if (isa<PHINode>(Src))
4005 if (Instruction *NV = FoldOpIntoPhi(CI))
4006 return NV;
4007
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004008 // If the source value is an instruction with only this use, we can attempt to
4009 // propagate the cast into the instruction. Also, only handle integral types
4010 // for now.
4011 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00004012 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004013 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4014 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004015 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4016 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004017
4018 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4019 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4020
4021 switch (SrcI->getOpcode()) {
4022 case Instruction::Add:
4023 case Instruction::Mul:
4024 case Instruction::And:
4025 case Instruction::Or:
4026 case Instruction::Xor:
4027 // If we are discarding information, or just changing the sign, rewrite.
4028 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4029 // Don't insert two casts if they cannot be eliminated. We allow two
4030 // casts to be inserted if the sizes are the same. This could only be
4031 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00004032 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4033 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004034 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4035 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4036 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4037 ->getOpcode(), Op0c, Op1c);
4038 }
4039 }
Chris Lattner72086162005-05-06 02:07:39 +00004040
4041 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4042 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4043 Op1 == ConstantBool::True &&
4044 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4045 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4046 return BinaryOperator::createXor(New,
4047 ConstantInt::get(CI.getType(), 1));
4048 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004049 break;
4050 case Instruction::Shl:
4051 // Allow changing the sign of the source operand. Do not allow changing
4052 // the size of the shift, UNLESS the shift amount is a constant. We
4053 // mush not change variable sized shifts to a smaller size, because it
4054 // is undefined to shift more bits out than exist in the value.
4055 if (DestBitSize == SrcBitSize ||
4056 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4057 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4058 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4059 }
4060 break;
Chris Lattner87380412005-05-06 04:18:52 +00004061 case Instruction::Shr:
4062 // If this is a signed shr, and if all bits shifted in are about to be
4063 // truncated off, turn it into an unsigned shr to allow greater
4064 // simplifications.
4065 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4066 isa<ConstantInt>(Op1)) {
4067 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4068 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4069 // Convert to unsigned.
4070 Value *N1 = InsertOperandCastBefore(Op0,
4071 Op0->getType()->getUnsignedVersion(), &CI);
4072 // Insert the new shift, which is now unsigned.
4073 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4074 Op1, Src->getName()), CI);
4075 return new CastInst(N1, CI.getType());
4076 }
4077 }
4078 break;
4079
Chris Lattner809dfac2005-05-04 19:10:26 +00004080 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00004081 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00004082 if (Op1C->getRawValue() == 0) {
4083 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004084 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00004085 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00004086 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00004087 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4088 if (CI.getType() == Op0->getType())
4089 return ReplaceInstUsesWith(CI, Op0);
4090 else
4091 return new CastInst(Op0, CI.getType());
4092 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00004093
4094 // If the input is an and with a single bit, shift then simplify.
4095 ConstantInt *AndRHS;
4096 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4097 if (AndRHS->getRawValue() &&
4098 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00004099 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00004100 // Perform an unsigned shr by shiftamt. Convert input to
4101 // unsigned if it is signed.
4102 Value *In = Op0;
4103 if (In->getType()->isSigned())
4104 In = InsertNewInstBefore(new CastInst(In,
4105 In->getType()->getUnsignedVersion(), In->getName()),CI);
4106 // Insert the shift to put the result in the low bit.
4107 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4108 ConstantInt::get(Type::UByteTy, ShiftAmt),
4109 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00004110 if (CI.getType() == In->getType())
4111 return ReplaceInstUsesWith(CI, In);
4112 else
4113 return new CastInst(In, CI.getType());
4114 }
4115 }
4116 }
4117 break;
4118 case Instruction::SetEQ:
4119 // We if we are just checking for a seteq of a single bit and casting it
4120 // to an integer. If so, shift the bit to the appropriate place then
4121 // cast to integer to avoid the comparison.
4122 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4123 // Is Op1C a power of two or zero?
4124 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4125 // cast (X == 1) to int -> X iff X has only the low bit set.
4126 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00004127 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00004128 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4129 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4130 if (CI.getType() == Op0->getType())
4131 return ReplaceInstUsesWith(CI, Op0);
4132 else
4133 return new CastInst(Op0, CI.getType());
4134 }
4135 }
Chris Lattner809dfac2005-05-04 19:10:26 +00004136 }
4137 }
4138 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004139 }
4140 }
Chris Lattnerbb171802005-10-27 05:53:56 +00004141
Chris Lattner260ab202002-04-18 17:39:14 +00004142 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004143}
4144
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004145/// GetSelectFoldableOperands - We want to turn code that looks like this:
4146/// %C = or %A, %B
4147/// %D = select %cond, %C, %A
4148/// into:
4149/// %C = select %cond, %B, 0
4150/// %D = or %A, %C
4151///
4152/// Assuming that the specified instruction is an operand to the select, return
4153/// a bitmask indicating which operands of this instruction are foldable if they
4154/// equal the other incoming value of the select.
4155///
4156static unsigned GetSelectFoldableOperands(Instruction *I) {
4157 switch (I->getOpcode()) {
4158 case Instruction::Add:
4159 case Instruction::Mul:
4160 case Instruction::And:
4161 case Instruction::Or:
4162 case Instruction::Xor:
4163 return 3; // Can fold through either operand.
4164 case Instruction::Sub: // Can only fold on the amount subtracted.
4165 case Instruction::Shl: // Can only fold on the shift amount.
4166 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004167 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004168 default:
4169 return 0; // Cannot fold
4170 }
4171}
4172
4173/// GetSelectFoldableConstant - For the same transformation as the previous
4174/// function, return the identity constant that goes into the select.
4175static Constant *GetSelectFoldableConstant(Instruction *I) {
4176 switch (I->getOpcode()) {
4177 default: assert(0 && "This cannot happen!"); abort();
4178 case Instruction::Add:
4179 case Instruction::Sub:
4180 case Instruction::Or:
4181 case Instruction::Xor:
4182 return Constant::getNullValue(I->getType());
4183 case Instruction::Shl:
4184 case Instruction::Shr:
4185 return Constant::getNullValue(Type::UByteTy);
4186 case Instruction::And:
4187 return ConstantInt::getAllOnesValue(I->getType());
4188 case Instruction::Mul:
4189 return ConstantInt::get(I->getType(), 1);
4190 }
4191}
4192
Chris Lattner411336f2005-01-19 21:50:18 +00004193/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4194/// have the same opcode and only one use each. Try to simplify this.
4195Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4196 Instruction *FI) {
4197 if (TI->getNumOperands() == 1) {
4198 // If this is a non-volatile load or a cast from the same type,
4199 // merge.
4200 if (TI->getOpcode() == Instruction::Cast) {
4201 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4202 return 0;
4203 } else {
4204 return 0; // unknown unary op.
4205 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004206
Chris Lattner411336f2005-01-19 21:50:18 +00004207 // Fold this by inserting a select from the input values.
4208 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4209 FI->getOperand(0), SI.getName()+".v");
4210 InsertNewInstBefore(NewSI, SI);
4211 return new CastInst(NewSI, TI->getType());
4212 }
4213
4214 // Only handle binary operators here.
4215 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4216 return 0;
4217
4218 // Figure out if the operations have any operands in common.
4219 Value *MatchOp, *OtherOpT, *OtherOpF;
4220 bool MatchIsOpZero;
4221 if (TI->getOperand(0) == FI->getOperand(0)) {
4222 MatchOp = TI->getOperand(0);
4223 OtherOpT = TI->getOperand(1);
4224 OtherOpF = FI->getOperand(1);
4225 MatchIsOpZero = true;
4226 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4227 MatchOp = TI->getOperand(1);
4228 OtherOpT = TI->getOperand(0);
4229 OtherOpF = FI->getOperand(0);
4230 MatchIsOpZero = false;
4231 } else if (!TI->isCommutative()) {
4232 return 0;
4233 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4234 MatchOp = TI->getOperand(0);
4235 OtherOpT = TI->getOperand(1);
4236 OtherOpF = FI->getOperand(0);
4237 MatchIsOpZero = true;
4238 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4239 MatchOp = TI->getOperand(1);
4240 OtherOpT = TI->getOperand(0);
4241 OtherOpF = FI->getOperand(1);
4242 MatchIsOpZero = true;
4243 } else {
4244 return 0;
4245 }
4246
4247 // If we reach here, they do have operations in common.
4248 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4249 OtherOpF, SI.getName()+".v");
4250 InsertNewInstBefore(NewSI, SI);
4251
4252 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4253 if (MatchIsOpZero)
4254 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4255 else
4256 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4257 } else {
4258 if (MatchIsOpZero)
4259 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4260 else
4261 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4262 }
4263}
4264
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004265Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004266 Value *CondVal = SI.getCondition();
4267 Value *TrueVal = SI.getTrueValue();
4268 Value *FalseVal = SI.getFalseValue();
4269
4270 // select true, X, Y -> X
4271 // select false, X, Y -> Y
4272 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004273 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004274 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004275 else {
4276 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004277 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004278 }
Chris Lattner533bc492004-03-30 19:37:13 +00004279
4280 // select C, X, X -> X
4281 if (TrueVal == FalseVal)
4282 return ReplaceInstUsesWith(SI, TrueVal);
4283
Chris Lattner81a7a232004-10-16 18:11:37 +00004284 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4285 return ReplaceInstUsesWith(SI, FalseVal);
4286 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4287 return ReplaceInstUsesWith(SI, TrueVal);
4288 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4289 if (isa<Constant>(TrueVal))
4290 return ReplaceInstUsesWith(SI, TrueVal);
4291 else
4292 return ReplaceInstUsesWith(SI, FalseVal);
4293 }
4294
Chris Lattner1c631e82004-04-08 04:43:23 +00004295 if (SI.getType() == Type::BoolTy)
4296 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4297 if (C == ConstantBool::True) {
4298 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004299 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004300 } else {
4301 // Change: A = select B, false, C --> A = and !B, C
4302 Value *NotCond =
4303 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4304 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004305 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004306 }
4307 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4308 if (C == ConstantBool::False) {
4309 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004310 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004311 } else {
4312 // Change: A = select B, C, true --> A = or !B, C
4313 Value *NotCond =
4314 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4315 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004316 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004317 }
4318 }
4319
Chris Lattner183b3362004-04-09 19:05:30 +00004320 // Selecting between two integer constants?
4321 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4322 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4323 // select C, 1, 0 -> cast C to int
4324 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4325 return new CastInst(CondVal, SI.getType());
4326 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4327 // select C, 0, 1 -> cast !C to int
4328 Value *NotCond =
4329 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004330 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004331 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004332 }
Chris Lattner35167c32004-06-09 07:59:58 +00004333
4334 // If one of the constants is zero (we know they can't both be) and we
4335 // have a setcc instruction with zero, and we have an 'and' with the
4336 // non-constant value, eliminate this whole mess. This corresponds to
4337 // cases like this: ((X & 27) ? 27 : 0)
4338 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4339 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4340 if ((IC->getOpcode() == Instruction::SetEQ ||
4341 IC->getOpcode() == Instruction::SetNE) &&
4342 isa<ConstantInt>(IC->getOperand(1)) &&
4343 cast<Constant>(IC->getOperand(1))->isNullValue())
4344 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4345 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004346 isa<ConstantInt>(ICA->getOperand(1)) &&
4347 (ICA->getOperand(1) == TrueValC ||
4348 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004349 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4350 // Okay, now we know that everything is set up, we just don't
4351 // know whether we have a setne or seteq and whether the true or
4352 // false val is the zero.
4353 bool ShouldNotVal = !TrueValC->isNullValue();
4354 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4355 Value *V = ICA;
4356 if (ShouldNotVal)
4357 V = InsertNewInstBefore(BinaryOperator::create(
4358 Instruction::Xor, V, ICA->getOperand(1)), SI);
4359 return ReplaceInstUsesWith(SI, V);
4360 }
Chris Lattner533bc492004-03-30 19:37:13 +00004361 }
Chris Lattner623fba12004-04-10 22:21:27 +00004362
4363 // See if we are selecting two values based on a comparison of the two values.
4364 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4365 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4366 // Transform (X == Y) ? X : Y -> Y
4367 if (SCI->getOpcode() == Instruction::SetEQ)
4368 return ReplaceInstUsesWith(SI, FalseVal);
4369 // Transform (X != Y) ? X : Y -> X
4370 if (SCI->getOpcode() == Instruction::SetNE)
4371 return ReplaceInstUsesWith(SI, TrueVal);
4372 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4373
4374 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4375 // Transform (X == Y) ? Y : X -> X
4376 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00004377 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004378 // Transform (X != Y) ? Y : X -> Y
4379 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00004380 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004381 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4382 }
4383 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004384
Chris Lattnera04c9042005-01-13 22:52:24 +00004385 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4386 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4387 if (TI->hasOneUse() && FI->hasOneUse()) {
4388 bool isInverse = false;
4389 Instruction *AddOp = 0, *SubOp = 0;
4390
Chris Lattner411336f2005-01-19 21:50:18 +00004391 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4392 if (TI->getOpcode() == FI->getOpcode())
4393 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4394 return IV;
4395
4396 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4397 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00004398 if (TI->getOpcode() == Instruction::Sub &&
4399 FI->getOpcode() == Instruction::Add) {
4400 AddOp = FI; SubOp = TI;
4401 } else if (FI->getOpcode() == Instruction::Sub &&
4402 TI->getOpcode() == Instruction::Add) {
4403 AddOp = TI; SubOp = FI;
4404 }
4405
4406 if (AddOp) {
4407 Value *OtherAddOp = 0;
4408 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4409 OtherAddOp = AddOp->getOperand(1);
4410 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4411 OtherAddOp = AddOp->getOperand(0);
4412 }
4413
4414 if (OtherAddOp) {
4415 // So at this point we know we have:
4416 // select C, (add X, Y), (sub X, ?)
4417 // We can do the transform profitably if either 'Y' = '?' or '?' is
4418 // a constant.
4419 if (SubOp->getOperand(1) == AddOp ||
4420 isa<Constant>(SubOp->getOperand(1))) {
4421 Value *NegVal;
4422 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4423 NegVal = ConstantExpr::getNeg(C);
4424 } else {
4425 NegVal = InsertNewInstBefore(
4426 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4427 }
4428
Chris Lattner51726c42005-01-14 17:35:12 +00004429 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004430 Value *NewFalseOp = NegVal;
4431 if (AddOp != TI)
4432 std::swap(NewTrueOp, NewFalseOp);
4433 Instruction *NewSel =
4434 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004435
Chris Lattnera04c9042005-01-13 22:52:24 +00004436 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004437 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004438 }
4439 }
4440 }
4441 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004442
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004443 // See if we can fold the select into one of our operands.
4444 if (SI.getType()->isInteger()) {
4445 // See the comment above GetSelectFoldableOperands for a description of the
4446 // transformation we are doing here.
4447 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4448 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4449 !isa<Constant>(FalseVal))
4450 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4451 unsigned OpToFold = 0;
4452 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4453 OpToFold = 1;
4454 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4455 OpToFold = 2;
4456 }
4457
4458 if (OpToFold) {
4459 Constant *C = GetSelectFoldableConstant(TVI);
4460 std::string Name = TVI->getName(); TVI->setName("");
4461 Instruction *NewSel =
4462 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4463 Name);
4464 InsertNewInstBefore(NewSel, SI);
4465 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4466 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4467 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4468 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4469 else {
4470 assert(0 && "Unknown instruction!!");
4471 }
4472 }
4473 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004474
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004475 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4476 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4477 !isa<Constant>(TrueVal))
4478 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4479 unsigned OpToFold = 0;
4480 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4481 OpToFold = 1;
4482 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4483 OpToFold = 2;
4484 }
4485
4486 if (OpToFold) {
4487 Constant *C = GetSelectFoldableConstant(FVI);
4488 std::string Name = FVI->getName(); FVI->setName("");
4489 Instruction *NewSel =
4490 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4491 Name);
4492 InsertNewInstBefore(NewSel, SI);
4493 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4494 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4495 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4496 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4497 else {
4498 assert(0 && "Unknown instruction!!");
4499 }
4500 }
4501 }
4502 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004503
4504 if (BinaryOperator::isNot(CondVal)) {
4505 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4506 SI.setOperand(1, FalseVal);
4507 SI.setOperand(2, TrueVal);
4508 return &SI;
4509 }
4510
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004511 return 0;
4512}
4513
4514
Chris Lattner970c33a2003-06-19 17:00:31 +00004515// CallInst simplification
4516//
4517Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00004518 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4519 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00004520 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4521 bool Changed = false;
4522
4523 // memmove/cpy/set of zero bytes is a noop.
4524 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4525 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4526
4527 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004528
Chris Lattner00648e12004-10-12 04:52:52 +00004529 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4530 if (CI->getRawValue() == 1) {
4531 // Replace the instruction with just byte operations. We would
4532 // transform other cases to loads/stores, but we don't know if
4533 // alignment is sufficient.
4534 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004535 }
4536
Chris Lattner00648e12004-10-12 04:52:52 +00004537 // If we have a memmove and the source operation is a constant global,
4538 // then the source and dest pointers can't alias, so we can change this
4539 // into a call to memcpy.
4540 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4541 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4542 if (GVSrc->isConstant()) {
4543 Module *M = CI.getParent()->getParent()->getParent();
4544 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4545 CI.getCalledFunction()->getFunctionType());
4546 CI.setOperand(0, MemCpy);
4547 Changed = true;
4548 }
4549
4550 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00004551 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4552 // If this stoppoint is at the same source location as the previous
4553 // stoppoint in the chain, it is not needed.
4554 if (DbgStopPointInst *PrevSPI =
4555 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4556 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4557 SPI->getColNo() == PrevSPI->getColNo()) {
4558 SPI->replaceAllUsesWith(PrevSPI);
4559 return EraseInstFromFunction(CI);
4560 }
Chris Lattner00648e12004-10-12 04:52:52 +00004561 }
4562
Chris Lattneraec3d942003-10-07 22:32:43 +00004563 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00004564}
4565
4566// InvokeInst simplification
4567//
4568Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004569 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004570}
4571
Chris Lattneraec3d942003-10-07 22:32:43 +00004572// visitCallSite - Improvements for call and invoke instructions.
4573//
4574Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004575 bool Changed = false;
4576
4577 // If the callee is a constexpr cast of a function, attempt to move the cast
4578 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004579 if (transformConstExprCastCall(CS)) return 0;
4580
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004581 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004582
Chris Lattner61d9d812005-05-13 07:09:09 +00004583 if (Function *CalleeF = dyn_cast<Function>(Callee))
4584 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4585 Instruction *OldCall = CS.getInstruction();
4586 // If the call and callee calling conventions don't match, this call must
4587 // be unreachable, as the call is undefined.
4588 new StoreInst(ConstantBool::True,
4589 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4590 if (!OldCall->use_empty())
4591 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4592 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4593 return EraseInstFromFunction(*OldCall);
4594 return 0;
4595 }
4596
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004597 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4598 // This instruction is not reachable, just remove it. We insert a store to
4599 // undef so that we know that this code is not reachable, despite the fact
4600 // that we can't modify the CFG here.
4601 new StoreInst(ConstantBool::True,
4602 UndefValue::get(PointerType::get(Type::BoolTy)),
4603 CS.getInstruction());
4604
4605 if (!CS.getInstruction()->use_empty())
4606 CS.getInstruction()->
4607 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4608
4609 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4610 // Don't break the CFG, insert a dummy cond branch.
4611 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4612 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004613 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004614 return EraseInstFromFunction(*CS.getInstruction());
4615 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004616
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004617 const PointerType *PTy = cast<PointerType>(Callee->getType());
4618 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4619 if (FTy->isVarArg()) {
4620 // See if we can optimize any arguments passed through the varargs area of
4621 // the call.
4622 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4623 E = CS.arg_end(); I != E; ++I)
4624 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4625 // If this cast does not effect the value passed through the varargs
4626 // area, we can eliminate the use of the cast.
4627 Value *Op = CI->getOperand(0);
4628 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4629 *I = Op;
4630 Changed = true;
4631 }
4632 }
4633 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004634
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004635 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004636}
4637
Chris Lattner970c33a2003-06-19 17:00:31 +00004638// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4639// attempt to move the cast to the arguments of the call/invoke.
4640//
4641bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4642 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4643 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004644 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004645 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004646 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004647 Instruction *Caller = CS.getInstruction();
4648
4649 // Okay, this is a cast from a function to a different type. Unless doing so
4650 // would cause a type conversion of one of our arguments, change this call to
4651 // be a direct call with arguments casted to the appropriate types.
4652 //
4653 const FunctionType *FT = Callee->getFunctionType();
4654 const Type *OldRetTy = Caller->getType();
4655
Chris Lattner1f7942f2004-01-14 06:06:08 +00004656 // Check to see if we are changing the return type...
4657 if (OldRetTy != FT->getReturnType()) {
4658 if (Callee->isExternal() &&
4659 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4660 !Caller->use_empty())
4661 return false; // Cannot transform this return value...
4662
4663 // If the callsite is an invoke instruction, and the return value is used by
4664 // a PHI node in a successor, we cannot change the return type of the call
4665 // because there is no place to put the cast instruction (without breaking
4666 // the critical edge). Bail out in this case.
4667 if (!Caller->use_empty())
4668 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4669 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4670 UI != E; ++UI)
4671 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4672 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004673 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004674 return false;
4675 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004676
4677 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4678 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004679
Chris Lattner970c33a2003-06-19 17:00:31 +00004680 CallSite::arg_iterator AI = CS.arg_begin();
4681 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4682 const Type *ParamTy = FT->getParamType(i);
4683 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004684 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004685 }
4686
4687 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4688 Callee->isExternal())
4689 return false; // Do not delete arguments unless we have a function body...
4690
4691 // Okay, we decided that this is a safe thing to do: go ahead and start
4692 // inserting cast instructions as necessary...
4693 std::vector<Value*> Args;
4694 Args.reserve(NumActualArgs);
4695
4696 AI = CS.arg_begin();
4697 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4698 const Type *ParamTy = FT->getParamType(i);
4699 if ((*AI)->getType() == ParamTy) {
4700 Args.push_back(*AI);
4701 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004702 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4703 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004704 }
4705 }
4706
4707 // If the function takes more arguments than the call was taking, add them
4708 // now...
4709 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4710 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4711
4712 // If we are removing arguments to the function, emit an obnoxious warning...
4713 if (FT->getNumParams() < NumActualArgs)
4714 if (!FT->isVarArg()) {
4715 std::cerr << "WARNING: While resolving call to function '"
4716 << Callee->getName() << "' arguments were dropped!\n";
4717 } else {
4718 // Add all of the arguments in their promoted form to the arg list...
4719 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4720 const Type *PTy = getPromotedType((*AI)->getType());
4721 if (PTy != (*AI)->getType()) {
4722 // Must promote to pass through va_arg area!
4723 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4724 InsertNewInstBefore(Cast, *Caller);
4725 Args.push_back(Cast);
4726 } else {
4727 Args.push_back(*AI);
4728 }
4729 }
4730 }
4731
4732 if (FT->getReturnType() == Type::VoidTy)
4733 Caller->setName(""); // Void type should not have a name...
4734
4735 Instruction *NC;
4736 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004737 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004738 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004739 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004740 } else {
4741 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004742 if (cast<CallInst>(Caller)->isTailCall())
4743 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004744 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004745 }
4746
4747 // Insert a cast of the return type as necessary...
4748 Value *NV = NC;
4749 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4750 if (NV->getType() != Type::VoidTy) {
4751 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004752
4753 // If this is an invoke instruction, we should insert it after the first
4754 // non-phi, instruction in the normal successor block.
4755 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4756 BasicBlock::iterator I = II->getNormalDest()->begin();
4757 while (isa<PHINode>(I)) ++I;
4758 InsertNewInstBefore(NC, *I);
4759 } else {
4760 // Otherwise, it's a call, just insert cast right after the call instr
4761 InsertNewInstBefore(NC, *Caller);
4762 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004763 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004764 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004765 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004766 }
4767 }
4768
4769 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4770 Caller->replaceAllUsesWith(NV);
4771 Caller->getParent()->getInstList().erase(Caller);
4772 removeFromWorkList(Caller);
4773 return true;
4774}
4775
4776
Chris Lattner7515cab2004-11-14 19:13:23 +00004777// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4778// operator and they all are only used by the PHI, PHI together their
4779// inputs, and do the operation once, to the result of the PHI.
4780Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4781 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4782
4783 // Scan the instruction, looking for input operations that can be folded away.
4784 // If all input operands to the phi are the same instruction (e.g. a cast from
4785 // the same type or "+42") we can pull the operation through the PHI, reducing
4786 // code size and simplifying code.
4787 Constant *ConstantOp = 0;
4788 const Type *CastSrcTy = 0;
4789 if (isa<CastInst>(FirstInst)) {
4790 CastSrcTy = FirstInst->getOperand(0)->getType();
4791 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4792 // Can fold binop or shift if the RHS is a constant.
4793 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4794 if (ConstantOp == 0) return 0;
4795 } else {
4796 return 0; // Cannot fold this operation.
4797 }
4798
4799 // Check to see if all arguments are the same operation.
4800 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4801 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4802 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4803 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4804 return 0;
4805 if (CastSrcTy) {
4806 if (I->getOperand(0)->getType() != CastSrcTy)
4807 return 0; // Cast operation must match.
4808 } else if (I->getOperand(1) != ConstantOp) {
4809 return 0;
4810 }
4811 }
4812
4813 // Okay, they are all the same operation. Create a new PHI node of the
4814 // correct type, and PHI together all of the LHS's of the instructions.
4815 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4816 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004817 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004818
4819 Value *InVal = FirstInst->getOperand(0);
4820 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004821
4822 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004823 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4824 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4825 if (NewInVal != InVal)
4826 InVal = 0;
4827 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4828 }
4829
4830 Value *PhiVal;
4831 if (InVal) {
4832 // The new PHI unions all of the same values together. This is really
4833 // common, so we handle it intelligently here for compile-time speed.
4834 PhiVal = InVal;
4835 delete NewPN;
4836 } else {
4837 InsertNewInstBefore(NewPN, PN);
4838 PhiVal = NewPN;
4839 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004840
Chris Lattner7515cab2004-11-14 19:13:23 +00004841 // Insert and return the new operation.
4842 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004843 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004844 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004845 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004846 else
4847 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004848 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004849}
Chris Lattner48a44f72002-05-02 17:06:02 +00004850
Chris Lattner71536432005-01-17 05:10:15 +00004851/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4852/// that is dead.
4853static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4854 if (PN->use_empty()) return true;
4855 if (!PN->hasOneUse()) return false;
4856
4857 // Remember this node, and if we find the cycle, return.
4858 if (!PotentiallyDeadPHIs.insert(PN).second)
4859 return true;
4860
4861 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4862 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004863
Chris Lattner71536432005-01-17 05:10:15 +00004864 return false;
4865}
4866
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004867// PHINode simplification
4868//
Chris Lattner113f4f42002-06-25 16:13:24 +00004869Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00004870 if (Value *V = PN.hasConstantValue())
4871 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00004872
4873 // If the only user of this instruction is a cast instruction, and all of the
4874 // incoming values are constants, change this PHI to merge together the casted
4875 // constants.
4876 if (PN.hasOneUse())
4877 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4878 if (CI->getType() != PN.getType()) { // noop casts will be folded
4879 bool AllConstant = true;
4880 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4881 if (!isa<Constant>(PN.getIncomingValue(i))) {
4882 AllConstant = false;
4883 break;
4884 }
4885 if (AllConstant) {
4886 // Make a new PHI with all casted values.
4887 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4888 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4889 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4890 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4891 PN.getIncomingBlock(i));
4892 }
4893
4894 // Update the cast instruction.
4895 CI->setOperand(0, New);
4896 WorkList.push_back(CI); // revisit the cast instruction to fold.
4897 WorkList.push_back(New); // Make sure to revisit the new Phi
4898 return &PN; // PN is now dead!
4899 }
4900 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004901
4902 // If all PHI operands are the same operation, pull them through the PHI,
4903 // reducing code size.
4904 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4905 PN.getIncomingValue(0)->hasOneUse())
4906 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4907 return Result;
4908
Chris Lattner71536432005-01-17 05:10:15 +00004909 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4910 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4911 // PHI)... break the cycle.
4912 if (PN.hasOneUse())
4913 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4914 std::set<PHINode*> PotentiallyDeadPHIs;
4915 PotentiallyDeadPHIs.insert(&PN);
4916 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4917 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4918 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004919
Chris Lattner91daeb52003-12-19 05:58:40 +00004920 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004921}
4922
Chris Lattner69193f92004-04-05 01:30:19 +00004923static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4924 Instruction *InsertPoint,
4925 InstCombiner *IC) {
4926 unsigned PS = IC->getTargetData().getPointerSize();
4927 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004928 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4929 // We must insert a cast to ensure we sign-extend.
4930 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4931 V->getName()), *InsertPoint);
4932 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4933 *InsertPoint);
4934}
4935
Chris Lattner48a44f72002-05-02 17:06:02 +00004936
Chris Lattner113f4f42002-06-25 16:13:24 +00004937Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004938 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004939 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004940 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004941 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004942 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004943
Chris Lattner81a7a232004-10-16 18:11:37 +00004944 if (isa<UndefValue>(GEP.getOperand(0)))
4945 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4946
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004947 bool HasZeroPointerIndex = false;
4948 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4949 HasZeroPointerIndex = C->isNullValue();
4950
4951 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004952 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004953
Chris Lattner69193f92004-04-05 01:30:19 +00004954 // Eliminate unneeded casts for indices.
4955 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004956 gep_type_iterator GTI = gep_type_begin(GEP);
4957 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4958 if (isa<SequentialType>(*GTI)) {
4959 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4960 Value *Src = CI->getOperand(0);
4961 const Type *SrcTy = Src->getType();
4962 const Type *DestTy = CI->getType();
4963 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004964 if (SrcTy->getPrimitiveSizeInBits() ==
4965 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004966 // We can always eliminate a cast from ulong or long to the other.
4967 // We can always eliminate a cast from uint to int or the other on
4968 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004969 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00004970 MadeChange = true;
4971 GEP.setOperand(i, Src);
4972 }
4973 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4974 SrcTy->getPrimitiveSize() == 4) {
4975 // We can always eliminate a cast from int to [u]long. We can
4976 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4977 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004978 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004979 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004980 MadeChange = true;
4981 GEP.setOperand(i, Src);
4982 }
Chris Lattner69193f92004-04-05 01:30:19 +00004983 }
4984 }
4985 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004986 // If we are using a wider index than needed for this platform, shrink it
4987 // to what we need. If the incoming value needs a cast instruction,
4988 // insert it. This explicit cast can make subsequent optimizations more
4989 // obvious.
4990 Value *Op = GEP.getOperand(i);
4991 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004992 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004993 GEP.setOperand(i, ConstantExpr::getCast(C,
4994 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004995 MadeChange = true;
4996 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004997 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4998 Op->getName()), GEP);
4999 GEP.setOperand(i, Op);
5000 MadeChange = true;
5001 }
Chris Lattner44d0b952004-07-20 01:48:15 +00005002
5003 // If this is a constant idx, make sure to canonicalize it to be a signed
5004 // operand, otherwise CSE and other optimizations are pessimized.
5005 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5006 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5007 CUI->getType()->getSignedVersion()));
5008 MadeChange = true;
5009 }
Chris Lattner69193f92004-04-05 01:30:19 +00005010 }
5011 if (MadeChange) return &GEP;
5012
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005013 // Combine Indices - If the source pointer to this getelementptr instruction
5014 // is a getelementptr instruction, combine the indices of the two
5015 // getelementptr instructions into a single instruction.
5016 //
Chris Lattner57c67b02004-03-25 22:59:29 +00005017 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00005018 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00005019 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00005020
5021 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00005022 // Note that if our source is a gep chain itself that we wait for that
5023 // chain to be resolved before we perform this transformation. This
5024 // avoids us creating a TON of code in some cases.
5025 //
5026 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5027 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5028 return 0; // Wait until our source is folded to completion.
5029
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005030 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00005031
5032 // Find out whether the last index in the source GEP is a sequential idx.
5033 bool EndsWithSequential = false;
5034 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5035 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00005036 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005037
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005038 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00005039 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00005040 // Replace: gep (gep %P, long B), long A, ...
5041 // With: T = long A+B; gep %P, T, ...
5042 //
Chris Lattner5f667a62004-05-07 22:09:22 +00005043 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00005044 if (SO1 == Constant::getNullValue(SO1->getType())) {
5045 Sum = GO1;
5046 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5047 Sum = SO1;
5048 } else {
5049 // If they aren't the same type, convert both to an integer of the
5050 // target's pointer size.
5051 if (SO1->getType() != GO1->getType()) {
5052 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5053 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5054 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5055 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5056 } else {
5057 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00005058 if (SO1->getType()->getPrimitiveSize() == PS) {
5059 // Convert GO1 to SO1's type.
5060 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5061
5062 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5063 // Convert SO1 to GO1's type.
5064 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5065 } else {
5066 const Type *PT = TD->getIntPtrType();
5067 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5068 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5069 }
5070 }
5071 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005072 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5073 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5074 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00005075 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5076 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00005077 }
Chris Lattner69193f92004-04-05 01:30:19 +00005078 }
Chris Lattner5f667a62004-05-07 22:09:22 +00005079
5080 // Recycle the GEP we already have if possible.
5081 if (SrcGEPOperands.size() == 2) {
5082 GEP.setOperand(0, SrcGEPOperands[0]);
5083 GEP.setOperand(1, Sum);
5084 return &GEP;
5085 } else {
5086 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5087 SrcGEPOperands.end()-1);
5088 Indices.push_back(Sum);
5089 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5090 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005091 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00005092 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005093 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005094 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00005095 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5096 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005097 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5098 }
5099
5100 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00005101 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005102
Chris Lattner5f667a62004-05-07 22:09:22 +00005103 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005104 // GEP of global variable. If all of the indices for this GEP are
5105 // constants, we can promote this to a constexpr instead of an instruction.
5106
5107 // Scan for nonconstants...
5108 std::vector<Constant*> Indices;
5109 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5110 for (; I != E && isa<Constant>(*I); ++I)
5111 Indices.push_back(cast<Constant>(*I));
5112
5113 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00005114 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00005115
5116 // Replace all uses of the GEP with the new constexpr...
5117 return ReplaceInstUsesWith(GEP, CE);
5118 }
Chris Lattner567b81f2005-09-13 00:40:14 +00005119 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5120 if (!isa<PointerType>(X->getType())) {
5121 // Not interesting. Source pointer must be a cast from pointer.
5122 } else if (HasZeroPointerIndex) {
5123 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5124 // into : GEP [10 x ubyte]* X, long 0, ...
5125 //
5126 // This occurs when the program declares an array extern like "int X[];"
5127 //
5128 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5129 const PointerType *XTy = cast<PointerType>(X->getType());
5130 if (const ArrayType *XATy =
5131 dyn_cast<ArrayType>(XTy->getElementType()))
5132 if (const ArrayType *CATy =
5133 dyn_cast<ArrayType>(CPTy->getElementType()))
5134 if (CATy->getElementType() == XATy->getElementType()) {
5135 // At this point, we know that the cast source type is a pointer
5136 // to an array of the same type as the destination pointer
5137 // array. Because the array type is never stepped over (there
5138 // is a leading zero) we can fold the cast into this GEP.
5139 GEP.setOperand(0, X);
5140 return &GEP;
5141 }
5142 } else if (GEP.getNumOperands() == 2) {
5143 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005144 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5145 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005146 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5147 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5148 if (isa<ArrayType>(SrcElTy) &&
5149 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5150 TD->getTypeSize(ResElTy)) {
5151 Value *V = InsertNewInstBefore(
5152 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5153 GEP.getOperand(1), GEP.getName()), GEP);
5154 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005155 }
Chris Lattner2a893292005-09-13 18:36:04 +00005156
5157 // Transform things like:
5158 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5159 // (where tmp = 8*tmp2) into:
5160 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5161
5162 if (isa<ArrayType>(SrcElTy) &&
5163 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5164 uint64_t ArrayEltSize =
5165 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5166
5167 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5168 // allow either a mul, shift, or constant here.
5169 Value *NewIdx = 0;
5170 ConstantInt *Scale = 0;
5171 if (ArrayEltSize == 1) {
5172 NewIdx = GEP.getOperand(1);
5173 Scale = ConstantInt::get(NewIdx->getType(), 1);
5174 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005175 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005176 Scale = CI;
5177 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5178 if (Inst->getOpcode() == Instruction::Shl &&
5179 isa<ConstantInt>(Inst->getOperand(1))) {
5180 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5181 if (Inst->getType()->isSigned())
5182 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5183 else
5184 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5185 NewIdx = Inst->getOperand(0);
5186 } else if (Inst->getOpcode() == Instruction::Mul &&
5187 isa<ConstantInt>(Inst->getOperand(1))) {
5188 Scale = cast<ConstantInt>(Inst->getOperand(1));
5189 NewIdx = Inst->getOperand(0);
5190 }
5191 }
5192
5193 // If the index will be to exactly the right offset with the scale taken
5194 // out, perform the transformation.
5195 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5196 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5197 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005198 (int64_t)C->getRawValue() /
5199 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005200 else
5201 Scale = ConstantUInt::get(Scale->getType(),
5202 Scale->getRawValue() / ArrayEltSize);
5203 if (Scale->getRawValue() != 1) {
5204 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5205 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5206 NewIdx = InsertNewInstBefore(Sc, GEP);
5207 }
5208
5209 // Insert the new GEP instruction.
5210 Instruction *Idx =
5211 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5212 NewIdx, GEP.getName());
5213 Idx = InsertNewInstBefore(Idx, GEP);
5214 return new CastInst(Idx, GEP.getType());
5215 }
5216 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005217 }
Chris Lattnerca081252001-12-14 16:52:21 +00005218 }
5219
Chris Lattnerca081252001-12-14 16:52:21 +00005220 return 0;
5221}
5222
Chris Lattner1085bdf2002-11-04 16:18:53 +00005223Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5224 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5225 if (AI.isArrayAllocation()) // Check C != 1
5226 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5227 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005228 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005229
5230 // Create and insert the replacement instruction...
5231 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00005232 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005233 else {
5234 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00005235 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005236 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005237
5238 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005239
Chris Lattner1085bdf2002-11-04 16:18:53 +00005240 // Scan to the end of the allocation instructions, to skip over a block of
5241 // allocas if possible...
5242 //
5243 BasicBlock::iterator It = New;
5244 while (isa<AllocationInst>(*It)) ++It;
5245
5246 // Now that I is pointing to the first non-allocation-inst in the block,
5247 // insert our getelementptr instruction...
5248 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005249 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5250 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5251 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005252
5253 // Now make everything use the getelementptr instead of the original
5254 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005255 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005256 } else if (isa<UndefValue>(AI.getArraySize())) {
5257 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005258 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005259
5260 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5261 // Note that we only do this for alloca's, because malloc should allocate and
5262 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005263 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005264 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005265 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5266
Chris Lattner1085bdf2002-11-04 16:18:53 +00005267 return 0;
5268}
5269
Chris Lattner8427bff2003-12-07 01:24:23 +00005270Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5271 Value *Op = FI.getOperand(0);
5272
5273 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5274 if (CastInst *CI = dyn_cast<CastInst>(Op))
5275 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5276 FI.setOperand(0, CI->getOperand(0));
5277 return &FI;
5278 }
5279
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005280 // free undef -> unreachable.
5281 if (isa<UndefValue>(Op)) {
5282 // Insert a new store to null because we cannot modify the CFG here.
5283 new StoreInst(ConstantBool::True,
5284 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5285 return EraseInstFromFunction(FI);
5286 }
5287
Chris Lattnerf3a36602004-02-28 04:57:37 +00005288 // If we have 'free null' delete the instruction. This can happen in stl code
5289 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005290 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005291 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005292
Chris Lattner8427bff2003-12-07 01:24:23 +00005293 return 0;
5294}
5295
5296
Chris Lattner72684fe2005-01-31 05:51:45 +00005297/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005298static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5299 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005300 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005301
5302 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005303 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005304 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005305
5306 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5307 // If the source is an array, the code below will not succeed. Check to
5308 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5309 // constants.
5310 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5311 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5312 if (ASrcTy->getNumElements() != 0) {
5313 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5314 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5315 SrcTy = cast<PointerType>(CastOp->getType());
5316 SrcPTy = SrcTy->getElementType();
5317 }
5318
5319 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005320 // Do not allow turning this into a load of an integer, which is then
5321 // casted to a pointer, this pessimizes pointer analysis a lot.
5322 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005323 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005324 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005325
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005326 // Okay, we are casting from one integer or pointer type to another of
5327 // the same size. Instead of casting the pointer before the load, cast
5328 // the result of the loaded value.
5329 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5330 CI->getName(),
5331 LI.isVolatile()),LI);
5332 // Now cast the result of the load.
5333 return new CastInst(NewLoad, LI.getType());
5334 }
Chris Lattner35e24772004-07-13 01:49:43 +00005335 }
5336 }
5337 return 0;
5338}
5339
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005340/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00005341/// from this value cannot trap. If it is not obviously safe to load from the
5342/// specified pointer, we do a quick local scan of the basic block containing
5343/// ScanFrom, to determine if the address is already accessed.
5344static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5345 // If it is an alloca or global variable, it is always safe to load from.
5346 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5347
5348 // Otherwise, be a little bit agressive by scanning the local block where we
5349 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005350 // from/to. If so, the previous load or store would have already trapped,
5351 // so there is no harm doing an extra load (also, CSE will later eliminate
5352 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00005353 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5354
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005355 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00005356 --BBI;
5357
5358 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5359 if (LI->getOperand(0) == V) return true;
5360 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5361 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005362
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005363 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005364 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005365}
5366
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005367Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5368 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005369
Chris Lattnera9d84e32005-05-01 04:24:53 +00005370 // load (cast X) --> cast (load X) iff safe
5371 if (CastInst *CI = dyn_cast<CastInst>(Op))
5372 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5373 return Res;
5374
5375 // None of the following transforms are legal for volatile loads.
5376 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005377
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005378 if (&LI.getParent()->front() != &LI) {
5379 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005380 // If the instruction immediately before this is a store to the same
5381 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005382 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5383 if (SI->getOperand(1) == LI.getOperand(0))
5384 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005385 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5386 if (LIB->getOperand(0) == LI.getOperand(0))
5387 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005388 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005389
5390 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5391 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5392 isa<UndefValue>(GEPI->getOperand(0))) {
5393 // Insert a new store to null instruction before the load to indicate
5394 // that this code is not reachable. We do this instead of inserting
5395 // an unreachable instruction directly because we cannot modify the
5396 // CFG.
5397 new StoreInst(UndefValue::get(LI.getType()),
5398 Constant::getNullValue(Op->getType()), &LI);
5399 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5400 }
5401
Chris Lattner81a7a232004-10-16 18:11:37 +00005402 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005403 // load null/undef -> undef
5404 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005405 // Insert a new store to null instruction before the load to indicate that
5406 // this code is not reachable. We do this instead of inserting an
5407 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005408 new StoreInst(UndefValue::get(LI.getType()),
5409 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005410 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005411 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005412
Chris Lattner81a7a232004-10-16 18:11:37 +00005413 // Instcombine load (constant global) into the value loaded.
5414 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5415 if (GV->isConstant() && !GV->isExternal())
5416 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005417
Chris Lattner81a7a232004-10-16 18:11:37 +00005418 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5419 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5420 if (CE->getOpcode() == Instruction::GetElementPtr) {
5421 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5422 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00005423 if (Constant *V =
5424 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00005425 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005426 if (CE->getOperand(0)->isNullValue()) {
5427 // Insert a new store to null instruction before the load to indicate
5428 // that this code is not reachable. We do this instead of inserting
5429 // an unreachable instruction directly because we cannot modify the
5430 // CFG.
5431 new StoreInst(UndefValue::get(LI.getType()),
5432 Constant::getNullValue(Op->getType()), &LI);
5433 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5434 }
5435
Chris Lattner81a7a232004-10-16 18:11:37 +00005436 } else if (CE->getOpcode() == Instruction::Cast) {
5437 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5438 return Res;
5439 }
5440 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005441
Chris Lattnera9d84e32005-05-01 04:24:53 +00005442 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005443 // Change select and PHI nodes to select values instead of addresses: this
5444 // helps alias analysis out a lot, allows many others simplifications, and
5445 // exposes redundancy in the code.
5446 //
5447 // Note that we cannot do the transformation unless we know that the
5448 // introduced loads cannot trap! Something like this is valid as long as
5449 // the condition is always false: load (select bool %C, int* null, int* %G),
5450 // but it would not be valid if we transformed it to load from null
5451 // unconditionally.
5452 //
5453 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5454 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005455 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5456 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005457 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005458 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005459 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005460 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005461 return new SelectInst(SI->getCondition(), V1, V2);
5462 }
5463
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005464 // load (select (cond, null, P)) -> load P
5465 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5466 if (C->isNullValue()) {
5467 LI.setOperand(0, SI->getOperand(2));
5468 return &LI;
5469 }
5470
5471 // load (select (cond, P, null)) -> load P
5472 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5473 if (C->isNullValue()) {
5474 LI.setOperand(0, SI->getOperand(1));
5475 return &LI;
5476 }
5477
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005478 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5479 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005480 bool Safe = PN->getParent() == LI.getParent();
5481
5482 // Scan all of the instructions between the PHI and the load to make
5483 // sure there are no instructions that might possibly alter the value
5484 // loaded from the PHI.
5485 if (Safe) {
5486 BasicBlock::iterator I = &LI;
5487 for (--I; !isa<PHINode>(I); --I)
5488 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5489 Safe = false;
5490 break;
5491 }
5492 }
5493
5494 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005495 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005496 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005497 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005498
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005499 if (Safe) {
5500 // Create the PHI.
5501 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5502 InsertNewInstBefore(NewPN, *PN);
5503 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5504
5505 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5506 BasicBlock *BB = PN->getIncomingBlock(i);
5507 Value *&TheLoad = LoadMap[BB];
5508 if (TheLoad == 0) {
5509 Value *InVal = PN->getIncomingValue(i);
5510 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5511 InVal->getName()+".val"),
5512 *BB->getTerminator());
5513 }
5514 NewPN->addIncoming(TheLoad, BB);
5515 }
5516 return ReplaceInstUsesWith(LI, NewPN);
5517 }
5518 }
5519 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005520 return 0;
5521}
5522
Chris Lattner72684fe2005-01-31 05:51:45 +00005523/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5524/// when possible.
5525static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5526 User *CI = cast<User>(SI.getOperand(1));
5527 Value *CastOp = CI->getOperand(0);
5528
5529 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5530 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5531 const Type *SrcPTy = SrcTy->getElementType();
5532
5533 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5534 // If the source is an array, the code below will not succeed. Check to
5535 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5536 // constants.
5537 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5538 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5539 if (ASrcTy->getNumElements() != 0) {
5540 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5541 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5542 SrcTy = cast<PointerType>(CastOp->getType());
5543 SrcPTy = SrcTy->getElementType();
5544 }
5545
5546 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005547 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005548 IC.getTargetData().getTypeSize(DestPTy)) {
5549
5550 // Okay, we are casting from one integer or pointer type to another of
5551 // the same size. Instead of casting the pointer before the store, cast
5552 // the value to be stored.
5553 Value *NewCast;
5554 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5555 NewCast = ConstantExpr::getCast(C, SrcPTy);
5556 else
5557 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5558 SrcPTy,
5559 SI.getOperand(0)->getName()+".c"), SI);
5560
5561 return new StoreInst(NewCast, CastOp);
5562 }
5563 }
5564 }
5565 return 0;
5566}
5567
Chris Lattner31f486c2005-01-31 05:36:43 +00005568Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5569 Value *Val = SI.getOperand(0);
5570 Value *Ptr = SI.getOperand(1);
5571
5572 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5573 removeFromWorkList(&SI);
5574 SI.eraseFromParent();
5575 ++NumCombined;
5576 return 0;
5577 }
5578
5579 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5580
5581 // store X, null -> turns into 'unreachable' in SimplifyCFG
5582 if (isa<ConstantPointerNull>(Ptr)) {
5583 if (!isa<UndefValue>(Val)) {
5584 SI.setOperand(0, UndefValue::get(Val->getType()));
5585 if (Instruction *U = dyn_cast<Instruction>(Val))
5586 WorkList.push_back(U); // Dropped a use.
5587 ++NumCombined;
5588 }
5589 return 0; // Do not modify these!
5590 }
5591
5592 // store undef, Ptr -> noop
5593 if (isa<UndefValue>(Val)) {
5594 removeFromWorkList(&SI);
5595 SI.eraseFromParent();
5596 ++NumCombined;
5597 return 0;
5598 }
5599
Chris Lattner72684fe2005-01-31 05:51:45 +00005600 // If the pointer destination is a cast, see if we can fold the cast into the
5601 // source instead.
5602 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5603 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5604 return Res;
5605 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5606 if (CE->getOpcode() == Instruction::Cast)
5607 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5608 return Res;
5609
Chris Lattner219175c2005-09-12 23:23:25 +00005610
5611 // If this store is the last instruction in the basic block, and if the block
5612 // ends with an unconditional branch, try to move it to the successor block.
5613 BasicBlock::iterator BBI = &SI; ++BBI;
5614 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5615 if (BI->isUnconditional()) {
5616 // Check to see if the successor block has exactly two incoming edges. If
5617 // so, see if the other predecessor contains a store to the same location.
5618 // if so, insert a PHI node (if needed) and move the stores down.
5619 BasicBlock *Dest = BI->getSuccessor(0);
5620
5621 pred_iterator PI = pred_begin(Dest);
5622 BasicBlock *Other = 0;
5623 if (*PI != BI->getParent())
5624 Other = *PI;
5625 ++PI;
5626 if (PI != pred_end(Dest)) {
5627 if (*PI != BI->getParent())
5628 if (Other)
5629 Other = 0;
5630 else
5631 Other = *PI;
5632 if (++PI != pred_end(Dest))
5633 Other = 0;
5634 }
5635 if (Other) { // If only one other pred...
5636 BBI = Other->getTerminator();
5637 // Make sure this other block ends in an unconditional branch and that
5638 // there is an instruction before the branch.
5639 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5640 BBI != Other->begin()) {
5641 --BBI;
5642 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5643
5644 // If this instruction is a store to the same location.
5645 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5646 // Okay, we know we can perform this transformation. Insert a PHI
5647 // node now if we need it.
5648 Value *MergedVal = OtherStore->getOperand(0);
5649 if (MergedVal != SI.getOperand(0)) {
5650 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5651 PN->reserveOperandSpace(2);
5652 PN->addIncoming(SI.getOperand(0), SI.getParent());
5653 PN->addIncoming(OtherStore->getOperand(0), Other);
5654 MergedVal = InsertNewInstBefore(PN, Dest->front());
5655 }
5656
5657 // Advance to a place where it is safe to insert the new store and
5658 // insert it.
5659 BBI = Dest->begin();
5660 while (isa<PHINode>(BBI)) ++BBI;
5661 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5662 OtherStore->isVolatile()), *BBI);
5663
5664 // Nuke the old stores.
5665 removeFromWorkList(&SI);
5666 removeFromWorkList(OtherStore);
5667 SI.eraseFromParent();
5668 OtherStore->eraseFromParent();
5669 ++NumCombined;
5670 return 0;
5671 }
5672 }
5673 }
5674 }
5675
Chris Lattner31f486c2005-01-31 05:36:43 +00005676 return 0;
5677}
5678
5679
Chris Lattner9eef8a72003-06-04 04:46:00 +00005680Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5681 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005682 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005683 BasicBlock *TrueDest;
5684 BasicBlock *FalseDest;
5685 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5686 !isa<Constant>(X)) {
5687 // Swap Destinations and condition...
5688 BI.setCondition(X);
5689 BI.setSuccessor(0, FalseDest);
5690 BI.setSuccessor(1, TrueDest);
5691 return &BI;
5692 }
5693
5694 // Cannonicalize setne -> seteq
5695 Instruction::BinaryOps Op; Value *Y;
5696 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5697 TrueDest, FalseDest)))
5698 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5699 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5700 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5701 std::string Name = I->getName(); I->setName("");
5702 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5703 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005704 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005705 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005706 BI.setSuccessor(0, FalseDest);
5707 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005708 removeFromWorkList(I);
5709 I->getParent()->getInstList().erase(I);
5710 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005711 return &BI;
5712 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005713
Chris Lattner9eef8a72003-06-04 04:46:00 +00005714 return 0;
5715}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005716
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005717Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5718 Value *Cond = SI.getCondition();
5719 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5720 if (I->getOpcode() == Instruction::Add)
5721 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5722 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5723 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005724 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005725 AddRHS));
5726 SI.setOperand(0, I->getOperand(0));
5727 WorkList.push_back(I);
5728 return &SI;
5729 }
5730 }
5731 return 0;
5732}
5733
Chris Lattner99f48c62002-09-02 04:59:56 +00005734void InstCombiner::removeFromWorkList(Instruction *I) {
5735 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5736 WorkList.end());
5737}
5738
Chris Lattner39c98bb2004-12-08 23:43:58 +00005739
5740/// TryToSinkInstruction - Try to move the specified instruction from its
5741/// current block into the beginning of DestBlock, which can only happen if it's
5742/// safe to move the instruction past all of the instructions between it and the
5743/// end of its block.
5744static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5745 assert(I->hasOneUse() && "Invariants didn't hold!");
5746
Chris Lattnerc4f67e62005-10-27 17:13:11 +00005747 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5748 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005749
Chris Lattner39c98bb2004-12-08 23:43:58 +00005750 // Do not sink alloca instructions out of the entry block.
5751 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5752 return false;
5753
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005754 // We can only sink load instructions if there is nothing between the load and
5755 // the end of block that could change the value.
5756 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005757 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5758 Scan != E; ++Scan)
5759 if (Scan->mayWriteToMemory())
5760 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005761 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005762
5763 BasicBlock::iterator InsertPos = DestBlock->begin();
5764 while (isa<PHINode>(InsertPos)) ++InsertPos;
5765
Chris Lattner9f269e42005-08-08 19:11:57 +00005766 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005767 ++NumSunkInst;
5768 return true;
5769}
5770
Chris Lattner113f4f42002-06-25 16:13:24 +00005771bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005772 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005773 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005774
Chris Lattner4ed40f72005-07-07 20:40:38 +00005775 {
5776 // Populate the worklist with the reachable instructions.
5777 std::set<BasicBlock*> Visited;
5778 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5779 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5780 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5781 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005782
Chris Lattner4ed40f72005-07-07 20:40:38 +00005783 // Do a quick scan over the function. If we find any blocks that are
5784 // unreachable, remove any instructions inside of them. This prevents
5785 // the instcombine code from having to deal with some bad special cases.
5786 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5787 if (!Visited.count(BB)) {
5788 Instruction *Term = BB->getTerminator();
5789 while (Term != BB->begin()) { // Remove instrs bottom-up
5790 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005791
Chris Lattner4ed40f72005-07-07 20:40:38 +00005792 DEBUG(std::cerr << "IC: DCE: " << *I);
5793 ++NumDeadInst;
5794
5795 if (!I->use_empty())
5796 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5797 I->eraseFromParent();
5798 }
5799 }
5800 }
Chris Lattnerca081252001-12-14 16:52:21 +00005801
5802 while (!WorkList.empty()) {
5803 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5804 WorkList.pop_back();
5805
Misha Brukman632df282002-10-29 23:06:16 +00005806 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005807 // Check to see if we can DIE the instruction...
5808 if (isInstructionTriviallyDead(I)) {
5809 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005810 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005811 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005812 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005813
Chris Lattnercd517ff2005-01-28 19:32:01 +00005814 DEBUG(std::cerr << "IC: DCE: " << *I);
5815
5816 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005817 removeFromWorkList(I);
5818 continue;
5819 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005820
Misha Brukman632df282002-10-29 23:06:16 +00005821 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005822 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005823 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005824 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005825 cast<Constant>(Ptr)->isNullValue() &&
5826 !isa<ConstantPointerNull>(C) &&
5827 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005828 // If this is a constant expr gep that is effectively computing an
5829 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5830 bool isFoldableGEP = true;
5831 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5832 if (!isa<ConstantInt>(I->getOperand(i)))
5833 isFoldableGEP = false;
5834 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005835 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005836 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5837 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005838 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005839 C = ConstantExpr::getCast(C, I->getType());
5840 }
5841 }
5842
Chris Lattnercd517ff2005-01-28 19:32:01 +00005843 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5844
Chris Lattner99f48c62002-09-02 04:59:56 +00005845 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005846 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005847 ReplaceInstUsesWith(*I, C);
5848
Chris Lattner99f48c62002-09-02 04:59:56 +00005849 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005850 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005851 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005852 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005853 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005854
Chris Lattner39c98bb2004-12-08 23:43:58 +00005855 // See if we can trivially sink this instruction to a successor basic block.
5856 if (I->hasOneUse()) {
5857 BasicBlock *BB = I->getParent();
5858 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5859 if (UserParent != BB) {
5860 bool UserIsSuccessor = false;
5861 // See if the user is one of our successors.
5862 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5863 if (*SI == UserParent) {
5864 UserIsSuccessor = true;
5865 break;
5866 }
5867
5868 // If the user is one of our immediate successors, and if that successor
5869 // only has us as a predecessors (we'd have to split the critical edge
5870 // otherwise), we can keep going.
5871 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5872 next(pred_begin(UserParent)) == pred_end(UserParent))
5873 // Okay, the CFG is simple enough, try to sink this instruction.
5874 Changed |= TryToSinkInstruction(I, UserParent);
5875 }
5876 }
5877
Chris Lattnerca081252001-12-14 16:52:21 +00005878 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005879 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005880 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005881 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005882 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005883 DEBUG(std::cerr << "IC: Old = " << *I
5884 << " New = " << *Result);
5885
Chris Lattner396dbfe2004-06-09 05:08:07 +00005886 // Everything uses the new instruction now.
5887 I->replaceAllUsesWith(Result);
5888
5889 // Push the new instruction and any users onto the worklist.
5890 WorkList.push_back(Result);
5891 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005892
5893 // Move the name to the new instruction first...
5894 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005895 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005896
5897 // Insert the new instruction into the basic block...
5898 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005899 BasicBlock::iterator InsertPos = I;
5900
5901 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5902 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5903 ++InsertPos;
5904
5905 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005906
Chris Lattner63d75af2004-05-01 23:27:23 +00005907 // Make sure that we reprocess all operands now that we reduced their
5908 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005909 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5910 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5911 WorkList.push_back(OpI);
5912
Chris Lattner396dbfe2004-06-09 05:08:07 +00005913 // Instructions can end up on the worklist more than once. Make sure
5914 // we do not process an instruction that has been deleted.
5915 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005916
5917 // Erase the old instruction.
5918 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005919 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005920 DEBUG(std::cerr << "IC: MOD = " << *I);
5921
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005922 // If the instruction was modified, it's possible that it is now dead.
5923 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005924 if (isInstructionTriviallyDead(I)) {
5925 // Make sure we process all operands now that we are reducing their
5926 // use counts.
5927 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5928 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5929 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005930
Chris Lattner63d75af2004-05-01 23:27:23 +00005931 // Instructions may end up in the worklist more than once. Erase all
5932 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005933 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005934 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005935 } else {
5936 WorkList.push_back(Result);
5937 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005938 }
Chris Lattner053c0932002-05-14 15:24:07 +00005939 }
Chris Lattner260ab202002-04-18 17:39:14 +00005940 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005941 }
5942 }
5943
Chris Lattner260ab202002-04-18 17:39:14 +00005944 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005945}
5946
Brian Gaeke38b79e82004-07-27 17:43:21 +00005947FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005948 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005949}
Brian Gaeke960707c2003-11-11 22:41:34 +00005950