blob: cf4af7916916f2694417d862cf1da337a8a3af84 [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 Lattner260ab202002-04-18 17:39:14 +0000230 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000231
Chris Lattnerc8b70922002-07-26 21:12:46 +0000232 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000233}
234
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000235// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000236// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000237static unsigned getComplexity(Value *V) {
238 if (isa<Instruction>(V)) {
239 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000240 return 3;
241 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000242 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000243 if (isa<Argument>(V)) return 3;
244 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000245}
Chris Lattner260ab202002-04-18 17:39:14 +0000246
Chris Lattner7fb29e12003-03-11 00:12:48 +0000247// isOnlyUse - Return true if this instruction will be deleted if we stop using
248// it.
249static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000250 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000251}
252
Chris Lattnere79e8542004-02-23 06:38:22 +0000253// getPromotedType - Return the specified type promoted as it would be to pass
254// though a va_arg area...
255static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000256 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000257 case Type::SByteTyID:
258 case Type::ShortTyID: return Type::IntTy;
259 case Type::UByteTyID:
260 case Type::UShortTyID: return Type::UIntTy;
261 case Type::FloatTyID: return Type::DoubleTy;
262 default: return Ty;
263 }
264}
265
Chris Lattner567b81f2005-09-13 00:40:14 +0000266/// isCast - If the specified operand is a CastInst or a constant expr cast,
267/// return the operand value, otherwise return null.
268static Value *isCast(Value *V) {
269 if (CastInst *I = dyn_cast<CastInst>(V))
270 return I->getOperand(0);
271 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
272 if (CE->getOpcode() == Instruction::Cast)
273 return CE->getOperand(0);
274 return 0;
275}
276
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000277// SimplifyCommutative - This performs a few simplifications for commutative
278// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000279//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000280// 1. Order operands such that they are listed from right (least complex) to
281// left (most complex). This puts constants before unary operators before
282// binary operators.
283//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000284// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
285// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000286//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000287bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000288 bool Changed = false;
289 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
290 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000291
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000292 if (!I.isAssociative()) return Changed;
293 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000294 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
295 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
296 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000297 Constant *Folded = ConstantExpr::get(I.getOpcode(),
298 cast<Constant>(I.getOperand(1)),
299 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000300 I.setOperand(0, Op->getOperand(0));
301 I.setOperand(1, Folded);
302 return true;
303 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
304 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
305 isOnlyUse(Op) && isOnlyUse(Op1)) {
306 Constant *C1 = cast<Constant>(Op->getOperand(1));
307 Constant *C2 = cast<Constant>(Op1->getOperand(1));
308
309 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000310 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000311 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
312 Op1->getOperand(0),
313 Op1->getName(), &I);
314 WorkList.push_back(New);
315 I.setOperand(0, New);
316 I.setOperand(1, Folded);
317 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000318 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000319 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000320 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000321}
Chris Lattnerca081252001-12-14 16:52:21 +0000322
Chris Lattnerbb74e222003-03-10 23:06:50 +0000323// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
324// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000325//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000326static inline Value *dyn_castNegVal(Value *V) {
327 if (BinaryOperator::isNeg(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000328 return BinaryOperator::getNegArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000329
Chris Lattner9ad0d552004-12-14 20:08:06 +0000330 // Constants can be considered to be negated values if they can be folded.
331 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
332 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000333 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000334}
335
Chris Lattnerbb74e222003-03-10 23:06:50 +0000336static inline Value *dyn_castNotVal(Value *V) {
337 if (BinaryOperator::isNot(V))
Chris Lattnerd6f636a2005-04-24 07:30:14 +0000338 return BinaryOperator::getNotArgument(V);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000339
340 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000341 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000342 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000343 return 0;
344}
345
Chris Lattner7fb29e12003-03-11 00:12:48 +0000346// dyn_castFoldableMul - If this value is a multiply that can be folded into
347// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000348// non-constant operand of the multiply, and set CST to point to the multiplier.
349// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000350//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000351static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000352 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000353 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000354 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000355 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000356 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000357 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000358 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000359 // The multiplier is really 1 << CST.
360 Constant *One = ConstantInt::get(V->getType(), 1);
361 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
362 return I->getOperand(0);
363 }
364 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000365 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000366}
Chris Lattner31ae8632002-08-14 17:51:49 +0000367
Chris Lattner0798af32005-01-13 20:14:25 +0000368/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
369/// expression, return it.
370static User *dyn_castGetElementPtr(Value *V) {
371 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
372 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
373 if (CE->getOpcode() == Instruction::GetElementPtr)
374 return cast<User>(V);
375 return false;
376}
377
Chris Lattner623826c2004-09-28 21:48:02 +0000378// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000379static ConstantInt *AddOne(ConstantInt *C) {
380 return cast<ConstantInt>(ConstantExpr::getAdd(C,
381 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000382}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000383static ConstantInt *SubOne(ConstantInt *C) {
384 return cast<ConstantInt>(ConstantExpr::getSub(C,
385 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000386}
387
Chris Lattner0b3557f2005-09-24 23:43:33 +0000388/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
389/// this predicate to simplify operations downstream. V and Mask are known to
390/// be the same type.
391static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
392 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
393 // we cannot optimize based on the assumption that it is zero without changing
394 // to to an explicit zero. If we don't change it to zero, other code could
395 // optimized based on the contradictory assumption that it is non-zero.
396 // Because instcombine aggressively folds operations with undef args anyway,
397 // this won't lose us code quality.
398 if (Mask->isNullValue())
399 return true;
400 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
401 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
402
403 if (Instruction *I = dyn_cast<Instruction>(V)) {
404 switch (I->getOpcode()) {
Chris Lattner62010c42005-10-09 06:36:35 +0000405 case Instruction::And:
406 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
Chris Lattner03b9eb52005-10-09 22:08:50 +0000407 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
408 ConstantIntegral *C1C2 =
409 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
410 if (MaskedValueIsZero(I->getOperand(0), C1C2))
Chris Lattner62010c42005-10-09 06:36:35 +0000411 return true;
Chris Lattner03b9eb52005-10-09 22:08:50 +0000412 }
413 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
414 return MaskedValueIsZero(I->getOperand(1), Mask) ||
415 MaskedValueIsZero(I->getOperand(0), Mask);
Chris Lattner62010c42005-10-09 06:36:35 +0000416 case Instruction::Or:
Chris Lattner03b9eb52005-10-09 22:08:50 +0000417 case Instruction::Xor:
Chris Lattner62010c42005-10-09 06:36:35 +0000418 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
419 return MaskedValueIsZero(I->getOperand(1), Mask) &&
420 MaskedValueIsZero(I->getOperand(0), Mask);
421 case Instruction::Select:
422 // If the T and F values are MaskedValueIsZero, the result is also zero.
423 return MaskedValueIsZero(I->getOperand(2), Mask) &&
424 MaskedValueIsZero(I->getOperand(1), Mask);
425 case Instruction::Cast: {
426 const Type *SrcTy = I->getOperand(0)->getType();
427 if (SrcTy == Type::BoolTy)
428 return (Mask->getRawValue() & 1) == 0;
429
430 if (SrcTy->isInteger()) {
431 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
432 if (SrcTy->isUnsigned() && // Only handle zero ext.
433 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
434 return true;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000435
Chris Lattner62010c42005-10-09 06:36:35 +0000436 // If this is a noop cast, recurse.
437 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
438 SrcTy->getSignedVersion() == I->getType()) {
439 Constant *NewMask =
440 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
Chris Lattner0b3557f2005-09-24 23:43:33 +0000441 return MaskedValueIsZero(I->getOperand(0),
Chris Lattner62010c42005-10-09 06:36:35 +0000442 cast<ConstantIntegral>(NewMask));
443 }
444 }
445 break;
446 }
447 case Instruction::Shl:
448 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
449 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
450 return MaskedValueIsZero(I->getOperand(0),
451 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)));
452 break;
453 case Instruction::Shr:
454 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
455 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
456 if (I->getType()->isUnsigned()) {
457 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
458 C1 = ConstantExpr::getShr(C1, SA);
459 C1 = ConstantExpr::getAnd(C1, Mask);
460 if (C1->isNullValue())
461 return true;
462 }
463 break;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000464 }
465 }
466
467 return false;
468}
469
Chris Lattner623826c2004-09-28 21:48:02 +0000470// isTrueWhenEqual - Return true if the specified setcondinst instruction is
471// true when both operands are equal...
472//
473static bool isTrueWhenEqual(Instruction &I) {
474 return I.getOpcode() == Instruction::SetEQ ||
475 I.getOpcode() == Instruction::SetGE ||
476 I.getOpcode() == Instruction::SetLE;
477}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000478
479/// AssociativeOpt - Perform an optimization on an associative operator. This
480/// function is designed to check a chain of associative operators for a
481/// potential to apply a certain optimization. Since the optimization may be
482/// applicable if the expression was reassociated, this checks the chain, then
483/// reassociates the expression as necessary to expose the optimization
484/// opportunity. This makes use of a special Functor, which must define
485/// 'shouldApply' and 'apply' methods.
486///
487template<typename Functor>
488Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
489 unsigned Opcode = Root.getOpcode();
490 Value *LHS = Root.getOperand(0);
491
492 // Quick check, see if the immediate LHS matches...
493 if (F.shouldApply(LHS))
494 return F.apply(Root);
495
496 // Otherwise, if the LHS is not of the same opcode as the root, return.
497 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000498 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000499 // Should we apply this transform to the RHS?
500 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
501
502 // If not to the RHS, check to see if we should apply to the LHS...
503 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
504 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
505 ShouldApply = true;
506 }
507
508 // If the functor wants to apply the optimization to the RHS of LHSI,
509 // reassociate the expression from ((? op A) op B) to (? op (A op B))
510 if (ShouldApply) {
511 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000512
Chris Lattnerb8b97502003-08-13 19:01:45 +0000513 // Now all of the instructions are in the current basic block, go ahead
514 // and perform the reassociation.
515 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
516
517 // First move the selected RHS to the LHS of the root...
518 Root.setOperand(0, LHSI->getOperand(1));
519
520 // Make what used to be the LHS of the root be the user of the root...
521 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000522 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000523 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
524 return 0;
525 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000526 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000527 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000528 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
529 BasicBlock::iterator ARI = &Root; ++ARI;
530 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
531 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000532
533 // Now propagate the ExtraOperand down the chain of instructions until we
534 // get to LHSI.
535 while (TmpLHSI != LHSI) {
536 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000537 // Move the instruction to immediately before the chain we are
538 // constructing to avoid breaking dominance properties.
539 NextLHSI->getParent()->getInstList().remove(NextLHSI);
540 BB->getInstList().insert(ARI, NextLHSI);
541 ARI = NextLHSI;
542
Chris Lattnerb8b97502003-08-13 19:01:45 +0000543 Value *NextOp = NextLHSI->getOperand(1);
544 NextLHSI->setOperand(1, ExtraOperand);
545 TmpLHSI = NextLHSI;
546 ExtraOperand = NextOp;
547 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000548
Chris Lattnerb8b97502003-08-13 19:01:45 +0000549 // Now that the instructions are reassociated, have the functor perform
550 // the transformation...
551 return F.apply(Root);
552 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000553
Chris Lattnerb8b97502003-08-13 19:01:45 +0000554 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
555 }
556 return 0;
557}
558
559
560// AddRHS - Implements: X + X --> X << 1
561struct AddRHS {
562 Value *RHS;
563 AddRHS(Value *rhs) : RHS(rhs) {}
564 bool shouldApply(Value *LHS) const { return LHS == RHS; }
565 Instruction *apply(BinaryOperator &Add) const {
566 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
567 ConstantInt::get(Type::UByteTy, 1));
568 }
569};
570
571// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
572// iff C1&C2 == 0
573struct AddMaskingAnd {
574 Constant *C2;
575 AddMaskingAnd(Constant *c) : C2(c) {}
576 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000577 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000578 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000579 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000580 }
581 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000582 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000583 }
584};
585
Chris Lattner86102b82005-01-01 16:22:27 +0000586static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000587 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000588 if (isa<CastInst>(I)) {
589 if (Constant *SOC = dyn_cast<Constant>(SO))
590 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000591
Chris Lattner86102b82005-01-01 16:22:27 +0000592 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
593 SO->getName() + ".cast"), I);
594 }
595
Chris Lattner183b3362004-04-09 19:05:30 +0000596 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000597 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
598 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000599
Chris Lattner183b3362004-04-09 19:05:30 +0000600 if (Constant *SOC = dyn_cast<Constant>(SO)) {
601 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000602 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
603 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000604 }
605
606 Value *Op0 = SO, *Op1 = ConstOperand;
607 if (!ConstIsRHS)
608 std::swap(Op0, Op1);
609 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000610 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
611 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
612 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
613 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000614 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000615 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000616 abort();
617 }
Chris Lattner86102b82005-01-01 16:22:27 +0000618 return IC->InsertNewInstBefore(New, I);
619}
620
621// FoldOpIntoSelect - Given an instruction with a select as one operand and a
622// constant as the other operand, try to fold the binary operator into the
623// select arguments. This also works for Cast instructions, which obviously do
624// not have a second operand.
625static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
626 InstCombiner *IC) {
627 // Don't modify shared select instructions
628 if (!SI->hasOneUse()) return 0;
629 Value *TV = SI->getOperand(1);
630 Value *FV = SI->getOperand(2);
631
632 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000633 // Bool selects with constant operands can be folded to logical ops.
634 if (SI->getType() == Type::BoolTy) return 0;
635
Chris Lattner86102b82005-01-01 16:22:27 +0000636 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
637 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
638
639 return new SelectInst(SI->getCondition(), SelectTrueVal,
640 SelectFalseVal);
641 }
642 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000643}
644
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000645
646/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
647/// node as operand #0, see if we can fold the instruction into the PHI (which
648/// is only possible if all operands to the PHI are constants).
649Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
650 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000651 unsigned NumPHIValues = PN->getNumIncomingValues();
652 if (!PN->hasOneUse() || NumPHIValues == 0 ||
653 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000654
655 // Check to see if all of the operands of the PHI are constants. If not, we
656 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000657 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000658 if (!isa<Constant>(PN->getIncomingValue(i)))
659 return 0;
660
661 // Okay, we can do the transformation: create the new PHI node.
662 PHINode *NewPN = new PHINode(I.getType(), I.getName());
663 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000664 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000665 InsertNewInstBefore(NewPN, *PN);
666
667 // Next, add all of the operands to the PHI.
668 if (I.getNumOperands() == 2) {
669 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000670 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000671 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
672 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
673 PN->getIncomingBlock(i));
674 }
675 } else {
676 assert(isa<CastInst>(I) && "Unary op should be a cast!");
677 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000678 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000679 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
680 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
681 PN->getIncomingBlock(i));
682 }
683 }
684 return ReplaceInstUsesWith(I, NewPN);
685}
686
Chris Lattner113f4f42002-06-25 16:13:24 +0000687Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000688 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000689 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000690
Chris Lattnercf4a9962004-04-10 22:01:55 +0000691 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000692 // X + undef -> undef
693 if (isa<UndefValue>(RHS))
694 return ReplaceInstUsesWith(I, RHS);
695
Chris Lattnercf4a9962004-04-10 22:01:55 +0000696 // X + 0 --> X
697 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
698 RHSC->isNullValue())
699 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000700
Chris Lattnercf4a9962004-04-10 22:01:55 +0000701 // X + (signbit) --> X ^ signbit
702 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000703 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnercf4a9962004-04-10 22:01:55 +0000704 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000705 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000706 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000707 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000708
709 if (isa<PHINode>(LHS))
710 if (Instruction *NV = FoldOpIntoPhi(I))
711 return NV;
Chris Lattner0b3557f2005-09-24 23:43:33 +0000712
713 ConstantInt *XorRHS;
714 Value *XorLHS;
715 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
716 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
717 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
718 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
719
720 uint64_t C0080Val = 1ULL << 31;
721 int64_t CFF80Val = -C0080Val;
722 unsigned Size = 32;
723 do {
724 if (TySizeBits > Size) {
725 bool Found = false;
726 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
727 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
728 if (RHSSExt == CFF80Val) {
729 if (XorRHS->getZExtValue() == C0080Val)
730 Found = true;
731 } else if (RHSZExt == C0080Val) {
732 if (XorRHS->getSExtValue() == CFF80Val)
733 Found = true;
734 }
735 if (Found) {
736 // This is a sign extend if the top bits are known zero.
737 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
738 Mask = ConstantExpr::getShl(Mask,
739 ConstantInt::get(Type::UByteTy, 64-TySizeBits-Size));
740 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
741 Size = 0; // Not a sign ext, but can't be any others either.
742 goto FoundSExt;
743 }
744 }
745 Size >>= 1;
746 C0080Val >>= Size;
747 CFF80Val >>= Size;
748 } while (Size >= 8);
749
750FoundSExt:
751 const Type *MiddleType = 0;
752 switch (Size) {
753 default: break;
754 case 32: MiddleType = Type::IntTy; break;
755 case 16: MiddleType = Type::ShortTy; break;
756 case 8: MiddleType = Type::SByteTy; break;
757 }
758 if (MiddleType) {
759 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
760 InsertNewInstBefore(NewTrunc, I);
761 return new CastInst(NewTrunc, I.getType());
762 }
763 }
Chris Lattnercf4a9962004-04-10 22:01:55 +0000764 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000765
Chris Lattnerb8b97502003-08-13 19:01:45 +0000766 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000767 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000768 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000769
770 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
771 if (RHSI->getOpcode() == Instruction::Sub)
772 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
773 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
774 }
775 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
776 if (LHSI->getOpcode() == Instruction::Sub)
777 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
778 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
779 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000780 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000781
Chris Lattner147e9752002-05-08 22:46:53 +0000782 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000783 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000784 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000785
786 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000787 if (!isa<Constant>(RHS))
788 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000789 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000790
Misha Brukmanb1c93172005-04-21 23:48:37 +0000791
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000792 ConstantInt *C2;
793 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
794 if (X == RHS) // X*C + X --> X * (C+1)
795 return BinaryOperator::createMul(RHS, AddOne(C2));
796
797 // X*C1 + X*C2 --> X * (C1+C2)
798 ConstantInt *C1;
799 if (X == dyn_castFoldableMul(RHS, C1))
800 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000801 }
802
803 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000804 if (dyn_castFoldableMul(RHS, C2) == LHS)
805 return BinaryOperator::createMul(LHS, AddOne(C2));
806
Chris Lattner57c8d992003-02-18 19:57:07 +0000807
Chris Lattnerb8b97502003-08-13 19:01:45 +0000808 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000809 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000810 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000811
Chris Lattnerb9cde762003-10-02 15:11:26 +0000812 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000813 Value *X;
814 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
815 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
816 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000817 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000818
Chris Lattnerbff91d92004-10-08 05:07:56 +0000819 // (X & FF00) + xx00 -> (X+xx00) & FF00
820 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
821 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
822 if (Anded == CRHS) {
823 // See if all bits from the first bit set in the Add RHS up are included
824 // in the mask. First, get the rightmost bit.
825 uint64_t AddRHSV = CRHS->getRawValue();
826
827 // Form a mask of all bits from the lowest bit added through the top.
828 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner2f1457f2005-04-24 17:46:05 +0000829 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerbff91d92004-10-08 05:07:56 +0000830
831 // See if the and mask includes all of these bits.
832 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000833
Chris Lattnerbff91d92004-10-08 05:07:56 +0000834 if (AddRHSHighBits == AddRHSHighBitsAnd) {
835 // Okay, the xform is safe. Insert the new add pronto.
836 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
837 LHS->getName()), I);
838 return BinaryOperator::createAnd(NewAdd, C2);
839 }
840 }
841 }
842
Chris Lattnerd4252a72004-07-30 07:50:03 +0000843 // Try to fold constant add into select arguments.
844 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000845 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000846 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000847 }
848
Chris Lattner113f4f42002-06-25 16:13:24 +0000849 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000850}
851
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000852// isSignBit - Return true if the value represented by the constant only has the
853// highest order bit set.
854static bool isSignBit(ConstantInt *CI) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000855 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner2f1457f2005-04-24 17:46:05 +0000856 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000857}
858
Chris Lattner022167f2004-03-13 00:11:49 +0000859/// RemoveNoopCast - Strip off nonconverting casts from the value.
860///
861static Value *RemoveNoopCast(Value *V) {
862 if (CastInst *CI = dyn_cast<CastInst>(V)) {
863 const Type *CTy = CI->getType();
864 const Type *OpTy = CI->getOperand(0)->getType();
865 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000866 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattner022167f2004-03-13 00:11:49 +0000867 return RemoveNoopCast(CI->getOperand(0));
868 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
869 return RemoveNoopCast(CI->getOperand(0));
870 }
871 return V;
872}
873
Chris Lattner113f4f42002-06-25 16:13:24 +0000874Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000875 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000876
Chris Lattnere6794492002-08-12 21:17:25 +0000877 if (Op0 == Op1) // sub X, X -> 0
878 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000879
Chris Lattnere6794492002-08-12 21:17:25 +0000880 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000881 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000882 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000883
Chris Lattner81a7a232004-10-16 18:11:37 +0000884 if (isa<UndefValue>(Op0))
885 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
886 if (isa<UndefValue>(Op1))
887 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
888
Chris Lattner8f2f5982003-11-05 01:06:05 +0000889 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
890 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000891 if (C->isAllOnesValue())
892 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000893
Chris Lattner8f2f5982003-11-05 01:06:05 +0000894 // C - ~X == X + (1+C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000895 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +0000896 if (match(Op1, m_Not(m_Value(X))))
897 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000898 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000899 // -((uint)X >> 31) -> ((int)X >> 31)
900 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000901 if (C->isNullValue()) {
902 Value *NoopCastedRHS = RemoveNoopCast(Op1);
903 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000904 if (SI->getOpcode() == Instruction::Shr)
905 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
906 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000907 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000908 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000909 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000910 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000911 // Check to see if we are shifting out everything but the sign bit.
Chris Lattnerd1f46d32005-04-24 06:59:08 +0000912 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000913 // Ok, the transformation is safe. Insert a cast of the incoming
914 // value, then the new shift, then the new cast.
915 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
916 SI->getOperand(0)->getName());
917 Value *InV = InsertNewInstBefore(FirstCast, I);
918 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
919 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000920 if (NewShift->getType() == I.getType())
921 return NewShift;
922 else {
923 InV = InsertNewInstBefore(NewShift, I);
924 return new CastInst(NewShift, I.getType());
925 }
Chris Lattner92295c52004-03-12 23:53:13 +0000926 }
927 }
Chris Lattner022167f2004-03-13 00:11:49 +0000928 }
Chris Lattner183b3362004-04-09 19:05:30 +0000929
930 // Try to fold constant sub into select arguments.
931 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000932 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000933 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000934
935 if (isa<PHINode>(Op0))
936 if (Instruction *NV = FoldOpIntoPhi(I))
937 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000938 }
939
Chris Lattnera9be4492005-04-07 16:15:25 +0000940 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
941 if (Op1I->getOpcode() == Instruction::Add &&
942 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000943 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000944 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000945 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000946 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000947 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
948 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
949 // C1-(X+C2) --> (C1-C2)-X
950 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
951 Op1I->getOperand(0));
952 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000953 }
954
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000955 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000956 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
957 // is not used by anyone else...
958 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000959 if (Op1I->getOpcode() == Instruction::Sub &&
960 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000961 // Swap the two operands of the subexpr...
962 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
963 Op1I->setOperand(0, IIOp1);
964 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000965
Chris Lattner3082c5a2003-02-18 19:28:33 +0000966 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000967 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000968 }
969
970 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
971 //
972 if (Op1I->getOpcode() == Instruction::And &&
973 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
974 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
975
Chris Lattner396dbfe2004-06-09 05:08:07 +0000976 Value *NewNot =
977 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000978 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000979 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000980
Chris Lattner0aee4b72004-10-06 15:08:25 +0000981 // -(X sdiv C) -> (X sdiv -C)
982 if (Op1I->getOpcode() == Instruction::Div)
983 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000984 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000985 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000986 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000987 ConstantExpr::getNeg(DivRHS));
988
Chris Lattner57c8d992003-02-18 19:57:07 +0000989 // X - X*C --> X * (1-C)
Reid Spencer4fdd96c2005-06-18 17:37:34 +0000990 ConstantInt *C2 = 0;
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000991 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000992 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000993 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000994 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000995 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000996 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000997 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000998
Chris Lattner47060462005-04-07 17:14:51 +0000999 if (!Op0->getType()->isFloatingPoint())
1000 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1001 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +00001002 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1003 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1004 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1005 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +00001006 } else if (Op0I->getOpcode() == Instruction::Sub) {
1007 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1008 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +00001009 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001010
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001011 ConstantInt *C1;
1012 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1013 if (X == Op1) { // X*C - X --> X * (C-1)
1014 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1015 return BinaryOperator::createMul(Op1, CP1);
1016 }
Chris Lattner57c8d992003-02-18 19:57:07 +00001017
Chris Lattner8c3e7b92004-11-13 19:50:12 +00001018 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1019 if (X == dyn_castFoldableMul(Op1, C2))
1020 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1021 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001022 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001023}
1024
Chris Lattnere79e8542004-02-23 06:38:22 +00001025/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1026/// really just returns true if the most significant (sign) bit is set.
1027static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1028 if (RHS->getType()->isSigned()) {
1029 // True if source is LHS < 0 or LHS <= -1
1030 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1031 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1032 } else {
1033 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1034 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1035 // the size of the integer type.
1036 if (Opcode == Instruction::SetGE)
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001037 return RHSC->getValue() ==
1038 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001039 if (Opcode == Instruction::SetGT)
1040 return RHSC->getValue() ==
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001041 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattnere79e8542004-02-23 06:38:22 +00001042 }
1043 return false;
1044}
1045
Chris Lattner113f4f42002-06-25 16:13:24 +00001046Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001047 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001048 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +00001049
Chris Lattner81a7a232004-10-16 18:11:37 +00001050 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1051 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1052
Chris Lattnere6794492002-08-12 21:17:25 +00001053 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +00001054 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1055 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +00001056
1057 // ((X << C1)*C2) == (X * (C2 << C1))
1058 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1059 if (SI->getOpcode() == Instruction::Shl)
1060 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001061 return BinaryOperator::createMul(SI->getOperand(0),
1062 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001063
Chris Lattnercce81be2003-09-11 22:24:54 +00001064 if (CI->isNullValue())
1065 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1066 if (CI->equalsInt(1)) // X * 1 == X
1067 return ReplaceInstUsesWith(I, Op0);
1068 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +00001069 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +00001070
Chris Lattnercce81be2003-09-11 22:24:54 +00001071 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001072 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1073 uint64_t C = Log2_64(Val);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001074 return new ShiftInst(Instruction::Shl, Op0,
1075 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001076 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +00001077 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001078 if (Op1F->isNullValue())
1079 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +00001080
Chris Lattner3082c5a2003-02-18 19:28:33 +00001081 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1082 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1083 if (Op1F->getValue() == 1.0)
1084 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1085 }
Chris Lattner183b3362004-04-09 19:05:30 +00001086
1087 // Try to fold constant mul into select arguments.
1088 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001089 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001090 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001091
1092 if (isa<PHINode>(Op0))
1093 if (Instruction *NV = FoldOpIntoPhi(I))
1094 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +00001095 }
1096
Chris Lattner934a64cf2003-03-10 23:23:04 +00001097 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1098 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001099 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +00001100
Chris Lattner2635b522004-02-23 05:39:21 +00001101 // If one of the operands of the multiply is a cast from a boolean value, then
1102 // we know the bool is either zero or one, so this is a 'masking' multiply.
1103 // See if we can simplify things based on how the boolean was originally
1104 // formed.
1105 CastInst *BoolCast = 0;
1106 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1107 if (CI->getOperand(0)->getType() == Type::BoolTy)
1108 BoolCast = CI;
1109 if (!BoolCast)
1110 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1111 if (CI->getOperand(0)->getType() == Type::BoolTy)
1112 BoolCast = CI;
1113 if (BoolCast) {
1114 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1115 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1116 const Type *SCOpTy = SCIOp0->getType();
1117
Chris Lattnere79e8542004-02-23 06:38:22 +00001118 // If the setcc is true iff the sign bit of X is set, then convert this
1119 // multiply into a shift/and combination.
1120 if (isa<ConstantInt>(SCIOp1) &&
1121 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +00001122 // Shift the X value right to turn it into "all signbits".
1123 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001124 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattnere79e8542004-02-23 06:38:22 +00001125 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001126 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +00001127 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1128 SCIOp0->getName()), I);
1129 }
1130
1131 Value *V =
1132 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1133 BoolCast->getOperand(0)->getName()+
1134 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001135
1136 // If the multiply type is not the same as the source type, sign extend
1137 // or truncate to the multiply type.
1138 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001139 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001140
Chris Lattner2635b522004-02-23 05:39:21 +00001141 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001142 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001143 }
1144 }
1145 }
1146
Chris Lattner113f4f42002-06-25 16:13:24 +00001147 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001148}
1149
Chris Lattner113f4f42002-06-25 16:13:24 +00001150Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001151 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001152
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001153 if (isa<UndefValue>(Op0)) // undef / X -> 0
1154 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1155 if (isa<UndefValue>(Op1))
1156 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1157
1158 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001159 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001160 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001161 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001162
Chris Lattnere20c3342004-04-26 14:01:59 +00001163 // div X, -1 == -X
1164 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001165 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001166
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001167 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001168 if (LHS->getOpcode() == Instruction::Div)
1169 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001170 // (X / C1) / C2 -> X / (C1*C2)
1171 return BinaryOperator::createDiv(LHS->getOperand(0),
1172 ConstantExpr::getMul(RHS, LHSRHS));
1173 }
1174
Chris Lattner3082c5a2003-02-18 19:28:33 +00001175 // Check to see if this is an unsigned division with an exact power of 2,
1176 // if so, convert to a right shift.
1177 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1178 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattner22d00a82005-08-02 19:16:58 +00001179 if (isPowerOf2_64(Val)) {
1180 uint64_t C = Log2_64(Val);
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001181 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001182 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner22d00a82005-08-02 19:16:58 +00001183 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001184
Chris Lattner4ad08352004-10-09 02:50:40 +00001185 // -X/C -> X/-C
1186 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001187 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001188 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1189
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001190 if (!RHS->isNullValue()) {
1191 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001192 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001193 return R;
1194 if (isa<PHINode>(Op0))
1195 if (Instruction *NV = FoldOpIntoPhi(I))
1196 return NV;
1197 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001198 }
1199
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001200 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1201 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1202 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1203 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1204 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1205 if (STO->getValue() == 0) { // Couldn't be this argument.
1206 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001207 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001208 } else if (SFO->getValue() == 0) {
Chris Lattner89dc4f12005-06-16 04:55:52 +00001209 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001210 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001211 }
1212
Chris Lattner42362612005-04-08 04:03:26 +00001213 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattner22d00a82005-08-02 19:16:58 +00001214 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1215 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattner42362612005-04-08 04:03:26 +00001216 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1217 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1218 TC, SI->getName()+".t");
1219 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001220
Chris Lattner42362612005-04-08 04:03:26 +00001221 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1222 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1223 FC, SI->getName()+".f");
1224 FSI = InsertNewInstBefore(FSI, I);
1225 return new SelectInst(SI->getOperand(0), TSI, FSI);
1226 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001227 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001228
Chris Lattner3082c5a2003-02-18 19:28:33 +00001229 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001230 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001231 if (LHS->equalsInt(0))
1232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1233
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001234 return 0;
1235}
1236
1237
Chris Lattner113f4f42002-06-25 16:13:24 +00001238Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001239 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001240 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001241 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001242 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001243 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001244 // X % -Y -> X % Y
1245 AddUsesToWorkList(I);
1246 I.setOperand(1, RHSNeg);
1247 return &I;
1248 }
1249
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001250 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001251 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001252 if (isa<UndefValue>(Op1))
1253 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001254
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001255 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001256 if (RHS->equalsInt(1)) // X % 1 == 0
1257 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1258
1259 // Check to see if this is an unsigned remainder with an exact power of 2,
1260 // if so, convert to a bitwise and.
1261 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1262 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001263 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001264 return BinaryOperator::createAnd(Op0,
1265 ConstantUInt::get(I.getType(), Val-1));
1266
1267 if (!RHS->isNullValue()) {
1268 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001269 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001270 return R;
1271 if (isa<PHINode>(Op0))
1272 if (Instruction *NV = FoldOpIntoPhi(I))
1273 return NV;
1274 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001275 }
1276
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001277 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1278 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1279 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1280 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1281 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1282 if (STO->getValue() == 0) { // Couldn't be this argument.
1283 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001284 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001285 } else if (SFO->getValue() == 0) {
1286 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001287 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001288 }
1289
1290 if (!(STO->getValue() & (STO->getValue()-1)) &&
1291 !(SFO->getValue() & (SFO->getValue()-1))) {
1292 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1293 SubOne(STO), SI->getName()+".t"), I);
1294 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1295 SubOne(SFO), SI->getName()+".f"), I);
1296 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1297 }
1298 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001299
Chris Lattner3082c5a2003-02-18 19:28:33 +00001300 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001301 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001302 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001303 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1304
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001305 return 0;
1306}
1307
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001308// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001309static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001310 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1311 // Calculate -1 casted to the right type...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001312 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001313 uint64_t Val = ~0ULL; // All ones
1314 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1315 return CU->getValue() == Val-1;
1316 }
1317
1318 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001319
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001320 // Calculate 0111111111..11111
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001321 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001322 int64_t Val = INT64_MAX; // All ones
1323 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1324 return CS->getValue() == Val-1;
1325}
1326
1327// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001328static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001329 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1330 return CU->getValue() == 1;
1331
1332 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001333
1334 // Calculate 1111111111000000000000
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001335 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001336 int64_t Val = -1; // All ones
1337 Val <<= TypeBits-1; // Shift over to the right spot
1338 return CS->getValue() == Val+1;
1339}
1340
Chris Lattner35167c32004-06-09 07:59:58 +00001341// isOneBitSet - Return true if there is exactly one bit set in the specified
1342// constant.
1343static bool isOneBitSet(const ConstantInt *CI) {
1344 uint64_t V = CI->getRawValue();
1345 return V && (V & (V-1)) == 0;
1346}
1347
Chris Lattner8fc5af42004-09-23 21:46:38 +00001348#if 0 // Currently unused
1349// isLowOnes - Return true if the constant is of the form 0+1+.
1350static bool isLowOnes(const ConstantInt *CI) {
1351 uint64_t V = CI->getRawValue();
1352
1353 // There won't be bits set in parts that the type doesn't contain.
1354 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1355
1356 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1357 return U && V && (U & V) == 0;
1358}
1359#endif
1360
1361// isHighOnes - Return true if the constant is of the form 1+0+.
1362// This is the same as lowones(~X).
1363static bool isHighOnes(const ConstantInt *CI) {
1364 uint64_t V = ~CI->getRawValue();
Chris Lattner2c14cf72005-08-07 07:03:10 +00001365 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattner8fc5af42004-09-23 21:46:38 +00001366
1367 // There won't be bits set in parts that the type doesn't contain.
1368 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1369
1370 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1371 return U && V && (U & V) == 0;
1372}
1373
1374
Chris Lattner3ac7c262003-08-13 20:16:26 +00001375/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1376/// are carefully arranged to allow folding of expressions such as:
1377///
1378/// (A < B) | (A > B) --> (A != B)
1379///
1380/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1381/// represents that the comparison is true if A == B, and bit value '1' is true
1382/// if A < B.
1383///
1384static unsigned getSetCondCode(const SetCondInst *SCI) {
1385 switch (SCI->getOpcode()) {
1386 // False -> 0
1387 case Instruction::SetGT: return 1;
1388 case Instruction::SetEQ: return 2;
1389 case Instruction::SetGE: return 3;
1390 case Instruction::SetLT: return 4;
1391 case Instruction::SetNE: return 5;
1392 case Instruction::SetLE: return 6;
1393 // True -> 7
1394 default:
1395 assert(0 && "Invalid SetCC opcode!");
1396 return 0;
1397 }
1398}
1399
1400/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1401/// opcode and two operands into either a constant true or false, or a brand new
1402/// SetCC instruction.
1403static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1404 switch (Opcode) {
1405 case 0: return ConstantBool::False;
1406 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1407 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1408 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1409 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1410 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1411 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1412 case 7: return ConstantBool::True;
1413 default: assert(0 && "Illegal SetCCCode!"); return 0;
1414 }
1415}
1416
1417// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1418struct FoldSetCCLogical {
1419 InstCombiner &IC;
1420 Value *LHS, *RHS;
1421 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1422 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1423 bool shouldApply(Value *V) const {
1424 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1425 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1426 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1427 return false;
1428 }
1429 Instruction *apply(BinaryOperator &Log) const {
1430 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1431 if (SCI->getOperand(0) != LHS) {
1432 assert(SCI->getOperand(1) == LHS);
1433 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1434 }
1435
1436 unsigned LHSCode = getSetCondCode(SCI);
1437 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1438 unsigned Code;
1439 switch (Log.getOpcode()) {
1440 case Instruction::And: Code = LHSCode & RHSCode; break;
1441 case Instruction::Or: Code = LHSCode | RHSCode; break;
1442 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001443 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001444 }
1445
1446 Value *RV = getSetCCValue(Code, LHS, RHS);
1447 if (Instruction *I = dyn_cast<Instruction>(RV))
1448 return I;
1449 // Otherwise, it's a constant boolean value...
1450 return IC.ReplaceInstUsesWith(Log, RV);
1451 }
1452};
1453
Chris Lattnerba1cb382003-09-19 17:17:26 +00001454// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1455// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1456// guaranteed to be either a shift instruction or a binary operator.
1457Instruction *InstCombiner::OptAndOp(Instruction *Op,
1458 ConstantIntegral *OpRHS,
1459 ConstantIntegral *AndRHS,
1460 BinaryOperator &TheAnd) {
1461 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001462 Constant *Together = 0;
1463 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001464 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001465
Chris Lattnerba1cb382003-09-19 17:17:26 +00001466 switch (Op->getOpcode()) {
1467 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001468 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001469 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1470 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001471 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001472 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001473 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001474 }
1475 break;
1476 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001477 if (Together == AndRHS) // (X | C) & C --> C
1478 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001479
Chris Lattner86102b82005-01-01 16:22:27 +00001480 if (Op->hasOneUse() && Together != OpRHS) {
1481 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1482 std::string Op0Name = Op->getName(); Op->setName("");
1483 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1484 InsertNewInstBefore(Or, TheAnd);
1485 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001486 }
1487 break;
1488 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001489 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001490 // Adding a one to a single bit bit-field should be turned into an XOR
1491 // of the bit. First thing to check is to see if this AND is with a
1492 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001493 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001494
1495 // Clear bits that are not part of the constant.
Chris Lattner2f1457f2005-04-24 17:46:05 +00001496 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerba1cb382003-09-19 17:17:26 +00001497
1498 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001499 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001500 // Ok, at this point, we know that we are masking the result of the
1501 // ADD down to exactly one bit. If the constant we are adding has
1502 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001503 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001504
Chris Lattnerba1cb382003-09-19 17:17:26 +00001505 // Check to see if any bits below the one bit set in AndRHSV are set.
1506 if ((AddRHS & (AndRHSV-1)) == 0) {
1507 // If not, the only thing that can effect the output of the AND is
1508 // the bit specified by AndRHSV. If that bit is set, the effect of
1509 // the XOR is to toggle the bit. If it is clear, then the ADD has
1510 // no effect.
1511 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1512 TheAnd.setOperand(0, X);
1513 return &TheAnd;
1514 } else {
1515 std::string Name = Op->getName(); Op->setName("");
1516 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001517 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001518 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001519 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001520 }
1521 }
1522 }
1523 }
1524 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001525
1526 case Instruction::Shl: {
1527 // We know that the AND will not produce any of the bits shifted in, so if
1528 // the anded constant includes them, clear them now!
1529 //
1530 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001531 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1532 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001533
Chris Lattner7e794272004-09-24 15:21:34 +00001534 if (CI == ShlMask) { // Masking out bits that the shift already masks
1535 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1536 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001537 TheAnd.setOperand(1, CI);
1538 return &TheAnd;
1539 }
1540 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001541 }
Chris Lattner2da29172003-09-19 19:05:02 +00001542 case Instruction::Shr:
1543 // We know that the AND will not produce any of the bits shifted in, so if
1544 // the anded constant includes them, clear them now! This only applies to
1545 // unsigned shifts, because a signed shr may bring in set bits!
1546 //
1547 if (AndRHS->getType()->isUnsigned()) {
1548 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001549 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1550 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1551
1552 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1553 return ReplaceInstUsesWith(TheAnd, Op);
1554 } else if (CI != AndRHS) {
1555 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001556 return &TheAnd;
1557 }
Chris Lattner7e794272004-09-24 15:21:34 +00001558 } else { // Signed shr.
1559 // See if this is shifting in some sign extension, then masking it out
1560 // with an and.
1561 if (Op->hasOneUse()) {
1562 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1563 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1564 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001565 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001566 // Make the argument unsigned.
1567 Value *ShVal = Op->getOperand(0);
1568 ShVal = InsertCastBefore(ShVal,
1569 ShVal->getType()->getUnsignedVersion(),
1570 TheAnd);
1571 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1572 OpRHS, Op->getName()),
1573 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001574 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1575 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1576 TheAnd.getName()),
1577 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001578 return new CastInst(ShVal, Op->getType());
1579 }
1580 }
Chris Lattner2da29172003-09-19 19:05:02 +00001581 }
1582 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001583 }
1584 return 0;
1585}
1586
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001587
Chris Lattner6862fbd2004-09-29 17:40:11 +00001588/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1589/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1590/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1591/// insert new instructions.
1592Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1593 bool Inside, Instruction &IB) {
1594 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1595 "Lo is not <= Hi in range emission code!");
1596 if (Inside) {
1597 if (Lo == Hi) // Trivially false.
1598 return new SetCondInst(Instruction::SetNE, V, V);
1599 if (cast<ConstantIntegral>(Lo)->isMinValue())
1600 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001601
Chris Lattner6862fbd2004-09-29 17:40:11 +00001602 Constant *AddCST = ConstantExpr::getNeg(Lo);
1603 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1604 InsertNewInstBefore(Add, IB);
1605 // Convert to unsigned for the comparison.
1606 const Type *UnsType = Add->getType()->getUnsignedVersion();
1607 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1608 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1609 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1610 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1611 }
1612
1613 if (Lo == Hi) // Trivially true.
1614 return new SetCondInst(Instruction::SetEQ, V, V);
1615
1616 Hi = SubOne(cast<ConstantInt>(Hi));
1617 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1618 return new SetCondInst(Instruction::SetGT, V, Hi);
1619
1620 // Emit X-Lo > Hi-Lo-1
1621 Constant *AddCST = ConstantExpr::getNeg(Lo);
1622 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1623 InsertNewInstBefore(Add, IB);
1624 // Convert to unsigned for the comparison.
1625 const Type *UnsType = Add->getType()->getUnsignedVersion();
1626 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1627 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1628 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1629 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1630}
1631
Chris Lattnerb4b25302005-09-18 07:22:02 +00001632// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1633// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1634// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1635// not, since all 1s are not contiguous.
1636static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1637 uint64_t V = Val->getRawValue();
1638 if (!isShiftedMask_64(V)) return false;
1639
1640 // look for the first zero bit after the run of ones
1641 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1642 // look for the first non-zero bit
1643 ME = 64-CountLeadingZeros_64(V);
1644 return true;
1645}
1646
1647
1648
1649/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1650/// where isSub determines whether the operator is a sub. If we can fold one of
1651/// the following xforms:
Chris Lattneraf517572005-09-18 04:24:45 +00001652///
1653/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1654/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1655/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1656///
1657/// return (A +/- B).
1658///
1659Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1660 ConstantIntegral *Mask, bool isSub,
1661 Instruction &I) {
1662 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1663 if (!LHSI || LHSI->getNumOperands() != 2 ||
1664 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1665
1666 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1667
1668 switch (LHSI->getOpcode()) {
1669 default: return 0;
1670 case Instruction::And:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001671 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1672 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1673 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1674 break;
1675
1676 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1677 // part, we don't need any explicit masks to take them out of A. If that
1678 // is all N is, ignore it.
1679 unsigned MB, ME;
1680 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1681 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1682 Mask = ConstantExpr::getUShr(Mask,
1683 ConstantInt::get(Type::UByteTy,
1684 (64-MB+1)));
1685 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1686 break;
1687 }
1688 }
Chris Lattneraf517572005-09-18 04:24:45 +00001689 return 0;
1690 case Instruction::Or:
1691 case Instruction::Xor:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001692 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1693 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1694 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattneraf517572005-09-18 04:24:45 +00001695 break;
1696 return 0;
1697 }
1698
1699 Instruction *New;
1700 if (isSub)
1701 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1702 else
1703 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1704 return InsertNewInstBefore(New, I);
1705}
1706
Chris Lattner6862fbd2004-09-29 17:40:11 +00001707
Chris Lattner113f4f42002-06-25 16:13:24 +00001708Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001709 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001710 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001711
Chris Lattner81a7a232004-10-16 18:11:37 +00001712 if (isa<UndefValue>(Op1)) // X & undef -> 0
1713 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1714
Chris Lattner86102b82005-01-01 16:22:27 +00001715 // and X, X = X
1716 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001717 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001718
Chris Lattner86102b82005-01-01 16:22:27 +00001719 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001720 // and X, -1 == X
1721 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001722 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001723
Chris Lattner86102b82005-01-01 16:22:27 +00001724 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1725 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1726
1727 // If the mask is not masking out any bits, there is no reason to do the
1728 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001729 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001730 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001731 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001732 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001733
Chris Lattnerba1cb382003-09-19 17:17:26 +00001734 // Optimize a variety of ((val OP C1) & C2) combinations...
1735 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1736 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001737 Value *Op0LHS = Op0I->getOperand(0);
1738 Value *Op0RHS = Op0I->getOperand(1);
1739 switch (Op0I->getOpcode()) {
1740 case Instruction::Xor:
1741 case Instruction::Or:
1742 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1743 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1744 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001745 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001746 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001747 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001748
1749 // If the mask is only needed on one incoming arm, push it up.
1750 if (Op0I->hasOneUse()) {
1751 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1752 // Not masking anything out for the LHS, move to RHS.
1753 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1754 Op0RHS->getName()+".masked");
1755 InsertNewInstBefore(NewRHS, I);
1756 return BinaryOperator::create(
1757 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001758 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001759 if (!isa<Constant>(NotAndRHS) &&
1760 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1761 // Not masking anything out for the RHS, move to LHS.
1762 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1763 Op0LHS->getName()+".masked");
1764 InsertNewInstBefore(NewLHS, I);
1765 return BinaryOperator::create(
1766 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1767 }
1768 }
1769
Chris Lattner86102b82005-01-01 16:22:27 +00001770 break;
1771 case Instruction::And:
1772 // (X & V) & C2 --> 0 iff (V & C2) == 0
1773 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1774 MaskedValueIsZero(Op0RHS, AndRHS))
1775 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1776 break;
Chris Lattneraf517572005-09-18 04:24:45 +00001777 case Instruction::Add:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001778 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1779 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1780 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1781 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1782 return BinaryOperator::createAnd(V, AndRHS);
1783 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1784 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattneraf517572005-09-18 04:24:45 +00001785 break;
1786
1787 case Instruction::Sub:
Chris Lattnerb4b25302005-09-18 07:22:02 +00001788 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1789 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1790 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1791 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1792 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattneraf517572005-09-18 04:24:45 +00001793 break;
Chris Lattner86102b82005-01-01 16:22:27 +00001794 }
1795
Chris Lattner16464b32003-07-23 19:25:52 +00001796 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001797 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001798 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001799 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1800 const Type *SrcTy = CI->getOperand(0)->getType();
1801
Chris Lattner2c14cf72005-08-07 07:03:10 +00001802 // If this is an integer truncation or change from signed-to-unsigned, and
1803 // if the source is an and/or with immediate, transform it. This
1804 // frequently occurs for bitfield accesses.
1805 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1806 if (SrcTy->getPrimitiveSizeInBits() >=
1807 I.getType()->getPrimitiveSizeInBits() &&
1808 CastOp->getNumOperands() == 2)
1809 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1810 if (CastOp->getOpcode() == Instruction::And) {
1811 // Change: and (cast (and X, C1) to T), C2
1812 // into : and (cast X to T), trunc(C1)&C2
1813 // This will folds the two ands together, which may allow other
1814 // simplifications.
1815 Instruction *NewCast =
1816 new CastInst(CastOp->getOperand(0), I.getType(),
1817 CastOp->getName()+".shrunk");
1818 NewCast = InsertNewInstBefore(NewCast, I);
1819
1820 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1821 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1822 return BinaryOperator::createAnd(NewCast, C3);
1823 } else if (CastOp->getOpcode() == Instruction::Or) {
1824 // Change: and (cast (or X, C1) to T), C2
1825 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1826 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1827 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1828 return ReplaceInstUsesWith(I, AndRHS);
1829 }
1830 }
1831
1832
Chris Lattner86102b82005-01-01 16:22:27 +00001833 // If this is an integer sign or zero extension instruction.
1834 if (SrcTy->isIntegral() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00001835 SrcTy->getPrimitiveSizeInBits() <
1836 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00001837
1838 if (SrcTy->isUnsigned()) {
1839 // See if this and is clearing out bits that are known to be zero
1840 // anyway (due to the zero extension).
1841 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1842 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1843 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1844 if (Result == Mask) // The "and" isn't doing anything, remove it.
1845 return ReplaceInstUsesWith(I, CI);
1846 if (Result != AndRHS) { // Reduce the and RHS constant.
1847 I.setOperand(1, Result);
1848 return &I;
1849 }
1850
1851 } else {
1852 if (CI->hasOneUse() && SrcTy->isInteger()) {
1853 // We can only do this if all of the sign bits brought in are masked
1854 // out. Compute this by first getting 0000011111, then inverting
1855 // it.
1856 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1857 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1858 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1859 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1860 // If the and is clearing all of the sign bits, change this to a
1861 // zero extension cast. To do this, cast the cast input to
1862 // unsigned, then to the requested size.
1863 Value *CastOp = CI->getOperand(0);
1864 Instruction *NC =
1865 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1866 CI->getName()+".uns");
1867 NC = InsertNewInstBefore(NC, I);
1868 // Finally, insert a replacement for CI.
1869 NC = new CastInst(NC, CI->getType(), CI->getName());
1870 CI->setName("");
1871 NC = InsertNewInstBefore(NC, I);
1872 WorkList.push_back(CI); // Delete CI later.
1873 I.setOperand(0, NC);
1874 return &I; // The AND operand was modified.
1875 }
1876 }
1877 }
1878 }
Chris Lattner33217db2003-07-23 19:36:21 +00001879 }
Chris Lattner183b3362004-04-09 19:05:30 +00001880
1881 // Try to fold constant and into select arguments.
1882 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001883 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001884 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001885 if (isa<PHINode>(Op0))
1886 if (Instruction *NV = FoldOpIntoPhi(I))
1887 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001888 }
1889
Chris Lattnerbb74e222003-03-10 23:06:50 +00001890 Value *Op0NotVal = dyn_castNotVal(Op0);
1891 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001892
Chris Lattner023a4832004-06-18 06:07:51 +00001893 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1894 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1895
Misha Brukman9c003d82004-07-30 12:50:08 +00001896 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001897 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001898 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1899 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001900 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001901 return BinaryOperator::createNot(Or);
1902 }
1903
Chris Lattner623826c2004-09-28 21:48:02 +00001904 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1905 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001906 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1907 return R;
1908
Chris Lattner623826c2004-09-28 21:48:02 +00001909 Value *LHSVal, *RHSVal;
1910 ConstantInt *LHSCst, *RHSCst;
1911 Instruction::BinaryOps LHSCC, RHSCC;
1912 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1913 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1914 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1915 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001916 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001917 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1918 // Ensure that the larger constant is on the RHS.
1919 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1920 SetCondInst *LHS = cast<SetCondInst>(Op0);
1921 if (cast<ConstantBool>(Cmp)->getValue()) {
1922 std::swap(LHS, RHS);
1923 std::swap(LHSCst, RHSCst);
1924 std::swap(LHSCC, RHSCC);
1925 }
1926
1927 // At this point, we know we have have two setcc instructions
1928 // comparing a value against two constants and and'ing the result
1929 // together. Because of the above check, we know that we only have
1930 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1931 // FoldSetCCLogical check above), that the two constants are not
1932 // equal.
1933 assert(LHSCst != RHSCst && "Compares not folded above?");
1934
1935 switch (LHSCC) {
1936 default: assert(0 && "Unknown integer condition code!");
1937 case Instruction::SetEQ:
1938 switch (RHSCC) {
1939 default: assert(0 && "Unknown integer condition code!");
1940 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1941 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1942 return ReplaceInstUsesWith(I, ConstantBool::False);
1943 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1944 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1945 return ReplaceInstUsesWith(I, LHS);
1946 }
1947 case Instruction::SetNE:
1948 switch (RHSCC) {
1949 default: assert(0 && "Unknown integer condition code!");
1950 case Instruction::SetLT:
1951 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1952 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1953 break; // (X != 13 & X < 15) -> no change
1954 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1955 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1956 return ReplaceInstUsesWith(I, RHS);
1957 case Instruction::SetNE:
1958 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1959 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1960 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1961 LHSVal->getName()+".off");
1962 InsertNewInstBefore(Add, I);
1963 const Type *UnsType = Add->getType()->getUnsignedVersion();
1964 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1965 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1966 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1967 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1968 }
1969 break; // (X != 13 & X != 15) -> no change
1970 }
1971 break;
1972 case Instruction::SetLT:
1973 switch (RHSCC) {
1974 default: assert(0 && "Unknown integer condition code!");
1975 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1976 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1977 return ReplaceInstUsesWith(I, ConstantBool::False);
1978 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1979 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1980 return ReplaceInstUsesWith(I, LHS);
1981 }
1982 case Instruction::SetGT:
1983 switch (RHSCC) {
1984 default: assert(0 && "Unknown integer condition code!");
1985 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1986 return ReplaceInstUsesWith(I, LHS);
1987 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1988 return ReplaceInstUsesWith(I, RHS);
1989 case Instruction::SetNE:
1990 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1991 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1992 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001993 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1994 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001995 }
1996 }
1997 }
1998 }
1999
Chris Lattner113f4f42002-06-25 16:13:24 +00002000 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002001}
2002
Chris Lattner113f4f42002-06-25 16:13:24 +00002003Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002004 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002005 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002006
Chris Lattner81a7a232004-10-16 18:11:37 +00002007 if (isa<UndefValue>(Op1))
2008 return ReplaceInstUsesWith(I, // X | undef -> -1
2009 ConstantIntegral::getAllOnesValue(I.getType()));
2010
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002011 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00002012 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2013 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002014
2015 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00002016 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00002017 // If X is known to only contain bits that already exist in RHS, just
2018 // replace this instruction with RHS directly.
2019 if (MaskedValueIsZero(Op0,
2020 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2021 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002022
Chris Lattnerd4252a72004-07-30 07:50:03 +00002023 ConstantInt *C1; Value *X;
2024 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2025 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattnerb62f5082005-05-09 04:58:36 +00002026 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2027 Op0->setName("");
Chris Lattnerd4252a72004-07-30 07:50:03 +00002028 InsertNewInstBefore(Or, I);
2029 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2030 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00002031
Chris Lattnerd4252a72004-07-30 07:50:03 +00002032 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2033 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2034 std::string Op0Name = Op0->getName(); Op0->setName("");
2035 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2036 InsertNewInstBefore(Or, I);
2037 return BinaryOperator::createXor(Or,
2038 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00002039 }
Chris Lattner183b3362004-04-09 19:05:30 +00002040
2041 // Try to fold constant and into select arguments.
2042 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002043 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002044 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002045 if (isa<PHINode>(Op0))
2046 if (Instruction *NV = FoldOpIntoPhi(I))
2047 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00002048 }
2049
Chris Lattnerd4252a72004-07-30 07:50:03 +00002050 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattner4294cec2005-05-07 23:49:08 +00002051
2052 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2053 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2054 return ReplaceInstUsesWith(I, Op1);
2055 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2056 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2057 return ReplaceInstUsesWith(I, Op0);
2058
Chris Lattnerb62f5082005-05-09 04:58:36 +00002059 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2060 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2061 MaskedValueIsZero(Op1, C1)) {
2062 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2063 Op0->setName("");
2064 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2065 }
2066
2067 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2068 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2069 MaskedValueIsZero(Op0, C1)) {
2070 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2071 Op0->setName("");
2072 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2073 }
2074
Chris Lattner15212982005-09-18 03:42:07 +00002075 // (A & C1)|(B & C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00002076 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner15212982005-09-18 03:42:07 +00002077 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2078
2079 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2080 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2081
2082
Chris Lattner01f56c62005-09-18 06:02:59 +00002083 // If we have: ((V + N) & C1) | (V & C2)
2084 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2085 // replace with V+N.
2086 if (C1 == ConstantExpr::getNot(C2)) {
2087 Value *V1, *V2;
2088 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2089 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2090 // Add commutes, try both ways.
2091 if (V1 == B && MaskedValueIsZero(V2, C2))
2092 return ReplaceInstUsesWith(I, A);
2093 if (V2 == B && MaskedValueIsZero(V1, C2))
2094 return ReplaceInstUsesWith(I, A);
2095 }
2096 // Or commutes, try both ways.
2097 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2098 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2099 // Add commutes, try both ways.
2100 if (V1 == A && MaskedValueIsZero(V2, C1))
2101 return ReplaceInstUsesWith(I, B);
2102 if (V2 == A && MaskedValueIsZero(V1, C1))
2103 return ReplaceInstUsesWith(I, B);
Chris Lattner15212982005-09-18 03:42:07 +00002104 }
2105 }
2106 }
Chris Lattner812aab72003-08-12 19:11:07 +00002107
Chris Lattnerd4252a72004-07-30 07:50:03 +00002108 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2109 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00002110 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002111 ConstantIntegral::getAllOnesValue(I.getType()));
2112 } else {
2113 A = 0;
2114 }
Chris Lattner4294cec2005-05-07 23:49:08 +00002115 // Note, A is still live here!
Chris Lattnerd4252a72004-07-30 07:50:03 +00002116 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2117 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002118 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00002119 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00002120
Misha Brukman9c003d82004-07-30 12:50:08 +00002121 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00002122 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2123 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2124 I.getName()+".demorgan"), I);
2125 return BinaryOperator::createNot(And);
2126 }
Chris Lattner3e327a42003-03-10 23:13:59 +00002127 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00002128
Chris Lattner3ac7c262003-08-13 20:16:26 +00002129 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002130 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00002131 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2132 return R;
2133
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002134 Value *LHSVal, *RHSVal;
2135 ConstantInt *LHSCst, *RHSCst;
2136 Instruction::BinaryOps LHSCC, RHSCC;
2137 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2138 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2139 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2140 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002141 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002142 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2143 // Ensure that the larger constant is on the RHS.
2144 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2145 SetCondInst *LHS = cast<SetCondInst>(Op0);
2146 if (cast<ConstantBool>(Cmp)->getValue()) {
2147 std::swap(LHS, RHS);
2148 std::swap(LHSCst, RHSCst);
2149 std::swap(LHSCC, RHSCC);
2150 }
2151
2152 // At this point, we know we have have two setcc instructions
2153 // comparing a value against two constants and or'ing the result
2154 // together. Because of the above check, we know that we only have
2155 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2156 // FoldSetCCLogical check above), that the two constants are not
2157 // equal.
2158 assert(LHSCst != RHSCst && "Compares not folded above?");
2159
2160 switch (LHSCC) {
2161 default: assert(0 && "Unknown integer condition code!");
2162 case Instruction::SetEQ:
2163 switch (RHSCC) {
2164 default: assert(0 && "Unknown integer condition code!");
2165 case Instruction::SetEQ:
2166 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2167 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2168 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2169 LHSVal->getName()+".off");
2170 InsertNewInstBefore(Add, I);
2171 const Type *UnsType = Add->getType()->getUnsignedVersion();
2172 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2173 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2174 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2175 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2176 }
2177 break; // (X == 13 | X == 15) -> no change
2178
Chris Lattner5c219462005-04-19 06:04:18 +00002179 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2180 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002181 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2182 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2183 return ReplaceInstUsesWith(I, RHS);
2184 }
2185 break;
2186 case Instruction::SetNE:
2187 switch (RHSCC) {
2188 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002189 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2190 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2191 return ReplaceInstUsesWith(I, LHS);
2192 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattner2ceb6ee2005-06-17 03:59:17 +00002193 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002194 return ReplaceInstUsesWith(I, ConstantBool::True);
2195 }
2196 break;
2197 case Instruction::SetLT:
2198 switch (RHSCC) {
2199 default: assert(0 && "Unknown integer condition code!");
2200 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2201 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002202 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2203 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00002204 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2205 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2206 return ReplaceInstUsesWith(I, RHS);
2207 }
2208 break;
2209 case Instruction::SetGT:
2210 switch (RHSCC) {
2211 default: assert(0 && "Unknown integer condition code!");
2212 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2213 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2214 return ReplaceInstUsesWith(I, LHS);
2215 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2216 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2217 return ReplaceInstUsesWith(I, ConstantBool::True);
2218 }
2219 }
2220 }
2221 }
Chris Lattner15212982005-09-18 03:42:07 +00002222
Chris Lattner113f4f42002-06-25 16:13:24 +00002223 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002224}
2225
Chris Lattnerc2076352004-02-16 01:20:27 +00002226// XorSelf - Implements: X ^ X --> 0
2227struct XorSelf {
2228 Value *RHS;
2229 XorSelf(Value *rhs) : RHS(rhs) {}
2230 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2231 Instruction *apply(BinaryOperator &Xor) const {
2232 return &Xor;
2233 }
2234};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002235
2236
Chris Lattner113f4f42002-06-25 16:13:24 +00002237Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002238 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002239 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002240
Chris Lattner81a7a232004-10-16 18:11:37 +00002241 if (isa<UndefValue>(Op1))
2242 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2243
Chris Lattnerc2076352004-02-16 01:20:27 +00002244 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2245 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2246 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002247 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002248 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002249
Chris Lattner97638592003-07-23 21:37:07 +00002250 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002251 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002252 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002253 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002254
Chris Lattner97638592003-07-23 21:37:07 +00002255 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002256 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002257 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002258 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002259 return new SetCondInst(SCI->getInverseCondition(),
2260 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002261
Chris Lattner8f2f5982003-11-05 01:06:05 +00002262 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002263 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2264 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002265 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2266 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002267 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002268 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002269 }
Chris Lattner023a4832004-06-18 06:07:51 +00002270
2271 // ~(~X & Y) --> (X | ~Y)
2272 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2273 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2274 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2275 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002276 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002277 Op0I->getOperand(1)->getName()+".not");
2278 InsertNewInstBefore(NotY, I);
2279 return BinaryOperator::createOr(Op0NotVal, NotY);
2280 }
2281 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002282
Chris Lattner97638592003-07-23 21:37:07 +00002283 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002284 switch (Op0I->getOpcode()) {
2285 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002286 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002287 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002288 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2289 return BinaryOperator::createSub(
2290 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002291 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002292 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002293 }
Chris Lattnere5806662003-11-04 23:50:51 +00002294 break;
2295 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002296 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002297 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2298 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002299 break;
2300 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002301 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002302 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002303 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002304 break;
2305 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002306 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002307 }
Chris Lattner183b3362004-04-09 19:05:30 +00002308
2309 // Try to fold constant and into select arguments.
2310 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002311 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002312 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002313 if (isa<PHINode>(Op0))
2314 if (Instruction *NV = FoldOpIntoPhi(I))
2315 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002316 }
2317
Chris Lattnerbb74e222003-03-10 23:06:50 +00002318 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002319 if (X == Op1)
2320 return ReplaceInstUsesWith(I,
2321 ConstantIntegral::getAllOnesValue(I.getType()));
2322
Chris Lattnerbb74e222003-03-10 23:06:50 +00002323 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002324 if (X == Op0)
2325 return ReplaceInstUsesWith(I,
2326 ConstantIntegral::getAllOnesValue(I.getType()));
2327
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002328 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002329 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002330 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2331 cast<BinaryOperator>(Op1I)->swapOperands();
2332 I.swapOperands();
2333 std::swap(Op0, Op1);
2334 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2335 I.swapOperands();
2336 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002337 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002338 } else if (Op1I->getOpcode() == Instruction::Xor) {
2339 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2340 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2341 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2342 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2343 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002344
2345 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002346 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002347 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2348 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002349 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002350 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2351 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002352 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002353 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002354 } else if (Op0I->getOpcode() == Instruction::Xor) {
2355 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2356 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2357 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2358 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002359 }
2360
Chris Lattner7aa2d472004-08-01 19:42:59 +00002361 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002362 Value *A, *B; ConstantInt *C1, *C2;
2363 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2364 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002365 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002366 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002367
Chris Lattner3ac7c262003-08-13 20:16:26 +00002368 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2369 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2370 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2371 return R;
2372
Chris Lattner113f4f42002-06-25 16:13:24 +00002373 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002374}
2375
Chris Lattner6862fbd2004-09-29 17:40:11 +00002376/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2377/// overflowed for this type.
2378static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2379 ConstantInt *In2) {
2380 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2381 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2382}
2383
2384static bool isPositive(ConstantInt *C) {
2385 return cast<ConstantSInt>(C)->getValue() >= 0;
2386}
2387
2388/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2389/// overflowed for this type.
2390static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2391 ConstantInt *In2) {
2392 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2393
2394 if (In1->getType()->isUnsigned())
2395 return cast<ConstantUInt>(Result)->getValue() <
2396 cast<ConstantUInt>(In1)->getValue();
2397 if (isPositive(In1) != isPositive(In2))
2398 return false;
2399 if (isPositive(In1))
2400 return cast<ConstantSInt>(Result)->getValue() <
2401 cast<ConstantSInt>(In1)->getValue();
2402 return cast<ConstantSInt>(Result)->getValue() >
2403 cast<ConstantSInt>(In1)->getValue();
2404}
2405
Chris Lattner0798af32005-01-13 20:14:25 +00002406/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2407/// code necessary to compute the offset from the base pointer (without adding
2408/// in the base pointer). Return the result as a signed integer of intptr size.
2409static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2410 TargetData &TD = IC.getTargetData();
2411 gep_type_iterator GTI = gep_type_begin(GEP);
2412 const Type *UIntPtrTy = TD.getIntPtrType();
2413 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2414 Value *Result = Constant::getNullValue(SIntPtrTy);
2415
2416 // Build a mask for high order bits.
2417 uint64_t PtrSizeMask = ~0ULL;
2418 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2419
Chris Lattner0798af32005-01-13 20:14:25 +00002420 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2421 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002422 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002423 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2424 SIntPtrTy);
2425 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2426 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002427 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002428 Scale = ConstantExpr::getMul(OpC, Scale);
2429 if (Constant *RC = dyn_cast<Constant>(Result))
2430 Result = ConstantExpr::getAdd(RC, Scale);
2431 else {
2432 // Emit an add instruction.
2433 Result = IC.InsertNewInstBefore(
2434 BinaryOperator::createAdd(Result, Scale,
2435 GEP->getName()+".offs"), I);
2436 }
2437 }
2438 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002439 // Convert to correct type.
2440 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2441 Op->getName()+".c"), I);
2442 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002443 // We'll let instcombine(mul) convert this to a shl if possible.
2444 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2445 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002446
2447 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002448 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002449 GEP->getName()+".offs"), I);
2450 }
2451 }
2452 return Result;
2453}
2454
2455/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2456/// else. At this point we know that the GEP is on the LHS of the comparison.
2457Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2458 Instruction::BinaryOps Cond,
2459 Instruction &I) {
2460 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002461
2462 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2463 if (isa<PointerType>(CI->getOperand(0)->getType()))
2464 RHS = CI->getOperand(0);
2465
Chris Lattner0798af32005-01-13 20:14:25 +00002466 Value *PtrBase = GEPLHS->getOperand(0);
2467 if (PtrBase == RHS) {
2468 // As an optimization, we don't actually have to compute the actual value of
2469 // OFFSET if this is a seteq or setne comparison, just return whether each
2470 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002471 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2472 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002473 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2474 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002475 bool EmitIt = true;
2476 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2477 if (isa<UndefValue>(C)) // undef index -> undef.
2478 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2479 if (C->isNullValue())
2480 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002481 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2482 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002483 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002484 return ReplaceInstUsesWith(I, // No comparison is needed here.
2485 ConstantBool::get(Cond == Instruction::SetNE));
2486 }
2487
2488 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002489 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002490 new SetCondInst(Cond, GEPLHS->getOperand(i),
2491 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2492 if (InVal == 0)
2493 InVal = Comp;
2494 else {
2495 InVal = InsertNewInstBefore(InVal, I);
2496 InsertNewInstBefore(Comp, I);
2497 if (Cond == Instruction::SetNE) // True if any are unequal
2498 InVal = BinaryOperator::createOr(InVal, Comp);
2499 else // True if all are equal
2500 InVal = BinaryOperator::createAnd(InVal, Comp);
2501 }
2502 }
2503 }
2504
2505 if (InVal)
2506 return InVal;
2507 else
2508 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2509 ConstantBool::get(Cond == Instruction::SetEQ));
2510 }
Chris Lattner0798af32005-01-13 20:14:25 +00002511
2512 // Only lower this if the setcc is the only user of the GEP or if we expect
2513 // the result to fold to a constant!
2514 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2515 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2516 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2517 return new SetCondInst(Cond, Offset,
2518 Constant::getNullValue(Offset->getType()));
2519 }
2520 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002521 // If the base pointers are different, but the indices are the same, just
2522 // compare the base pointer.
2523 if (PtrBase != GEPRHS->getOperand(0)) {
2524 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002525 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattnerbd43b9d2005-04-26 14:40:41 +00002526 GEPRHS->getOperand(0)->getType();
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002527 if (IndicesTheSame)
2528 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2529 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2530 IndicesTheSame = false;
2531 break;
2532 }
2533
2534 // If all indices are the same, just compare the base pointers.
2535 if (IndicesTheSame)
2536 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2537 GEPRHS->getOperand(0));
2538
2539 // Otherwise, the base pointers are different and the indices are
2540 // different, bail out.
Chris Lattner0798af32005-01-13 20:14:25 +00002541 return 0;
Chris Lattnera21bf8d2005-04-25 20:17:30 +00002542 }
Chris Lattner0798af32005-01-13 20:14:25 +00002543
Chris Lattner81e84172005-01-13 22:25:21 +00002544 // If one of the GEPs has all zero indices, recurse.
2545 bool AllZeros = true;
2546 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2547 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2548 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2549 AllZeros = false;
2550 break;
2551 }
2552 if (AllZeros)
2553 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2554 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002555
2556 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002557 AllZeros = true;
2558 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2559 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2560 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2561 AllZeros = false;
2562 break;
2563 }
2564 if (AllZeros)
2565 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2566
Chris Lattner4fa89822005-01-14 00:20:05 +00002567 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2568 // If the GEPs only differ by one index, compare it.
2569 unsigned NumDifferences = 0; // Keep track of # differences.
2570 unsigned DiffOperand = 0; // The operand that differs.
2571 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2572 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002573 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2574 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002575 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002576 NumDifferences = 2;
2577 break;
2578 } else {
2579 if (NumDifferences++) break;
2580 DiffOperand = i;
2581 }
2582 }
2583
2584 if (NumDifferences == 0) // SAME GEP?
2585 return ReplaceInstUsesWith(I, // No comparison is needed here.
2586 ConstantBool::get(Cond == Instruction::SetEQ));
2587 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002588 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2589 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner247aef82005-07-18 23:07:33 +00002590
2591 // Convert the operands to signed values to make sure to perform a
2592 // signed comparison.
2593 const Type *NewTy = LHSV->getType()->getSignedVersion();
2594 if (LHSV->getType() != NewTy)
2595 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2596 LHSV->getName()), I);
2597 if (RHSV->getType() != NewTy)
2598 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2599 RHSV->getName()), I);
2600 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002601 }
2602 }
2603
Chris Lattner0798af32005-01-13 20:14:25 +00002604 // Only lower this if the setcc is the only user of the GEP or if we expect
2605 // the result to fold to a constant!
2606 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2607 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2608 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2609 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2610 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2611 return new SetCondInst(Cond, L, R);
2612 }
2613 }
2614 return 0;
2615}
2616
2617
Chris Lattnerd1f46d32005-04-24 06:59:08 +00002618Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002619 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2621 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002622
2623 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002624 if (Op0 == Op1)
2625 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002626
Chris Lattner81a7a232004-10-16 18:11:37 +00002627 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2628 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2629
Chris Lattner15ff1e12004-11-14 07:33:16 +00002630 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2631 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002632 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2633 isa<ConstantPointerNull>(Op0)) &&
2634 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002635 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002636 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2637
2638 // setcc's with boolean values can always be turned into bitwise operations
2639 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002640 switch (I.getOpcode()) {
2641 default: assert(0 && "Invalid setcc instruction!");
2642 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002643 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002644 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002645 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002646 }
Chris Lattner4456da62004-08-11 00:50:51 +00002647 case Instruction::SetNE:
2648 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002649
Chris Lattner4456da62004-08-11 00:50:51 +00002650 case Instruction::SetGT:
2651 std::swap(Op0, Op1); // Change setgt -> setlt
2652 // FALL THROUGH
2653 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2654 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2655 InsertNewInstBefore(Not, I);
2656 return BinaryOperator::createAnd(Not, Op1);
2657 }
2658 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002659 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002660 // FALL THROUGH
2661 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2662 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2663 InsertNewInstBefore(Not, I);
2664 return BinaryOperator::createOr(Not, Op1);
2665 }
2666 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002667 }
2668
Chris Lattner2dd01742004-06-09 04:24:29 +00002669 // See if we are doing a comparison between a constant and an instruction that
2670 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002671 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002672 // Check to see if we are comparing against the minimum or maximum value...
2673 if (CI->isMinValue()) {
2674 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2675 return ReplaceInstUsesWith(I, ConstantBool::False);
2676 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2677 return ReplaceInstUsesWith(I, ConstantBool::True);
2678 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2679 return BinaryOperator::createSetEQ(Op0, Op1);
2680 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2681 return BinaryOperator::createSetNE(Op0, Op1);
2682
2683 } else if (CI->isMaxValue()) {
2684 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2685 return ReplaceInstUsesWith(I, ConstantBool::False);
2686 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2687 return ReplaceInstUsesWith(I, ConstantBool::True);
2688 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2689 return BinaryOperator::createSetEQ(Op0, Op1);
2690 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2691 return BinaryOperator::createSetNE(Op0, Op1);
2692
2693 // Comparing against a value really close to min or max?
2694 } else if (isMinValuePlusOne(CI)) {
2695 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2696 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2697 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2698 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2699
2700 } else if (isMaxValueMinusOne(CI)) {
2701 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2702 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2703 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2704 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2705 }
2706
2707 // If we still have a setle or setge instruction, turn it into the
2708 // appropriate setlt or setgt instruction. Since the border cases have
2709 // already been handled above, this requires little checking.
2710 //
2711 if (I.getOpcode() == Instruction::SetLE)
2712 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2713 if (I.getOpcode() == Instruction::SetGE)
2714 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2715
Chris Lattnere1e10e12004-05-25 06:32:08 +00002716 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002717 switch (LHSI->getOpcode()) {
2718 case Instruction::And:
2719 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2720 LHSI->getOperand(0)->hasOneUse()) {
2721 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2722 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2723 // happens a LOT in code produced by the C front-end, for bitfield
2724 // access.
2725 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2726 ConstantUInt *ShAmt;
2727 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2728 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2729 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002730
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002731 // We can fold this as long as we can't shift unknown bits
2732 // into the mask. This can only happen with signed shift
2733 // rights, as they sign-extend.
2734 if (ShAmt) {
2735 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002736 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002737 if (!CanFold) {
2738 // To test for the bad case of the signed shr, see if any
2739 // of the bits shifted in could be tested after the mask.
Chris Lattnerc53cb9d2005-06-17 01:29:28 +00002740 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2741 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2742
2743 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002744 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002745 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2746 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2747 CanFold = true;
2748 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002749
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002750 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002751 Constant *NewCst;
2752 if (Shift->getOpcode() == Instruction::Shl)
2753 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2754 else
2755 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002756
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002757 // Check to see if we are shifting out any of the bits being
2758 // compared.
2759 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2760 // If we shifted bits out, the fold is not going to work out.
2761 // As a special case, check to see if this means that the
2762 // result is always true or false now.
2763 if (I.getOpcode() == Instruction::SetEQ)
2764 return ReplaceInstUsesWith(I, ConstantBool::False);
2765 if (I.getOpcode() == Instruction::SetNE)
2766 return ReplaceInstUsesWith(I, ConstantBool::True);
2767 } else {
2768 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002769 Constant *NewAndCST;
2770 if (Shift->getOpcode() == Instruction::Shl)
2771 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2772 else
2773 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2774 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002775 LHSI->setOperand(0, Shift->getOperand(0));
2776 WorkList.push_back(Shift); // Shift is dead.
2777 AddUsesToWorkList(I);
2778 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002779 }
2780 }
Chris Lattner35167c32004-06-09 07:59:58 +00002781 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002782 }
2783 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002784
Chris Lattner272d5ca2004-09-28 18:22:15 +00002785 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2786 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2787 switch (I.getOpcode()) {
2788 default: break;
2789 case Instruction::SetEQ:
2790 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002791 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2792
2793 // Check that the shift amount is in range. If not, don't perform
2794 // undefined shifts. When the shift is visited it will be
2795 // simplified.
2796 if (ShAmt->getValue() >= TypeBits)
2797 break;
2798
Chris Lattner272d5ca2004-09-28 18:22:15 +00002799 // If we are comparing against bits always shifted out, the
2800 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002801 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002802 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2803 if (Comp != CI) {// Comparing against a bit that we know is zero.
2804 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2805 Constant *Cst = ConstantBool::get(IsSetNE);
2806 return ReplaceInstUsesWith(I, Cst);
2807 }
2808
2809 if (LHSI->hasOneUse()) {
2810 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002811 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002812 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2813
2814 Constant *Mask;
2815 if (CI->getType()->isUnsigned()) {
2816 Mask = ConstantUInt::get(CI->getType(), Val);
2817 } else if (ShAmtVal != 0) {
2818 Mask = ConstantSInt::get(CI->getType(), Val);
2819 } else {
2820 Mask = ConstantInt::getAllOnesValue(CI->getType());
2821 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002822
Chris Lattner272d5ca2004-09-28 18:22:15 +00002823 Instruction *AndI =
2824 BinaryOperator::createAnd(LHSI->getOperand(0),
2825 Mask, LHSI->getName()+".mask");
2826 Value *And = InsertNewInstBefore(AndI, I);
2827 return new SetCondInst(I.getOpcode(), And,
2828 ConstantExpr::getUShr(CI, ShAmt));
2829 }
2830 }
2831 }
2832 }
2833 break;
2834
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002835 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002836 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002837 switch (I.getOpcode()) {
2838 default: break;
2839 case Instruction::SetEQ:
2840 case Instruction::SetNE: {
Chris Lattner19b57f52005-06-15 20:53:31 +00002841
2842 // Check that the shift amount is in range. If not, don't perform
2843 // undefined shifts. When the shift is visited it will be
2844 // simplified.
Chris Lattner104002b2005-06-16 01:52:07 +00002845 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner19b57f52005-06-15 20:53:31 +00002846 if (ShAmt->getValue() >= TypeBits)
2847 break;
2848
Chris Lattner1023b872004-09-27 16:18:50 +00002849 // If we are comparing against bits always shifted out, the
2850 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002851 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002852 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002853
Chris Lattner1023b872004-09-27 16:18:50 +00002854 if (Comp != CI) {// Comparing against a bit that we know is zero.
2855 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2856 Constant *Cst = ConstantBool::get(IsSetNE);
2857 return ReplaceInstUsesWith(I, Cst);
2858 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002859
Chris Lattner1023b872004-09-27 16:18:50 +00002860 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002861 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002862
Chris Lattner1023b872004-09-27 16:18:50 +00002863 // Otherwise strength reduce the shift into an and.
2864 uint64_t Val = ~0ULL; // All ones.
2865 Val <<= ShAmtVal; // Shift over to the right spot.
2866
2867 Constant *Mask;
2868 if (CI->getType()->isUnsigned()) {
Chris Lattner2f1457f2005-04-24 17:46:05 +00002869 Val &= ~0ULL >> (64-TypeBits);
Chris Lattner1023b872004-09-27 16:18:50 +00002870 Mask = ConstantUInt::get(CI->getType(), Val);
2871 } else {
2872 Mask = ConstantSInt::get(CI->getType(), Val);
2873 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002874
Chris Lattner1023b872004-09-27 16:18:50 +00002875 Instruction *AndI =
2876 BinaryOperator::createAnd(LHSI->getOperand(0),
2877 Mask, LHSI->getName()+".mask");
2878 Value *And = InsertNewInstBefore(AndI, I);
2879 return new SetCondInst(I.getOpcode(), And,
2880 ConstantExpr::getShl(CI, ShAmt));
2881 }
2882 break;
2883 }
2884 }
2885 }
2886 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002887
Chris Lattner6862fbd2004-09-29 17:40:11 +00002888 case Instruction::Div:
2889 // Fold: (div X, C1) op C2 -> range check
2890 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2891 // Fold this div into the comparison, producing a range check.
2892 // Determine, based on the divide type, what the range is being
2893 // checked. If there is an overflow on the low or high side, remember
2894 // it, otherwise compute the range [low, hi) bounding the new value.
2895 bool LoOverflow = false, HiOverflow = 0;
2896 ConstantInt *LoBound = 0, *HiBound = 0;
2897
2898 ConstantInt *Prod;
2899 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2900
Chris Lattnera92af962004-10-11 19:40:04 +00002901 Instruction::BinaryOps Opcode = I.getOpcode();
2902
Chris Lattner6862fbd2004-09-29 17:40:11 +00002903 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2904 } else if (LHSI->getType()->isUnsigned()) { // udiv
2905 LoBound = Prod;
2906 LoOverflow = ProdOV;
2907 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2908 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2909 if (CI->isNullValue()) { // (X / pos) op 0
2910 // Can't overflow.
2911 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2912 HiBound = DivRHS;
2913 } else if (isPositive(CI)) { // (X / pos) op pos
2914 LoBound = Prod;
2915 LoOverflow = ProdOV;
2916 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2917 } else { // (X / pos) op neg
2918 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2919 LoOverflow = AddWithOverflow(LoBound, Prod,
2920 cast<ConstantInt>(DivRHSH));
2921 HiBound = Prod;
2922 HiOverflow = ProdOV;
2923 }
2924 } else { // Divisor is < 0.
2925 if (CI->isNullValue()) { // (X / neg) op 0
2926 LoBound = AddOne(DivRHS);
2927 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner73bcba52005-06-17 02:05:55 +00002928 if (HiBound == DivRHS)
2929 LoBound = 0; // - INTMIN = INTMIN
Chris Lattner6862fbd2004-09-29 17:40:11 +00002930 } else if (isPositive(CI)) { // (X / neg) op pos
2931 HiOverflow = LoOverflow = ProdOV;
2932 if (!LoOverflow)
2933 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2934 HiBound = AddOne(Prod);
2935 } else { // (X / neg) op neg
2936 LoBound = Prod;
2937 LoOverflow = HiOverflow = ProdOV;
2938 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2939 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002940
Chris Lattnera92af962004-10-11 19:40:04 +00002941 // Dividing by a negate swaps the condition.
2942 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002943 }
2944
2945 if (LoBound) {
2946 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002947 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002948 default: assert(0 && "Unhandled setcc opcode!");
2949 case Instruction::SetEQ:
2950 if (LoOverflow && HiOverflow)
2951 return ReplaceInstUsesWith(I, ConstantBool::False);
2952 else if (HiOverflow)
2953 return new SetCondInst(Instruction::SetGE, X, LoBound);
2954 else if (LoOverflow)
2955 return new SetCondInst(Instruction::SetLT, X, HiBound);
2956 else
2957 return InsertRangeTest(X, LoBound, HiBound, true, I);
2958 case Instruction::SetNE:
2959 if (LoOverflow && HiOverflow)
2960 return ReplaceInstUsesWith(I, ConstantBool::True);
2961 else if (HiOverflow)
2962 return new SetCondInst(Instruction::SetLT, X, LoBound);
2963 else if (LoOverflow)
2964 return new SetCondInst(Instruction::SetGE, X, HiBound);
2965 else
2966 return InsertRangeTest(X, LoBound, HiBound, false, I);
2967 case Instruction::SetLT:
2968 if (LoOverflow)
2969 return ReplaceInstUsesWith(I, ConstantBool::False);
2970 return new SetCondInst(Instruction::SetLT, X, LoBound);
2971 case Instruction::SetGT:
2972 if (HiOverflow)
2973 return ReplaceInstUsesWith(I, ConstantBool::False);
2974 return new SetCondInst(Instruction::SetGE, X, HiBound);
2975 }
2976 }
2977 }
2978 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002979 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002980
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002981 // Simplify seteq and setne instructions...
2982 if (I.getOpcode() == Instruction::SetEQ ||
2983 I.getOpcode() == Instruction::SetNE) {
2984 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2985
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002986 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002987 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002988 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2989 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002990 case Instruction::Rem:
2991 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2992 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2993 BO->hasOneUse() &&
Chris Lattner22d00a82005-08-02 19:16:58 +00002994 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
2995 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
2996 if (isPowerOf2_64(V)) {
2997 unsigned L2 = Log2_64(V);
Chris Lattner23b47b62004-07-06 07:38:18 +00002998 const Type *UTy = BO->getType()->getUnsignedVersion();
2999 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3000 UTy, "tmp"), I);
3001 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3002 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3003 RHSCst, BO->getName()), I);
3004 return BinaryOperator::create(I.getOpcode(), NewRem,
3005 Constant::getNullValue(UTy));
3006 }
Chris Lattner22d00a82005-08-02 19:16:58 +00003007 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003008 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00003009
Chris Lattnerc992add2003-08-13 05:33:12 +00003010 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00003011 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3012 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00003013 if (BO->hasOneUse())
3014 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3015 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00003016 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003017 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3018 // efficiently invertible, or if the add has just this one use.
3019 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003020
Chris Lattnerc992add2003-08-13 05:33:12 +00003021 if (Value *NegVal = dyn_castNegVal(BOp1))
3022 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3023 else if (Value *NegVal = dyn_castNegVal(BOp0))
3024 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003025 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00003026 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3027 BO->setName("");
3028 InsertNewInstBefore(Neg, I);
3029 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3030 }
3031 }
3032 break;
3033 case Instruction::Xor:
3034 // For the xor case, we can xor two constants together, eliminating
3035 // the explicit xor.
3036 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3037 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003038 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00003039
3040 // FALLTHROUGH
3041 case Instruction::Sub:
3042 // Replace (([sub|xor] A, B) != 0) with (A != B)
3043 if (CI->isNullValue())
3044 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3045 BO->getOperand(1));
3046 break;
3047
3048 case Instruction::Or:
3049 // If bits are being or'd in that are not present in the constant we
3050 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003051 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003052 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003053 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003054 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003055 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003056 break;
3057
3058 case Instruction::And:
3059 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003060 // If bits are being compared against that are and'd out, then the
3061 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00003062 if (!ConstantExpr::getAnd(CI,
3063 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003064 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00003065
Chris Lattner35167c32004-06-09 07:59:58 +00003066 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00003067 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00003068 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3069 Instruction::SetNE, Op0,
3070 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00003071
Chris Lattnerc992add2003-08-13 05:33:12 +00003072 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3073 // to be a signed value as appropriate.
3074 if (isSignBit(BOC)) {
3075 Value *X = BO->getOperand(0);
3076 // If 'X' is not signed, insert a cast now...
3077 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00003078 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003079 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00003080 }
3081 return new SetCondInst(isSetNE ? Instruction::SetLT :
3082 Instruction::SetGE, X,
3083 Constant::getNullValue(X->getType()));
3084 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003085
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003086 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00003087 if (CI->isNullValue() && isHighOnes(BOC)) {
3088 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003089 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003090
3091 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003092 if (NegX->getType()->isSigned()) {
3093 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3094 X = InsertCastBefore(X, DestTy, I);
3095 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003096 }
3097
3098 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00003099 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00003100 }
3101
Chris Lattnerd492a0b2003-07-23 17:02:11 +00003102 }
Chris Lattnerc992add2003-08-13 05:33:12 +00003103 default: break;
3104 }
3105 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00003106 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00003107 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00003108 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3109 Value *CastOp = Cast->getOperand(0);
3110 const Type *SrcTy = CastOp->getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003111 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattner2b55ea32004-02-23 07:16:20 +00003112 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003113 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003114 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00003115 "Source and destination signednesses should differ!");
3116 if (Cast->getType()->isSigned()) {
3117 // If this is a signed comparison, check for comparisons in the
3118 // vicinity of zero.
3119 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3120 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003121 return BinaryOperator::createSetGT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003122 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003123 else if (I.getOpcode() == Instruction::SetGT &&
3124 cast<ConstantSInt>(CI)->getValue() == -1)
3125 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003126 return BinaryOperator::createSetLT(CastOp,
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003127 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003128 } else {
3129 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3130 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003131 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattner2b55ea32004-02-23 07:16:20 +00003132 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003133 return BinaryOperator::createSetGT(CastOp,
3134 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003135 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003136 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattner2b55ea32004-02-23 07:16:20 +00003137 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003138 return BinaryOperator::createSetLT(CastOp,
3139 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00003140 }
3141 }
3142 }
Chris Lattnere967b342003-06-04 05:10:11 +00003143 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003144 }
3145
Chris Lattner77c32c32005-04-23 15:31:55 +00003146 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3147 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3148 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3149 switch (LHSI->getOpcode()) {
Chris Lattnera816eee2005-05-01 04:42:15 +00003150 case Instruction::GetElementPtr:
3151 if (RHSC->isNullValue()) {
3152 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3153 bool isAllZeros = true;
3154 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3155 if (!isa<Constant>(LHSI->getOperand(i)) ||
3156 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3157 isAllZeros = false;
3158 break;
3159 }
3160 if (isAllZeros)
3161 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3162 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3163 }
3164 break;
3165
Chris Lattner77c32c32005-04-23 15:31:55 +00003166 case Instruction::PHI:
3167 if (Instruction *NV = FoldOpIntoPhi(I))
3168 return NV;
3169 break;
3170 case Instruction::Select:
3171 // If either operand of the select is a constant, we can fold the
3172 // comparison into the select arms, which will cause one to be
3173 // constant folded and the select turned into a bitwise or.
3174 Value *Op1 = 0, *Op2 = 0;
3175 if (LHSI->hasOneUse()) {
3176 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3177 // Fold the known value into the constant operand.
3178 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3179 // Insert a new SetCC of the other select operand.
3180 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3181 LHSI->getOperand(2), RHSC,
3182 I.getName()), I);
3183 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3184 // Fold the known value into the constant operand.
3185 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3186 // Insert a new SetCC of the other select operand.
3187 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3188 LHSI->getOperand(1), RHSC,
3189 I.getName()), I);
3190 }
3191 }
Jeff Cohen82639852005-04-23 21:38:35 +00003192
Chris Lattner77c32c32005-04-23 15:31:55 +00003193 if (Op1)
3194 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3195 break;
3196 }
3197 }
3198
Chris Lattner0798af32005-01-13 20:14:25 +00003199 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3200 if (User *GEP = dyn_castGetElementPtr(Op0))
3201 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3202 return NI;
3203 if (User *GEP = dyn_castGetElementPtr(Op1))
3204 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3205 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3206 return NI;
3207
Chris Lattner16930792003-11-03 04:25:02 +00003208 // Test to see if the operands of the setcc are casted versions of other
3209 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00003210 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3211 Value *CastOp0 = CI->getOperand(0);
3212 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00003213 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00003214 (I.getOpcode() == Instruction::SetEQ ||
3215 I.getOpcode() == Instruction::SetNE)) {
3216 // We keep moving the cast from the left operand over to the right
3217 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00003218 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003219
Chris Lattner16930792003-11-03 04:25:02 +00003220 // If operand #1 is a cast instruction, see if we can eliminate it as
3221 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00003222 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3223 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00003224 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00003225 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003226
Chris Lattner16930792003-11-03 04:25:02 +00003227 // If Op1 is a constant, we can fold the cast into the constant.
3228 if (Op1->getType() != Op0->getType())
3229 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3230 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3231 } else {
3232 // Otherwise, cast the RHS right before the setcc
3233 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3234 InsertNewInstBefore(cast<Instruction>(Op1), I);
3235 }
3236 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3237 }
3238
Chris Lattner6444c372003-11-03 05:17:03 +00003239 // Handle the special case of: setcc (cast bool to X), <cst>
3240 // This comes up when you have code like
3241 // int X = A < B;
3242 // if (X) ...
3243 // For generality, we handle any zero-extension of any operand comparison
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003244 // with a constant or another cast from the same type.
3245 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3246 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3247 return R;
Chris Lattner6444c372003-11-03 05:17:03 +00003248 }
Chris Lattner113f4f42002-06-25 16:13:24 +00003249 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003250}
3251
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003252// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3253// We only handle extending casts so far.
3254//
3255Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3256 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3257 const Type *SrcTy = LHSCIOp->getType();
3258 const Type *DestTy = SCI.getOperand(0)->getType();
3259 Value *RHSCIOp;
3260
3261 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattner03f06f12005-01-17 03:20:02 +00003262 return 0;
3263
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003264 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3265 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3266 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3267
3268 // Is this a sign or zero extension?
3269 bool isSignSrc = SrcTy->isSigned();
3270 bool isSignDest = DestTy->isSigned();
3271
3272 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3273 // Not an extension from the same type?
3274 RHSCIOp = CI->getOperand(0);
3275 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3276 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3277 // Compute the constant that would happen if we truncated to SrcTy then
3278 // reextended to DestTy.
3279 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3280
3281 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3282 RHSCIOp = Res;
3283 } else {
3284 // If the value cannot be represented in the shorter type, we cannot emit
3285 // a simple comparison.
3286 if (SCI.getOpcode() == Instruction::SetEQ)
3287 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3288 if (SCI.getOpcode() == Instruction::SetNE)
3289 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3290
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003291 // Evaluate the comparison for LT.
3292 Value *Result;
3293 if (DestTy->isSigned()) {
3294 // We're performing a signed comparison.
3295 if (isSignSrc) {
3296 // Signed extend and signed comparison.
3297 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3298 Result = ConstantBool::False;
3299 else
3300 Result = ConstantBool::True; // X < (large) --> true
3301 } else {
3302 // Unsigned extend and signed comparison.
3303 if (cast<ConstantSInt>(CI)->getValue() < 0)
3304 Result = ConstantBool::False;
3305 else
3306 Result = ConstantBool::True;
3307 }
3308 } else {
3309 // We're performing an unsigned comparison.
3310 if (!isSignSrc) {
3311 // Unsigned extend & compare -> always true.
3312 Result = ConstantBool::True;
3313 } else {
3314 // We're performing an unsigned comp with a sign extended value.
3315 // This is true if the input is >= 0. [aka >s -1]
3316 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3317 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3318 NegOne, SCI.getName()), SCI);
3319 }
Reid Spencer279fa252004-11-28 21:31:15 +00003320 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003321
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003322 // Finally, return the value computed.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003323 if (SCI.getOpcode() == Instruction::SetLT) {
3324 return ReplaceInstUsesWith(SCI, Result);
3325 } else {
3326 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3327 if (Constant *CI = dyn_cast<Constant>(Result))
3328 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3329 else
3330 return BinaryOperator::createNot(Result);
3331 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003332 }
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003333 } else {
3334 return 0;
Reid Spencer279fa252004-11-28 21:31:15 +00003335 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003336
Chris Lattner252a8452005-06-16 03:00:08 +00003337 // Okay, just insert a compare of the reduced operands now!
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003338 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3339}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003340
Chris Lattnere8d6c602003-03-10 19:16:08 +00003341Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003342 assert(I.getOperand(1)->getType() == Type::UByteTy);
3343 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003344 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003345
3346 // shl X, 0 == X and shr X, 0 == X
3347 // shl 0, X == 0 and shr 0, X == 0
3348 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003349 Op0 == Constant::getNullValue(Op0->getType()))
3350 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003351
Chris Lattner81a7a232004-10-16 18:11:37 +00003352 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3353 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003354 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003355 else // undef << X -> 0 AND undef >>u X -> 0
3356 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3357 }
3358 if (isa<UndefValue>(Op1)) {
Chris Lattner18aa4d82005-07-20 18:49:28 +00003359 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00003360 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3361 else
3362 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3363 }
3364
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003365 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3366 if (!isLeftShift)
3367 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3368 if (CSI->isAllOnesValue())
3369 return ReplaceInstUsesWith(I, CSI);
3370
Chris Lattner183b3362004-04-09 19:05:30 +00003371 // Try to fold constant and into select arguments.
3372 if (isa<Constant>(Op0))
3373 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003374 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003375 return R;
3376
Chris Lattnerb18dbbf2005-05-08 17:34:56 +00003377 // See if we can turn a signed shr into an unsigned shr.
3378 if (!isLeftShift && I.getType()->isSigned()) {
3379 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3380 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3381 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3382 I.getName()), I);
3383 return new CastInst(V, I.getType());
3384 }
3385 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003386
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003387 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003388 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3389 // of a signed value.
3390 //
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003391 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003392 if (CUI->getValue() >= TypeBits) {
3393 if (!Op0->getType()->isSigned() || isLeftShift)
3394 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3395 else {
3396 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3397 return &I;
3398 }
3399 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003400
Chris Lattnerede3fe02003-08-13 04:18:28 +00003401 // ((X*C1) << C2) == (X * (C1 << C2))
3402 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3403 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3404 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003405 return BinaryOperator::createMul(BO->getOperand(0),
3406 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanb1c93172005-04-21 23:48:37 +00003407
Chris Lattner183b3362004-04-09 19:05:30 +00003408 // Try to fold constant and into select arguments.
3409 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003410 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003411 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003412 if (isa<PHINode>(Op0))
3413 if (Instruction *NV = FoldOpIntoPhi(I))
3414 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003415
Chris Lattner86102b82005-01-01 16:22:27 +00003416 if (Op0->hasOneUse()) {
3417 // If this is a SHL of a sign-extending cast, see if we can turn the input
3418 // into a zero extending cast (a simple strength reduction).
3419 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3420 const Type *SrcTy = CI->getOperand(0)->getType();
3421 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003422 SrcTy->getPrimitiveSizeInBits() <
3423 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner86102b82005-01-01 16:22:27 +00003424 // We can change it to a zero extension if we are shifting out all of
3425 // the sign extended bits. To check this, form a mask of all of the
3426 // sign extend bits, then shift them left and see if we have anything
3427 // left.
3428 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3429 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3430 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3431 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3432 // If the shift is nuking all of the sign bits, change this to a
3433 // zero extension cast. To do this, cast the cast input to
3434 // unsigned, then to the requested size.
3435 Value *CastOp = CI->getOperand(0);
3436 Instruction *NC =
3437 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3438 CI->getName()+".uns");
3439 NC = InsertNewInstBefore(NC, I);
3440 // Finally, insert a replacement for CI.
3441 NC = new CastInst(NC, CI->getType(), CI->getName());
3442 CI->setName("");
3443 NC = InsertNewInstBefore(NC, I);
3444 WorkList.push_back(CI); // Delete CI later.
3445 I.setOperand(0, NC);
3446 return &I; // The SHL operand was modified.
3447 }
3448 }
3449 }
3450
Chris Lattner27cb9db2005-09-18 05:12:10 +00003451 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3452 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Jeff Cohen572910c2005-10-07 05:28:29 +00003453 Value *V1, *V2;
Chris Lattner797dee72005-09-18 06:30:59 +00003454 ConstantInt *CC;
Chris Lattner27cb9db2005-09-18 05:12:10 +00003455 switch (Op0BO->getOpcode()) {
3456 default: break;
3457 case Instruction::Add:
3458 case Instruction::And:
3459 case Instruction::Or:
3460 case Instruction::Xor:
3461 // These operators commute.
3462 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003463 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3464 match(Op0BO->getOperand(1),
3465 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3466 Instruction *YS = new ShiftInst(Instruction::Shl,
3467 Op0BO->getOperand(0), CUI,
3468 Op0BO->getName());
3469 InsertNewInstBefore(YS, I); // (Y << C)
3470 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3471 V1,
3472 Op0BO->getOperand(1)->getName());
3473 InsertNewInstBefore(X, I); // (X + (Y << C))
3474 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3475 C2 = ConstantExpr::getShl(C2, CUI);
3476 return BinaryOperator::createAnd(X, C2);
3477 }
3478
3479 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3480 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3481 match(Op0BO->getOperand(1),
3482 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3483 m_ConstantInt(CC))) && V2 == CUI &&
3484 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3485 Instruction *YS = new ShiftInst(Instruction::Shl,
3486 Op0BO->getOperand(0), CUI,
3487 Op0BO->getName());
3488 InsertNewInstBefore(YS, I); // (Y << C)
3489 Instruction *XM =
3490 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3491 V1->getName()+".mask");
3492 InsertNewInstBefore(XM, I); // X & (CC << C)
3493
3494 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3495 }
3496
3497 // FALL THROUGH.
Chris Lattner27cb9db2005-09-18 05:12:10 +00003498 case Instruction::Sub:
3499 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner797dee72005-09-18 06:30:59 +00003500 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3501 match(Op0BO->getOperand(0),
3502 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3503 Instruction *YS = new ShiftInst(Instruction::Shl,
3504 Op0BO->getOperand(1), CUI,
3505 Op0BO->getName());
3506 InsertNewInstBefore(YS, I); // (Y << C)
3507 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3508 V1,
3509 Op0BO->getOperand(0)->getName());
3510 InsertNewInstBefore(X, I); // (X + (Y << C))
3511 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3512 C2 = ConstantExpr::getShl(C2, CUI);
3513 return BinaryOperator::createAnd(X, C2);
3514 }
3515
3516 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3517 match(Op0BO->getOperand(0),
3518 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3519 m_ConstantInt(CC))) && V2 == CUI &&
3520 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3521 Instruction *YS = new ShiftInst(Instruction::Shl,
3522 Op0BO->getOperand(1), CUI,
3523 Op0BO->getName());
3524 InsertNewInstBefore(YS, I); // (Y << C)
3525 Instruction *XM =
3526 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3527 V1->getName()+".mask");
3528 InsertNewInstBefore(XM, I); // X & (CC << C)
3529
3530 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3531 }
3532
Chris Lattner27cb9db2005-09-18 05:12:10 +00003533 break;
3534 }
3535
3536
3537 // If the operand is an bitwise operator with a constant RHS, and the
3538 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003539 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3540 bool isValid = true; // Valid only for And, Or, Xor
3541 bool highBitSet = false; // Transform if high bit of constant set?
3542
3543 switch (Op0BO->getOpcode()) {
3544 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003545 case Instruction::Add:
3546 isValid = isLeftShift;
3547 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003548 case Instruction::Or:
3549 case Instruction::Xor:
3550 highBitSet = false;
3551 break;
3552 case Instruction::And:
3553 highBitSet = true;
3554 break;
3555 }
3556
3557 // If this is a signed shift right, and the high bit is modified
3558 // by the logical operation, do not perform the transformation.
3559 // The highBitSet boolean indicates the value of the high bit of
3560 // the constant which would cause it to be modified for this
3561 // operation.
3562 //
3563 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3564 uint64_t Val = Op0C->getRawValue();
3565 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3566 }
3567
3568 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003569 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003570
3571 Instruction *NewShift =
3572 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3573 Op0BO->getName());
3574 Op0BO->setName("");
3575 InsertNewInstBefore(NewShift, I);
3576
3577 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3578 NewRHS);
3579 }
3580 }
Chris Lattner27cb9db2005-09-18 05:12:10 +00003581 }
Chris Lattner86102b82005-01-01 16:22:27 +00003582 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003583
Chris Lattner3204d4e2003-07-24 17:52:58 +00003584 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003585 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003586 if (ConstantUInt *ShiftAmt1C =
3587 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003588 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3589 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003590
Chris Lattner3204d4e2003-07-24 17:52:58 +00003591 // Check for (A << c1) << c2 and (A >> c1) >> c2
3592 if (I.getOpcode() == Op0SI->getOpcode()) {
3593 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003594 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3595 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003596 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3597 ConstantUInt::get(Type::UByteTy, Amt));
3598 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003599
Chris Lattnerab780df2003-07-24 18:38:56 +00003600 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3601 // signed types, we can only support the (A >> c1) << c2 configuration,
3602 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003603 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003604 // Calculate bitmask for what gets shifted off the edge...
3605 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003606 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003607 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003608 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003609 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003610
Chris Lattner3204d4e2003-07-24 17:52:58 +00003611 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003612 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3613 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003614 InsertNewInstBefore(Mask, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003615
Chris Lattner3204d4e2003-07-24 17:52:58 +00003616 // Figure out what flavor of shift we should use...
3617 if (ShiftAmt1 == ShiftAmt2)
3618 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3619 else if (ShiftAmt1 < ShiftAmt2) {
3620 return new ShiftInst(I.getOpcode(), Mask,
3621 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3622 } else {
3623 return new ShiftInst(Op0SI->getOpcode(), Mask,
3624 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3625 }
Chris Lattner0b3557f2005-09-24 23:43:33 +00003626 } else {
3627 // We can handle signed (X << C1) >> C2 if it's a sign extend. In
3628 // this case, C1 == C2 and C1 is 8, 16, or 32.
3629 if (ShiftAmt1 == ShiftAmt2) {
3630 const Type *SExtType = 0;
3631 switch (ShiftAmt1) {
3632 case 8 : SExtType = Type::SByteTy; break;
3633 case 16: SExtType = Type::ShortTy; break;
3634 case 32: SExtType = Type::IntTy; break;
3635 }
3636
3637 if (SExtType) {
3638 Instruction *NewTrunc = new CastInst(Op0SI->getOperand(0),
3639 SExtType, "sext");
3640 InsertNewInstBefore(NewTrunc, I);
3641 return new CastInst(NewTrunc, I.getType());
3642 }
3643 }
Chris Lattner3204d4e2003-07-24 17:52:58 +00003644 }
3645 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003646 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003647
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003648 return 0;
3649}
3650
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003651enum CastType {
3652 Noop = 0,
3653 Truncate = 1,
3654 Signext = 2,
3655 Zeroext = 3
3656};
3657
3658/// getCastType - In the future, we will split the cast instruction into these
3659/// various types. Until then, we have to do the analysis here.
3660static CastType getCastType(const Type *Src, const Type *Dest) {
3661 assert(Src->isIntegral() && Dest->isIntegral() &&
3662 "Only works on integral types!");
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003663 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3664 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003665
3666 if (SrcSize == DestSize) return Noop;
3667 if (SrcSize > DestSize) return Truncate;
3668 if (Src->isSigned()) return Signext;
3669 return Zeroext;
3670}
3671
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003672
Chris Lattner48a44f72002-05-02 17:06:02 +00003673// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3674// instruction.
3675//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003676static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003677 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003678
Chris Lattner650b6da2002-08-02 20:00:25 +00003679 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003680 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003681 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003682 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003683 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003684
Chris Lattner4fbad962004-07-21 04:27:24 +00003685 // If we are casting between pointer and integer types, treat pointers as
3686 // integers of the appropriate size for the code below.
3687 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3688 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3689 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003690
Chris Lattner48a44f72002-05-02 17:06:02 +00003691 // Allow free casting and conversion of sizes as long as the sign doesn't
3692 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003693 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003694 CastType FirstCast = getCastType(SrcTy, MidTy);
3695 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003696
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003697 // Capture the effect of these two casts. If the result is a legal cast,
3698 // the CastType is stored here, otherwise a special code is used.
3699 static const unsigned CastResult[] = {
3700 // First cast is noop
3701 0, 1, 2, 3,
3702 // First cast is a truncate
3703 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3704 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003705 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003706 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003707 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003708 };
3709
3710 unsigned Result = CastResult[FirstCast*4+SecondCast];
3711 switch (Result) {
3712 default: assert(0 && "Illegal table value!");
3713 case 0:
3714 case 1:
3715 case 2:
3716 case 3:
3717 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3718 // truncates, we could eliminate more casts.
3719 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3720 case 4:
3721 return false; // Not possible to eliminate this here.
3722 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003723 // Sign or zero extend followed by truncate is always ok if the result
3724 // is a truncate or noop.
3725 CastType ResultCast = getCastType(SrcTy, DstTy);
3726 if (ResultCast == Noop || ResultCast == Truncate)
3727 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003728 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003729 // result will match the sign/zeroextendness of the result.
3730 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003731 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003732 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003733 return false;
3734}
3735
Chris Lattner11ffd592004-07-20 05:21:00 +00003736static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003737 if (V->getType() == Ty || isa<Constant>(V)) return false;
3738 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003739 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3740 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003741 return false;
3742 return true;
3743}
3744
3745/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3746/// InsertBefore instruction. This is specialized a bit to avoid inserting
3747/// casts that are known to not do anything...
3748///
3749Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3750 Instruction *InsertBefore) {
3751 if (V->getType() == DestTy) return V;
3752 if (Constant *C = dyn_cast<Constant>(V))
3753 return ConstantExpr::getCast(C, DestTy);
3754
3755 CastInst *CI = new CastInst(V, DestTy, V->getName());
3756 InsertNewInstBefore(CI, *InsertBefore);
3757 return CI;
3758}
Chris Lattner48a44f72002-05-02 17:06:02 +00003759
3760// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003761//
Chris Lattner113f4f42002-06-25 16:13:24 +00003762Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003763 Value *Src = CI.getOperand(0);
3764
Chris Lattner48a44f72002-05-02 17:06:02 +00003765 // If the user is casting a value to the same type, eliminate this cast
3766 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003767 if (CI.getType() == Src->getType())
3768 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003769
Chris Lattner81a7a232004-10-16 18:11:37 +00003770 if (isa<UndefValue>(Src)) // cast undef -> undef
3771 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3772
Chris Lattner48a44f72002-05-02 17:06:02 +00003773 // If casting the result of another cast instruction, try to eliminate this
3774 // one!
3775 //
Chris Lattner86102b82005-01-01 16:22:27 +00003776 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3777 Value *A = CSrc->getOperand(0);
3778 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3779 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003780 // This instruction now refers directly to the cast's src operand. This
3781 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003782 CI.setOperand(0, CSrc->getOperand(0));
3783 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003784 }
3785
Chris Lattner650b6da2002-08-02 20:00:25 +00003786 // If this is an A->B->A cast, and we are dealing with integral types, try
3787 // to convert this into a logical 'and' instruction.
3788 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003789 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003790 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003791 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003792 CSrc->getType()->getPrimitiveSizeInBits() <
3793 CI.getType()->getPrimitiveSizeInBits()&&
3794 A->getType()->getPrimitiveSizeInBits() ==
3795 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003796 assert(CSrc->getType() != Type::ULongTy &&
3797 "Cannot have type bigger than ulong!");
Chris Lattner2f1457f2005-04-24 17:46:05 +00003798 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner86102b82005-01-01 16:22:27 +00003799 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3800 AndValue);
3801 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3802 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3803 if (And->getType() != CI.getType()) {
3804 And->setName(CSrc->getName()+".mask");
3805 InsertNewInstBefore(And, CI);
3806 And = new CastInst(And, CI.getType());
3807 }
3808 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003809 }
3810 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003811
Chris Lattner03841652004-05-25 04:29:21 +00003812 // If this is a cast to bool, turn it into the appropriate setne instruction.
3813 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003814 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003815 Constant::getNullValue(CI.getOperand(0)->getType()));
3816
Chris Lattnerd0d51602003-06-21 23:12:02 +00003817 // If casting the result of a getelementptr instruction with no offset, turn
3818 // this into a cast of the original pointer!
3819 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003820 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003821 bool AllZeroOperands = true;
3822 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3823 if (!isa<Constant>(GEP->getOperand(i)) ||
3824 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3825 AllZeroOperands = false;
3826 break;
3827 }
3828 if (AllZeroOperands) {
3829 CI.setOperand(0, GEP->getOperand(0));
3830 return &CI;
3831 }
3832 }
3833
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003834 // If we are casting a malloc or alloca to a pointer to a type of the same
3835 // size, rewrite the allocation instruction to allocate the "right" type.
3836 //
3837 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003838 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003839 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3840 // Get the type really allocated and the type casted to...
3841 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003842 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003843 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003844 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3845 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003846
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003847 // If the allocation is for an even multiple of the cast type size
3848 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003849 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003850 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003851 std::string Name = AI->getName(); AI->setName("");
3852 AllocationInst *New;
3853 if (isa<MallocInst>(AI))
3854 New = new MallocInst(CastElTy, Amt, Name);
3855 else
3856 New = new AllocaInst(CastElTy, Amt, Name);
3857 InsertNewInstBefore(New, *AI);
3858 return ReplaceInstUsesWith(CI, New);
3859 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003860 }
3861 }
3862
Chris Lattner86102b82005-01-01 16:22:27 +00003863 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3864 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3865 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003866 if (isa<PHINode>(Src))
3867 if (Instruction *NV = FoldOpIntoPhi(CI))
3868 return NV;
3869
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003870 // If the source value is an instruction with only this use, we can attempt to
3871 // propagate the cast into the instruction. Also, only handle integral types
3872 // for now.
3873 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003874 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003875 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3876 const Type *DestTy = CI.getType();
Chris Lattnerd1f46d32005-04-24 06:59:08 +00003877 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
3878 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003879
3880 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3881 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3882
3883 switch (SrcI->getOpcode()) {
3884 case Instruction::Add:
3885 case Instruction::Mul:
3886 case Instruction::And:
3887 case Instruction::Or:
3888 case Instruction::Xor:
3889 // If we are discarding information, or just changing the sign, rewrite.
3890 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3891 // Don't insert two casts if they cannot be eliminated. We allow two
3892 // casts to be inserted if the sizes are the same. This could only be
3893 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003894 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3895 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003896 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3897 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3898 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3899 ->getOpcode(), Op0c, Op1c);
3900 }
3901 }
Chris Lattner72086162005-05-06 02:07:39 +00003902
3903 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
3904 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
3905 Op1 == ConstantBool::True &&
3906 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
3907 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
3908 return BinaryOperator::createXor(New,
3909 ConstantInt::get(CI.getType(), 1));
3910 }
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003911 break;
3912 case Instruction::Shl:
3913 // Allow changing the sign of the source operand. Do not allow changing
3914 // the size of the shift, UNLESS the shift amount is a constant. We
3915 // mush not change variable sized shifts to a smaller size, because it
3916 // is undefined to shift more bits out than exist in the value.
3917 if (DestBitSize == SrcBitSize ||
3918 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3919 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3920 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3921 }
3922 break;
Chris Lattner87380412005-05-06 04:18:52 +00003923 case Instruction::Shr:
3924 // If this is a signed shr, and if all bits shifted in are about to be
3925 // truncated off, turn it into an unsigned shr to allow greater
3926 // simplifications.
3927 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
3928 isa<ConstantInt>(Op1)) {
3929 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
3930 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
3931 // Convert to unsigned.
3932 Value *N1 = InsertOperandCastBefore(Op0,
3933 Op0->getType()->getUnsignedVersion(), &CI);
3934 // Insert the new shift, which is now unsigned.
3935 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
3936 Op1, Src->getName()), CI);
3937 return new CastInst(N1, CI.getType());
3938 }
3939 }
3940 break;
3941
Chris Lattner809dfac2005-05-04 19:10:26 +00003942 case Instruction::SetNE:
Chris Lattner809dfac2005-05-04 19:10:26 +00003943 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4c2d3782005-05-06 01:53:19 +00003944 if (Op1C->getRawValue() == 0) {
3945 // If the input only has the low bit set, simplify directly.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003946 Constant *Not1 =
Chris Lattner809dfac2005-05-04 19:10:26 +00003947 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattner4c2d3782005-05-06 01:53:19 +00003948 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner809dfac2005-05-04 19:10:26 +00003949 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3950 if (CI.getType() == Op0->getType())
3951 return ReplaceInstUsesWith(CI, Op0);
3952 else
3953 return new CastInst(Op0, CI.getType());
3954 }
Chris Lattner4c2d3782005-05-06 01:53:19 +00003955
3956 // If the input is an and with a single bit, shift then simplify.
3957 ConstantInt *AndRHS;
3958 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
3959 if (AndRHS->getRawValue() &&
3960 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattner22d00a82005-08-02 19:16:58 +00003961 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattner4c2d3782005-05-06 01:53:19 +00003962 // Perform an unsigned shr by shiftamt. Convert input to
3963 // unsigned if it is signed.
3964 Value *In = Op0;
3965 if (In->getType()->isSigned())
3966 In = InsertNewInstBefore(new CastInst(In,
3967 In->getType()->getUnsignedVersion(), In->getName()),CI);
3968 // Insert the shift to put the result in the low bit.
3969 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
3970 ConstantInt::get(Type::UByteTy, ShiftAmt),
3971 In->getName()+".lobit"), CI);
Chris Lattner4c2d3782005-05-06 01:53:19 +00003972 if (CI.getType() == In->getType())
3973 return ReplaceInstUsesWith(CI, In);
3974 else
3975 return new CastInst(In, CI.getType());
3976 }
3977 }
3978 }
3979 break;
3980 case Instruction::SetEQ:
3981 // We if we are just checking for a seteq of a single bit and casting it
3982 // to an integer. If so, shift the bit to the appropriate place then
3983 // cast to integer to avoid the comparison.
3984 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
3985 // Is Op1C a power of two or zero?
3986 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
3987 // cast (X == 1) to int -> X iff X has only the low bit set.
3988 if (Op1C->getRawValue() == 1) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00003989 Constant *Not1 =
Chris Lattner4c2d3782005-05-06 01:53:19 +00003990 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
3991 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3992 if (CI.getType() == Op0->getType())
3993 return ReplaceInstUsesWith(CI, Op0);
3994 else
3995 return new CastInst(Op0, CI.getType());
3996 }
3997 }
Chris Lattner809dfac2005-05-04 19:10:26 +00003998 }
3999 }
4000 break;
Chris Lattnerdfae8be2003-07-24 17:35:25 +00004001 }
4002 }
Chris Lattner260ab202002-04-18 17:39:14 +00004003 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00004004}
4005
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004006/// GetSelectFoldableOperands - We want to turn code that looks like this:
4007/// %C = or %A, %B
4008/// %D = select %cond, %C, %A
4009/// into:
4010/// %C = select %cond, %B, 0
4011/// %D = or %A, %C
4012///
4013/// Assuming that the specified instruction is an operand to the select, return
4014/// a bitmask indicating which operands of this instruction are foldable if they
4015/// equal the other incoming value of the select.
4016///
4017static unsigned GetSelectFoldableOperands(Instruction *I) {
4018 switch (I->getOpcode()) {
4019 case Instruction::Add:
4020 case Instruction::Mul:
4021 case Instruction::And:
4022 case Instruction::Or:
4023 case Instruction::Xor:
4024 return 3; // Can fold through either operand.
4025 case Instruction::Sub: // Can only fold on the amount subtracted.
4026 case Instruction::Shl: // Can only fold on the shift amount.
4027 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00004028 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004029 default:
4030 return 0; // Cannot fold
4031 }
4032}
4033
4034/// GetSelectFoldableConstant - For the same transformation as the previous
4035/// function, return the identity constant that goes into the select.
4036static Constant *GetSelectFoldableConstant(Instruction *I) {
4037 switch (I->getOpcode()) {
4038 default: assert(0 && "This cannot happen!"); abort();
4039 case Instruction::Add:
4040 case Instruction::Sub:
4041 case Instruction::Or:
4042 case Instruction::Xor:
4043 return Constant::getNullValue(I->getType());
4044 case Instruction::Shl:
4045 case Instruction::Shr:
4046 return Constant::getNullValue(Type::UByteTy);
4047 case Instruction::And:
4048 return ConstantInt::getAllOnesValue(I->getType());
4049 case Instruction::Mul:
4050 return ConstantInt::get(I->getType(), 1);
4051 }
4052}
4053
Chris Lattner411336f2005-01-19 21:50:18 +00004054/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4055/// have the same opcode and only one use each. Try to simplify this.
4056Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4057 Instruction *FI) {
4058 if (TI->getNumOperands() == 1) {
4059 // If this is a non-volatile load or a cast from the same type,
4060 // merge.
4061 if (TI->getOpcode() == Instruction::Cast) {
4062 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4063 return 0;
4064 } else {
4065 return 0; // unknown unary op.
4066 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004067
Chris Lattner411336f2005-01-19 21:50:18 +00004068 // Fold this by inserting a select from the input values.
4069 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4070 FI->getOperand(0), SI.getName()+".v");
4071 InsertNewInstBefore(NewSI, SI);
4072 return new CastInst(NewSI, TI->getType());
4073 }
4074
4075 // Only handle binary operators here.
4076 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4077 return 0;
4078
4079 // Figure out if the operations have any operands in common.
4080 Value *MatchOp, *OtherOpT, *OtherOpF;
4081 bool MatchIsOpZero;
4082 if (TI->getOperand(0) == FI->getOperand(0)) {
4083 MatchOp = TI->getOperand(0);
4084 OtherOpT = TI->getOperand(1);
4085 OtherOpF = FI->getOperand(1);
4086 MatchIsOpZero = true;
4087 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4088 MatchOp = TI->getOperand(1);
4089 OtherOpT = TI->getOperand(0);
4090 OtherOpF = FI->getOperand(0);
4091 MatchIsOpZero = false;
4092 } else if (!TI->isCommutative()) {
4093 return 0;
4094 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4095 MatchOp = TI->getOperand(0);
4096 OtherOpT = TI->getOperand(1);
4097 OtherOpF = FI->getOperand(0);
4098 MatchIsOpZero = true;
4099 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4100 MatchOp = TI->getOperand(1);
4101 OtherOpT = TI->getOperand(0);
4102 OtherOpF = FI->getOperand(1);
4103 MatchIsOpZero = true;
4104 } else {
4105 return 0;
4106 }
4107
4108 // If we reach here, they do have operations in common.
4109 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4110 OtherOpF, SI.getName()+".v");
4111 InsertNewInstBefore(NewSI, SI);
4112
4113 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4114 if (MatchIsOpZero)
4115 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4116 else
4117 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4118 } else {
4119 if (MatchIsOpZero)
4120 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4121 else
4122 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4123 }
4124}
4125
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004126Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00004127 Value *CondVal = SI.getCondition();
4128 Value *TrueVal = SI.getTrueValue();
4129 Value *FalseVal = SI.getFalseValue();
4130
4131 // select true, X, Y -> X
4132 // select false, X, Y -> Y
4133 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004134 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00004135 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004136 else {
4137 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00004138 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004139 }
Chris Lattner533bc492004-03-30 19:37:13 +00004140
4141 // select C, X, X -> X
4142 if (TrueVal == FalseVal)
4143 return ReplaceInstUsesWith(SI, TrueVal);
4144
Chris Lattner81a7a232004-10-16 18:11:37 +00004145 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4146 return ReplaceInstUsesWith(SI, FalseVal);
4147 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4148 return ReplaceInstUsesWith(SI, TrueVal);
4149 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4150 if (isa<Constant>(TrueVal))
4151 return ReplaceInstUsesWith(SI, TrueVal);
4152 else
4153 return ReplaceInstUsesWith(SI, FalseVal);
4154 }
4155
Chris Lattner1c631e82004-04-08 04:43:23 +00004156 if (SI.getType() == Type::BoolTy)
4157 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4158 if (C == ConstantBool::True) {
4159 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004160 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004161 } else {
4162 // Change: A = select B, false, C --> A = and !B, C
4163 Value *NotCond =
4164 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4165 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004166 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004167 }
4168 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4169 if (C == ConstantBool::False) {
4170 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004171 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004172 } else {
4173 // Change: A = select B, C, true --> A = or !B, C
4174 Value *NotCond =
4175 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4176 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004177 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00004178 }
4179 }
4180
Chris Lattner183b3362004-04-09 19:05:30 +00004181 // Selecting between two integer constants?
4182 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4183 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4184 // select C, 1, 0 -> cast C to int
4185 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4186 return new CastInst(CondVal, SI.getType());
4187 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4188 // select C, 0, 1 -> cast !C to int
4189 Value *NotCond =
4190 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00004191 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00004192 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00004193 }
Chris Lattner35167c32004-06-09 07:59:58 +00004194
4195 // If one of the constants is zero (we know they can't both be) and we
4196 // have a setcc instruction with zero, and we have an 'and' with the
4197 // non-constant value, eliminate this whole mess. This corresponds to
4198 // cases like this: ((X & 27) ? 27 : 0)
4199 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4200 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4201 if ((IC->getOpcode() == Instruction::SetEQ ||
4202 IC->getOpcode() == Instruction::SetNE) &&
4203 isa<ConstantInt>(IC->getOperand(1)) &&
4204 cast<Constant>(IC->getOperand(1))->isNullValue())
4205 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4206 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004207 isa<ConstantInt>(ICA->getOperand(1)) &&
4208 (ICA->getOperand(1) == TrueValC ||
4209 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00004210 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4211 // Okay, now we know that everything is set up, we just don't
4212 // know whether we have a setne or seteq and whether the true or
4213 // false val is the zero.
4214 bool ShouldNotVal = !TrueValC->isNullValue();
4215 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4216 Value *V = ICA;
4217 if (ShouldNotVal)
4218 V = InsertNewInstBefore(BinaryOperator::create(
4219 Instruction::Xor, V, ICA->getOperand(1)), SI);
4220 return ReplaceInstUsesWith(SI, V);
4221 }
Chris Lattner533bc492004-03-30 19:37:13 +00004222 }
Chris Lattner623fba12004-04-10 22:21:27 +00004223
4224 // See if we are selecting two values based on a comparison of the two values.
4225 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4226 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4227 // Transform (X == Y) ? X : Y -> Y
4228 if (SCI->getOpcode() == Instruction::SetEQ)
4229 return ReplaceInstUsesWith(SI, FalseVal);
4230 // Transform (X != Y) ? X : Y -> X
4231 if (SCI->getOpcode() == Instruction::SetNE)
4232 return ReplaceInstUsesWith(SI, TrueVal);
4233 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4234
4235 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4236 // Transform (X == Y) ? Y : X -> X
4237 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00004238 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004239 // Transform (X != Y) ? Y : X -> Y
4240 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00004241 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00004242 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4243 }
4244 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004245
Chris Lattnera04c9042005-01-13 22:52:24 +00004246 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4247 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4248 if (TI->hasOneUse() && FI->hasOneUse()) {
4249 bool isInverse = false;
4250 Instruction *AddOp = 0, *SubOp = 0;
4251
Chris Lattner411336f2005-01-19 21:50:18 +00004252 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4253 if (TI->getOpcode() == FI->getOpcode())
4254 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4255 return IV;
4256
4257 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4258 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00004259 if (TI->getOpcode() == Instruction::Sub &&
4260 FI->getOpcode() == Instruction::Add) {
4261 AddOp = FI; SubOp = TI;
4262 } else if (FI->getOpcode() == Instruction::Sub &&
4263 TI->getOpcode() == Instruction::Add) {
4264 AddOp = TI; SubOp = FI;
4265 }
4266
4267 if (AddOp) {
4268 Value *OtherAddOp = 0;
4269 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4270 OtherAddOp = AddOp->getOperand(1);
4271 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4272 OtherAddOp = AddOp->getOperand(0);
4273 }
4274
4275 if (OtherAddOp) {
4276 // So at this point we know we have:
4277 // select C, (add X, Y), (sub X, ?)
4278 // We can do the transform profitably if either 'Y' = '?' or '?' is
4279 // a constant.
4280 if (SubOp->getOperand(1) == AddOp ||
4281 isa<Constant>(SubOp->getOperand(1))) {
4282 Value *NegVal;
4283 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4284 NegVal = ConstantExpr::getNeg(C);
4285 } else {
4286 NegVal = InsertNewInstBefore(
4287 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4288 }
4289
Chris Lattner51726c42005-01-14 17:35:12 +00004290 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00004291 Value *NewFalseOp = NegVal;
4292 if (AddOp != TI)
4293 std::swap(NewTrueOp, NewFalseOp);
4294 Instruction *NewSel =
4295 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00004296
Chris Lattnera04c9042005-01-13 22:52:24 +00004297 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00004298 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00004299 }
4300 }
4301 }
4302 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004303
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004304 // See if we can fold the select into one of our operands.
4305 if (SI.getType()->isInteger()) {
4306 // See the comment above GetSelectFoldableOperands for a description of the
4307 // transformation we are doing here.
4308 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4309 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4310 !isa<Constant>(FalseVal))
4311 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4312 unsigned OpToFold = 0;
4313 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4314 OpToFold = 1;
4315 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4316 OpToFold = 2;
4317 }
4318
4319 if (OpToFold) {
4320 Constant *C = GetSelectFoldableConstant(TVI);
4321 std::string Name = TVI->getName(); TVI->setName("");
4322 Instruction *NewSel =
4323 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4324 Name);
4325 InsertNewInstBefore(NewSel, SI);
4326 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4327 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4328 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4329 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4330 else {
4331 assert(0 && "Unknown instruction!!");
4332 }
4333 }
4334 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00004335
Chris Lattner56e4d3d2004-04-09 23:46:01 +00004336 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4337 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4338 !isa<Constant>(TrueVal))
4339 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4340 unsigned OpToFold = 0;
4341 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4342 OpToFold = 1;
4343 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4344 OpToFold = 2;
4345 }
4346
4347 if (OpToFold) {
4348 Constant *C = GetSelectFoldableConstant(FVI);
4349 std::string Name = FVI->getName(); FVI->setName("");
4350 Instruction *NewSel =
4351 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4352 Name);
4353 InsertNewInstBefore(NewSel, SI);
4354 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4355 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4356 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4357 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4358 else {
4359 assert(0 && "Unknown instruction!!");
4360 }
4361 }
4362 }
4363 }
Chris Lattnerd6f636a2005-04-24 07:30:14 +00004364
4365 if (BinaryOperator::isNot(CondVal)) {
4366 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4367 SI.setOperand(1, FalseVal);
4368 SI.setOperand(2, TrueVal);
4369 return &SI;
4370 }
4371
Chris Lattnerb909e8b2004-03-12 05:52:32 +00004372 return 0;
4373}
4374
4375
Chris Lattner970c33a2003-06-19 17:00:31 +00004376// CallInst simplification
4377//
4378Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00004379 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4380 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00004381 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4382 bool Changed = false;
4383
4384 // memmove/cpy/set of zero bytes is a noop.
4385 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4386 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4387
4388 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004389
Chris Lattner00648e12004-10-12 04:52:52 +00004390 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4391 if (CI->getRawValue() == 1) {
4392 // Replace the instruction with just byte operations. We would
4393 // transform other cases to loads/stores, but we don't know if
4394 // alignment is sufficient.
4395 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004396 }
4397
Chris Lattner00648e12004-10-12 04:52:52 +00004398 // If we have a memmove and the source operation is a constant global,
4399 // then the source and dest pointers can't alias, so we can change this
4400 // into a call to memcpy.
4401 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4402 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4403 if (GVSrc->isConstant()) {
4404 Module *M = CI.getParent()->getParent()->getParent();
4405 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4406 CI.getCalledFunction()->getFunctionType());
4407 CI.setOperand(0, MemCpy);
4408 Changed = true;
4409 }
4410
4411 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00004412 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4413 // If this stoppoint is at the same source location as the previous
4414 // stoppoint in the chain, it is not needed.
4415 if (DbgStopPointInst *PrevSPI =
4416 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4417 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4418 SPI->getColNo() == PrevSPI->getColNo()) {
4419 SPI->replaceAllUsesWith(PrevSPI);
4420 return EraseInstFromFunction(CI);
4421 }
Chris Lattner00648e12004-10-12 04:52:52 +00004422 }
4423
Chris Lattneraec3d942003-10-07 22:32:43 +00004424 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00004425}
4426
4427// InvokeInst simplification
4428//
4429Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00004430 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00004431}
4432
Chris Lattneraec3d942003-10-07 22:32:43 +00004433// visitCallSite - Improvements for call and invoke instructions.
4434//
4435Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004436 bool Changed = false;
4437
4438 // If the callee is a constexpr cast of a function, attempt to move the cast
4439 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00004440 if (transformConstExprCastCall(CS)) return 0;
4441
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004442 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00004443
Chris Lattner61d9d812005-05-13 07:09:09 +00004444 if (Function *CalleeF = dyn_cast<Function>(Callee))
4445 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4446 Instruction *OldCall = CS.getInstruction();
4447 // If the call and callee calling conventions don't match, this call must
4448 // be unreachable, as the call is undefined.
4449 new StoreInst(ConstantBool::True,
4450 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4451 if (!OldCall->use_empty())
4452 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4453 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4454 return EraseInstFromFunction(*OldCall);
4455 return 0;
4456 }
4457
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004458 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4459 // This instruction is not reachable, just remove it. We insert a store to
4460 // undef so that we know that this code is not reachable, despite the fact
4461 // that we can't modify the CFG here.
4462 new StoreInst(ConstantBool::True,
4463 UndefValue::get(PointerType::get(Type::BoolTy)),
4464 CS.getInstruction());
4465
4466 if (!CS.getInstruction()->use_empty())
4467 CS.getInstruction()->
4468 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4469
4470 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4471 // Don't break the CFG, insert a dummy cond branch.
4472 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4473 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00004474 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004475 return EraseInstFromFunction(*CS.getInstruction());
4476 }
Chris Lattner81a7a232004-10-16 18:11:37 +00004477
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004478 const PointerType *PTy = cast<PointerType>(Callee->getType());
4479 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4480 if (FTy->isVarArg()) {
4481 // See if we can optimize any arguments passed through the varargs area of
4482 // the call.
4483 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4484 E = CS.arg_end(); I != E; ++I)
4485 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4486 // If this cast does not effect the value passed through the varargs
4487 // area, we can eliminate the use of the cast.
4488 Value *Op = CI->getOperand(0);
4489 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4490 *I = Op;
4491 Changed = true;
4492 }
4493 }
4494 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004495
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004496 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004497}
4498
Chris Lattner970c33a2003-06-19 17:00:31 +00004499// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4500// attempt to move the cast to the arguments of the call/invoke.
4501//
4502bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4503 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4504 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004505 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004506 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004507 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004508 Instruction *Caller = CS.getInstruction();
4509
4510 // Okay, this is a cast from a function to a different type. Unless doing so
4511 // would cause a type conversion of one of our arguments, change this call to
4512 // be a direct call with arguments casted to the appropriate types.
4513 //
4514 const FunctionType *FT = Callee->getFunctionType();
4515 const Type *OldRetTy = Caller->getType();
4516
Chris Lattner1f7942f2004-01-14 06:06:08 +00004517 // Check to see if we are changing the return type...
4518 if (OldRetTy != FT->getReturnType()) {
4519 if (Callee->isExternal() &&
4520 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4521 !Caller->use_empty())
4522 return false; // Cannot transform this return value...
4523
4524 // If the callsite is an invoke instruction, and the return value is used by
4525 // a PHI node in a successor, we cannot change the return type of the call
4526 // because there is no place to put the cast instruction (without breaking
4527 // the critical edge). Bail out in this case.
4528 if (!Caller->use_empty())
4529 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4530 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4531 UI != E; ++UI)
4532 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4533 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004534 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004535 return false;
4536 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004537
4538 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4539 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004540
Chris Lattner970c33a2003-06-19 17:00:31 +00004541 CallSite::arg_iterator AI = CS.arg_begin();
4542 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4543 const Type *ParamTy = FT->getParamType(i);
4544 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004545 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004546 }
4547
4548 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4549 Callee->isExternal())
4550 return false; // Do not delete arguments unless we have a function body...
4551
4552 // Okay, we decided that this is a safe thing to do: go ahead and start
4553 // inserting cast instructions as necessary...
4554 std::vector<Value*> Args;
4555 Args.reserve(NumActualArgs);
4556
4557 AI = CS.arg_begin();
4558 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4559 const Type *ParamTy = FT->getParamType(i);
4560 if ((*AI)->getType() == ParamTy) {
4561 Args.push_back(*AI);
4562 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004563 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4564 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004565 }
4566 }
4567
4568 // If the function takes more arguments than the call was taking, add them
4569 // now...
4570 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4571 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4572
4573 // If we are removing arguments to the function, emit an obnoxious warning...
4574 if (FT->getNumParams() < NumActualArgs)
4575 if (!FT->isVarArg()) {
4576 std::cerr << "WARNING: While resolving call to function '"
4577 << Callee->getName() << "' arguments were dropped!\n";
4578 } else {
4579 // Add all of the arguments in their promoted form to the arg list...
4580 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4581 const Type *PTy = getPromotedType((*AI)->getType());
4582 if (PTy != (*AI)->getType()) {
4583 // Must promote to pass through va_arg area!
4584 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4585 InsertNewInstBefore(Cast, *Caller);
4586 Args.push_back(Cast);
4587 } else {
4588 Args.push_back(*AI);
4589 }
4590 }
4591 }
4592
4593 if (FT->getReturnType() == Type::VoidTy)
4594 Caller->setName(""); // Void type should not have a name...
4595
4596 Instruction *NC;
4597 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004598 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004599 Args, Caller->getName(), Caller);
Chris Lattner05c703e2005-05-14 12:25:32 +00004600 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004601 } else {
4602 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattner6aacb0f2005-05-06 06:48:21 +00004603 if (cast<CallInst>(Caller)->isTailCall())
4604 cast<CallInst>(NC)->setTailCall();
Chris Lattner05c703e2005-05-14 12:25:32 +00004605 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner970c33a2003-06-19 17:00:31 +00004606 }
4607
4608 // Insert a cast of the return type as necessary...
4609 Value *NV = NC;
4610 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4611 if (NV->getType() != Type::VoidTy) {
4612 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004613
4614 // If this is an invoke instruction, we should insert it after the first
4615 // non-phi, instruction in the normal successor block.
4616 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4617 BasicBlock::iterator I = II->getNormalDest()->begin();
4618 while (isa<PHINode>(I)) ++I;
4619 InsertNewInstBefore(NC, *I);
4620 } else {
4621 // Otherwise, it's a call, just insert cast right after the call instr
4622 InsertNewInstBefore(NC, *Caller);
4623 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004624 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004625 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004626 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004627 }
4628 }
4629
4630 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4631 Caller->replaceAllUsesWith(NV);
4632 Caller->getParent()->getInstList().erase(Caller);
4633 removeFromWorkList(Caller);
4634 return true;
4635}
4636
4637
Chris Lattner7515cab2004-11-14 19:13:23 +00004638// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4639// operator and they all are only used by the PHI, PHI together their
4640// inputs, and do the operation once, to the result of the PHI.
4641Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4642 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4643
4644 // Scan the instruction, looking for input operations that can be folded away.
4645 // If all input operands to the phi are the same instruction (e.g. a cast from
4646 // the same type or "+42") we can pull the operation through the PHI, reducing
4647 // code size and simplifying code.
4648 Constant *ConstantOp = 0;
4649 const Type *CastSrcTy = 0;
4650 if (isa<CastInst>(FirstInst)) {
4651 CastSrcTy = FirstInst->getOperand(0)->getType();
4652 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4653 // Can fold binop or shift if the RHS is a constant.
4654 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4655 if (ConstantOp == 0) return 0;
4656 } else {
4657 return 0; // Cannot fold this operation.
4658 }
4659
4660 // Check to see if all arguments are the same operation.
4661 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4662 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4663 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4664 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4665 return 0;
4666 if (CastSrcTy) {
4667 if (I->getOperand(0)->getType() != CastSrcTy)
4668 return 0; // Cast operation must match.
4669 } else if (I->getOperand(1) != ConstantOp) {
4670 return 0;
4671 }
4672 }
4673
4674 // Okay, they are all the same operation. Create a new PHI node of the
4675 // correct type, and PHI together all of the LHS's of the instructions.
4676 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4677 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004678 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004679
4680 Value *InVal = FirstInst->getOperand(0);
4681 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004682
4683 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004684 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4685 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4686 if (NewInVal != InVal)
4687 InVal = 0;
4688 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4689 }
4690
4691 Value *PhiVal;
4692 if (InVal) {
4693 // The new PHI unions all of the same values together. This is really
4694 // common, so we handle it intelligently here for compile-time speed.
4695 PhiVal = InVal;
4696 delete NewPN;
4697 } else {
4698 InsertNewInstBefore(NewPN, PN);
4699 PhiVal = NewPN;
4700 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004701
Chris Lattner7515cab2004-11-14 19:13:23 +00004702 // Insert and return the new operation.
4703 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004704 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004705 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004706 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004707 else
4708 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004709 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004710}
Chris Lattner48a44f72002-05-02 17:06:02 +00004711
Chris Lattner71536432005-01-17 05:10:15 +00004712/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4713/// that is dead.
4714static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4715 if (PN->use_empty()) return true;
4716 if (!PN->hasOneUse()) return false;
4717
4718 // Remember this node, and if we find the cycle, return.
4719 if (!PotentiallyDeadPHIs.insert(PN).second)
4720 return true;
4721
4722 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4723 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004724
Chris Lattner71536432005-01-17 05:10:15 +00004725 return false;
4726}
4727
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004728// PHINode simplification
4729//
Chris Lattner113f4f42002-06-25 16:13:24 +00004730Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner9f9c2602005-08-05 01:04:30 +00004731 if (Value *V = PN.hasConstantValue())
4732 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00004733
4734 // If the only user of this instruction is a cast instruction, and all of the
4735 // incoming values are constants, change this PHI to merge together the casted
4736 // constants.
4737 if (PN.hasOneUse())
4738 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4739 if (CI->getType() != PN.getType()) { // noop casts will be folded
4740 bool AllConstant = true;
4741 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4742 if (!isa<Constant>(PN.getIncomingValue(i))) {
4743 AllConstant = false;
4744 break;
4745 }
4746 if (AllConstant) {
4747 // Make a new PHI with all casted values.
4748 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4749 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4750 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4751 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4752 PN.getIncomingBlock(i));
4753 }
4754
4755 // Update the cast instruction.
4756 CI->setOperand(0, New);
4757 WorkList.push_back(CI); // revisit the cast instruction to fold.
4758 WorkList.push_back(New); // Make sure to revisit the new Phi
4759 return &PN; // PN is now dead!
4760 }
4761 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004762
4763 // If all PHI operands are the same operation, pull them through the PHI,
4764 // reducing code size.
4765 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4766 PN.getIncomingValue(0)->hasOneUse())
4767 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4768 return Result;
4769
Chris Lattner71536432005-01-17 05:10:15 +00004770 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4771 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4772 // PHI)... break the cycle.
4773 if (PN.hasOneUse())
4774 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4775 std::set<PHINode*> PotentiallyDeadPHIs;
4776 PotentiallyDeadPHIs.insert(&PN);
4777 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4778 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4779 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004780
Chris Lattner91daeb52003-12-19 05:58:40 +00004781 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004782}
4783
Chris Lattner69193f92004-04-05 01:30:19 +00004784static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4785 Instruction *InsertPoint,
4786 InstCombiner *IC) {
4787 unsigned PS = IC->getTargetData().getPointerSize();
4788 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004789 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4790 // We must insert a cast to ensure we sign-extend.
4791 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4792 V->getName()), *InsertPoint);
4793 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4794 *InsertPoint);
4795}
4796
Chris Lattner48a44f72002-05-02 17:06:02 +00004797
Chris Lattner113f4f42002-06-25 16:13:24 +00004798Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004799 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004800 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004801 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004802 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004803 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004804
Chris Lattner81a7a232004-10-16 18:11:37 +00004805 if (isa<UndefValue>(GEP.getOperand(0)))
4806 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4807
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004808 bool HasZeroPointerIndex = false;
4809 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4810 HasZeroPointerIndex = C->isNullValue();
4811
4812 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004813 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004814
Chris Lattner69193f92004-04-05 01:30:19 +00004815 // Eliminate unneeded casts for indices.
4816 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004817 gep_type_iterator GTI = gep_type_begin(GEP);
4818 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4819 if (isa<SequentialType>(*GTI)) {
4820 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4821 Value *Src = CI->getOperand(0);
4822 const Type *SrcTy = Src->getType();
4823 const Type *DestTy = CI->getType();
4824 if (Src->getType()->isInteger()) {
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004825 if (SrcTy->getPrimitiveSizeInBits() ==
4826 DestTy->getPrimitiveSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004827 // We can always eliminate a cast from ulong or long to the other.
4828 // We can always eliminate a cast from uint to int or the other on
4829 // 32-bit pointer platforms.
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004830 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattner2b2412d2004-04-07 18:38:20 +00004831 MadeChange = true;
4832 GEP.setOperand(i, Src);
4833 }
4834 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4835 SrcTy->getPrimitiveSize() == 4) {
4836 // We can always eliminate a cast from int to [u]long. We can
4837 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4838 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004839 if (SrcTy->isSigned() ||
Chris Lattnerd1f46d32005-04-24 06:59:08 +00004840 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004841 MadeChange = true;
4842 GEP.setOperand(i, Src);
4843 }
Chris Lattner69193f92004-04-05 01:30:19 +00004844 }
4845 }
4846 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004847 // If we are using a wider index than needed for this platform, shrink it
4848 // to what we need. If the incoming value needs a cast instruction,
4849 // insert it. This explicit cast can make subsequent optimizations more
4850 // obvious.
4851 Value *Op = GEP.getOperand(i);
4852 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004853 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004854 GEP.setOperand(i, ConstantExpr::getCast(C,
4855 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004856 MadeChange = true;
4857 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004858 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4859 Op->getName()), GEP);
4860 GEP.setOperand(i, Op);
4861 MadeChange = true;
4862 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004863
4864 // If this is a constant idx, make sure to canonicalize it to be a signed
4865 // operand, otherwise CSE and other optimizations are pessimized.
4866 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4867 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4868 CUI->getType()->getSignedVersion()));
4869 MadeChange = true;
4870 }
Chris Lattner69193f92004-04-05 01:30:19 +00004871 }
4872 if (MadeChange) return &GEP;
4873
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004874 // Combine Indices - If the source pointer to this getelementptr instruction
4875 // is a getelementptr instruction, combine the indices of the two
4876 // getelementptr instructions into a single instruction.
4877 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004878 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004879 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004880 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004881
4882 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004883 // Note that if our source is a gep chain itself that we wait for that
4884 // chain to be resolved before we perform this transformation. This
4885 // avoids us creating a TON of code in some cases.
4886 //
4887 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4888 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4889 return 0; // Wait until our source is folded to completion.
4890
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004891 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004892
4893 // Find out whether the last index in the source GEP is a sequential idx.
4894 bool EndsWithSequential = false;
4895 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4896 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004897 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004898
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004899 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004900 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004901 // Replace: gep (gep %P, long B), long A, ...
4902 // With: T = long A+B; gep %P, T, ...
4903 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004904 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004905 if (SO1 == Constant::getNullValue(SO1->getType())) {
4906 Sum = GO1;
4907 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4908 Sum = SO1;
4909 } else {
4910 // If they aren't the same type, convert both to an integer of the
4911 // target's pointer size.
4912 if (SO1->getType() != GO1->getType()) {
4913 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4914 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4915 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4916 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4917 } else {
4918 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004919 if (SO1->getType()->getPrimitiveSize() == PS) {
4920 // Convert GO1 to SO1's type.
4921 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4922
4923 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4924 // Convert SO1 to GO1's type.
4925 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4926 } else {
4927 const Type *PT = TD->getIntPtrType();
4928 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4929 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4930 }
4931 }
4932 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004933 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4934 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4935 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004936 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4937 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004938 }
Chris Lattner69193f92004-04-05 01:30:19 +00004939 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004940
4941 // Recycle the GEP we already have if possible.
4942 if (SrcGEPOperands.size() == 2) {
4943 GEP.setOperand(0, SrcGEPOperands[0]);
4944 GEP.setOperand(1, Sum);
4945 return &GEP;
4946 } else {
4947 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4948 SrcGEPOperands.end()-1);
4949 Indices.push_back(Sum);
4950 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4951 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004952 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00004953 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004954 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004955 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004956 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4957 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004958 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4959 }
4960
4961 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004962 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004963
Chris Lattner5f667a62004-05-07 22:09:22 +00004964 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004965 // GEP of global variable. If all of the indices for this GEP are
4966 // constants, we can promote this to a constexpr instead of an instruction.
4967
4968 // Scan for nonconstants...
4969 std::vector<Constant*> Indices;
4970 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4971 for (; I != E && isa<Constant>(*I); ++I)
4972 Indices.push_back(cast<Constant>(*I));
4973
4974 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004975 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004976
4977 // Replace all uses of the GEP with the new constexpr...
4978 return ReplaceInstUsesWith(GEP, CE);
4979 }
Chris Lattner567b81f2005-09-13 00:40:14 +00004980 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
4981 if (!isa<PointerType>(X->getType())) {
4982 // Not interesting. Source pointer must be a cast from pointer.
4983 } else if (HasZeroPointerIndex) {
4984 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4985 // into : GEP [10 x ubyte]* X, long 0, ...
4986 //
4987 // This occurs when the program declares an array extern like "int X[];"
4988 //
4989 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4990 const PointerType *XTy = cast<PointerType>(X->getType());
4991 if (const ArrayType *XATy =
4992 dyn_cast<ArrayType>(XTy->getElementType()))
4993 if (const ArrayType *CATy =
4994 dyn_cast<ArrayType>(CPTy->getElementType()))
4995 if (CATy->getElementType() == XATy->getElementType()) {
4996 // At this point, we know that the cast source type is a pointer
4997 // to an array of the same type as the destination pointer
4998 // array. Because the array type is never stepped over (there
4999 // is a leading zero) we can fold the cast into this GEP.
5000 GEP.setOperand(0, X);
5001 return &GEP;
5002 }
5003 } else if (GEP.getNumOperands() == 2) {
5004 // Transform things like:
Chris Lattner2a893292005-09-13 18:36:04 +00005005 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5006 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattner567b81f2005-09-13 00:40:14 +00005007 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5008 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5009 if (isa<ArrayType>(SrcElTy) &&
5010 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5011 TD->getTypeSize(ResElTy)) {
5012 Value *V = InsertNewInstBefore(
5013 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5014 GEP.getOperand(1), GEP.getName()), GEP);
5015 return new CastInst(V, GEP.getType());
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005016 }
Chris Lattner2a893292005-09-13 18:36:04 +00005017
5018 // Transform things like:
5019 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5020 // (where tmp = 8*tmp2) into:
5021 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5022
5023 if (isa<ArrayType>(SrcElTy) &&
5024 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5025 uint64_t ArrayEltSize =
5026 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5027
5028 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5029 // allow either a mul, shift, or constant here.
5030 Value *NewIdx = 0;
5031 ConstantInt *Scale = 0;
5032 if (ArrayEltSize == 1) {
5033 NewIdx = GEP.getOperand(1);
5034 Scale = ConstantInt::get(NewIdx->getType(), 1);
5035 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattnera393e4d2005-09-14 17:32:56 +00005036 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner2a893292005-09-13 18:36:04 +00005037 Scale = CI;
5038 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5039 if (Inst->getOpcode() == Instruction::Shl &&
5040 isa<ConstantInt>(Inst->getOperand(1))) {
5041 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5042 if (Inst->getType()->isSigned())
5043 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5044 else
5045 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5046 NewIdx = Inst->getOperand(0);
5047 } else if (Inst->getOpcode() == Instruction::Mul &&
5048 isa<ConstantInt>(Inst->getOperand(1))) {
5049 Scale = cast<ConstantInt>(Inst->getOperand(1));
5050 NewIdx = Inst->getOperand(0);
5051 }
5052 }
5053
5054 // If the index will be to exactly the right offset with the scale taken
5055 // out, perform the transformation.
5056 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5057 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5058 Scale = ConstantSInt::get(C->getType(),
Chris Lattnera393e4d2005-09-14 17:32:56 +00005059 (int64_t)C->getRawValue() /
5060 (int64_t)ArrayEltSize);
Chris Lattner2a893292005-09-13 18:36:04 +00005061 else
5062 Scale = ConstantUInt::get(Scale->getType(),
5063 Scale->getRawValue() / ArrayEltSize);
5064 if (Scale->getRawValue() != 1) {
5065 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5066 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5067 NewIdx = InsertNewInstBefore(Sc, GEP);
5068 }
5069
5070 // Insert the new GEP instruction.
5071 Instruction *Idx =
5072 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5073 NewIdx, GEP.getName());
5074 Idx = InsertNewInstBefore(Idx, GEP);
5075 return new CastInst(Idx, GEP.getType());
5076 }
5077 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00005078 }
Chris Lattnerca081252001-12-14 16:52:21 +00005079 }
5080
Chris Lattnerca081252001-12-14 16:52:21 +00005081 return 0;
5082}
5083
Chris Lattner1085bdf2002-11-04 16:18:53 +00005084Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5085 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5086 if (AI.isArrayAllocation()) // Check C != 1
5087 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5088 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005089 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00005090
5091 // Create and insert the replacement instruction...
5092 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00005093 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005094 else {
5095 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00005096 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00005097 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005098
5099 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005100
Chris Lattner1085bdf2002-11-04 16:18:53 +00005101 // Scan to the end of the allocation instructions, to skip over a block of
5102 // allocas if possible...
5103 //
5104 BasicBlock::iterator It = New;
5105 while (isa<AllocationInst>(*It)) ++It;
5106
5107 // Now that I is pointing to the first non-allocation-inst in the block,
5108 // insert our getelementptr instruction...
5109 //
Chris Lattner809dfac2005-05-04 19:10:26 +00005110 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5111 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5112 New->getName()+".sub", It);
Chris Lattner1085bdf2002-11-04 16:18:53 +00005113
5114 // Now make everything use the getelementptr instead of the original
5115 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00005116 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00005117 } else if (isa<UndefValue>(AI.getArraySize())) {
5118 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00005119 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00005120
5121 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5122 // Note that we only do this for alloca's, because malloc should allocate and
5123 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00005124 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00005125 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00005126 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5127
Chris Lattner1085bdf2002-11-04 16:18:53 +00005128 return 0;
5129}
5130
Chris Lattner8427bff2003-12-07 01:24:23 +00005131Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5132 Value *Op = FI.getOperand(0);
5133
5134 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5135 if (CastInst *CI = dyn_cast<CastInst>(Op))
5136 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5137 FI.setOperand(0, CI->getOperand(0));
5138 return &FI;
5139 }
5140
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005141 // free undef -> unreachable.
5142 if (isa<UndefValue>(Op)) {
5143 // Insert a new store to null because we cannot modify the CFG here.
5144 new StoreInst(ConstantBool::True,
5145 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5146 return EraseInstFromFunction(FI);
5147 }
5148
Chris Lattnerf3a36602004-02-28 04:57:37 +00005149 // If we have 'free null' delete the instruction. This can happen in stl code
5150 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005151 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00005152 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00005153
Chris Lattner8427bff2003-12-07 01:24:23 +00005154 return 0;
5155}
5156
5157
Chris Lattner72684fe2005-01-31 05:51:45 +00005158/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00005159static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5160 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005161 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00005162
5163 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005164 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00005165 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005166
5167 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5168 // If the source is an array, the code below will not succeed. Check to
5169 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5170 // constants.
5171 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5172 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5173 if (ASrcTy->getNumElements() != 0) {
5174 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5175 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5176 SrcTy = cast<PointerType>(CastOp->getType());
5177 SrcPTy = SrcTy->getElementType();
5178 }
5179
5180 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00005181 // Do not allow turning this into a load of an integer, which is then
5182 // casted to a pointer, this pessimizes pointer analysis a lot.
5183 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005184 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005185 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00005186
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00005187 // Okay, we are casting from one integer or pointer type to another of
5188 // the same size. Instead of casting the pointer before the load, cast
5189 // the result of the loaded value.
5190 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5191 CI->getName(),
5192 LI.isVolatile()),LI);
5193 // Now cast the result of the load.
5194 return new CastInst(NewLoad, LI.getType());
5195 }
Chris Lattner35e24772004-07-13 01:49:43 +00005196 }
5197 }
5198 return 0;
5199}
5200
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005201/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00005202/// from this value cannot trap. If it is not obviously safe to load from the
5203/// specified pointer, we do a quick local scan of the basic block containing
5204/// ScanFrom, to determine if the address is already accessed.
5205static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5206 // If it is an alloca or global variable, it is always safe to load from.
5207 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5208
5209 // Otherwise, be a little bit agressive by scanning the local block where we
5210 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005211 // from/to. If so, the previous load or store would have already trapped,
5212 // so there is no harm doing an extra load (also, CSE will later eliminate
5213 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00005214 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5215
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005216 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00005217 --BBI;
5218
5219 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5220 if (LI->getOperand(0) == V) return true;
5221 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5222 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005223
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00005224 }
Chris Lattnere6f13092004-09-19 19:18:10 +00005225 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005226}
5227
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005228Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5229 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00005230
Chris Lattnera9d84e32005-05-01 04:24:53 +00005231 // load (cast X) --> cast (load X) iff safe
5232 if (CastInst *CI = dyn_cast<CastInst>(Op))
5233 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5234 return Res;
5235
5236 // None of the following transforms are legal for volatile loads.
5237 if (LI.isVolatile()) return 0;
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005238
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005239 if (&LI.getParent()->front() != &LI) {
5240 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005241 // If the instruction immediately before this is a store to the same
5242 // address, do a simple form of store->load forwarding.
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005243 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5244 if (SI->getOperand(1) == LI.getOperand(0))
5245 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattnere0bfdf12005-09-12 22:21:03 +00005246 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5247 if (LIB->getOperand(0) == LI.getOperand(0))
5248 return ReplaceInstUsesWith(LI, LIB);
Chris Lattnerb990f7d2005-09-12 22:00:15 +00005249 }
Chris Lattnera9d84e32005-05-01 04:24:53 +00005250
5251 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5252 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5253 isa<UndefValue>(GEPI->getOperand(0))) {
5254 // Insert a new store to null instruction before the load to indicate
5255 // that this code is not reachable. We do this instead of inserting
5256 // an unreachable instruction directly because we cannot modify the
5257 // CFG.
5258 new StoreInst(UndefValue::get(LI.getType()),
5259 Constant::getNullValue(Op->getType()), &LI);
5260 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5261 }
5262
Chris Lattner81a7a232004-10-16 18:11:37 +00005263 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattnera9d84e32005-05-01 04:24:53 +00005264 // load null/undef -> undef
5265 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005266 // Insert a new store to null instruction before the load to indicate that
5267 // this code is not reachable. We do this instead of inserting an
5268 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattnera9d84e32005-05-01 04:24:53 +00005269 new StoreInst(UndefValue::get(LI.getType()),
5270 Constant::getNullValue(Op->getType()), &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00005271 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00005272 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005273
Chris Lattner81a7a232004-10-16 18:11:37 +00005274 // Instcombine load (constant global) into the value loaded.
5275 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5276 if (GV->isConstant() && !GV->isExternal())
5277 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00005278
Chris Lattner81a7a232004-10-16 18:11:37 +00005279 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5280 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5281 if (CE->getOpcode() == Instruction::GetElementPtr) {
5282 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5283 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0b011ec2005-09-26 05:28:06 +00005284 if (Constant *V =
5285 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattner81a7a232004-10-16 18:11:37 +00005286 return ReplaceInstUsesWith(LI, V);
Chris Lattnera9d84e32005-05-01 04:24:53 +00005287 if (CE->getOperand(0)->isNullValue()) {
5288 // Insert a new store to null instruction before the load to indicate
5289 // that this code is not reachable. We do this instead of inserting
5290 // an unreachable instruction directly because we cannot modify the
5291 // CFG.
5292 new StoreInst(UndefValue::get(LI.getType()),
5293 Constant::getNullValue(Op->getType()), &LI);
5294 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5295 }
5296
Chris Lattner81a7a232004-10-16 18:11:37 +00005297 } else if (CE->getOpcode() == Instruction::Cast) {
5298 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5299 return Res;
5300 }
5301 }
Chris Lattnere228ee52004-04-08 20:39:49 +00005302
Chris Lattnera9d84e32005-05-01 04:24:53 +00005303 if (Op->hasOneUse()) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005304 // Change select and PHI nodes to select values instead of addresses: this
5305 // helps alias analysis out a lot, allows many others simplifications, and
5306 // exposes redundancy in the code.
5307 //
5308 // Note that we cannot do the transformation unless we know that the
5309 // introduced loads cannot trap! Something like this is valid as long as
5310 // the condition is always false: load (select bool %C, int* null, int* %G),
5311 // but it would not be valid if we transformed it to load from null
5312 // unconditionally.
5313 //
5314 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5315 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00005316 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5317 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005318 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00005319 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005320 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00005321 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005322 return new SelectInst(SI->getCondition(), V1, V2);
5323 }
5324
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00005325 // load (select (cond, null, P)) -> load P
5326 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5327 if (C->isNullValue()) {
5328 LI.setOperand(0, SI->getOperand(2));
5329 return &LI;
5330 }
5331
5332 // load (select (cond, P, null)) -> load P
5333 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5334 if (C->isNullValue()) {
5335 LI.setOperand(0, SI->getOperand(1));
5336 return &LI;
5337 }
5338
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005339 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5340 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00005341 bool Safe = PN->getParent() == LI.getParent();
5342
5343 // Scan all of the instructions between the PHI and the load to make
5344 // sure there are no instructions that might possibly alter the value
5345 // loaded from the PHI.
5346 if (Safe) {
5347 BasicBlock::iterator I = &LI;
5348 for (--I; !isa<PHINode>(I); --I)
5349 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5350 Safe = false;
5351 break;
5352 }
5353 }
5354
5355 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00005356 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00005357 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005358 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00005359
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00005360 if (Safe) {
5361 // Create the PHI.
5362 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5363 InsertNewInstBefore(NewPN, *PN);
5364 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5365
5366 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5367 BasicBlock *BB = PN->getIncomingBlock(i);
5368 Value *&TheLoad = LoadMap[BB];
5369 if (TheLoad == 0) {
5370 Value *InVal = PN->getIncomingValue(i);
5371 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5372 InVal->getName()+".val"),
5373 *BB->getTerminator());
5374 }
5375 NewPN->addIncoming(TheLoad, BB);
5376 }
5377 return ReplaceInstUsesWith(LI, NewPN);
5378 }
5379 }
5380 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00005381 return 0;
5382}
5383
Chris Lattner72684fe2005-01-31 05:51:45 +00005384/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5385/// when possible.
5386static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5387 User *CI = cast<User>(SI.getOperand(1));
5388 Value *CastOp = CI->getOperand(0);
5389
5390 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5391 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5392 const Type *SrcPTy = SrcTy->getElementType();
5393
5394 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5395 // If the source is an array, the code below will not succeed. Check to
5396 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5397 // constants.
5398 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5399 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5400 if (ASrcTy->getNumElements() != 0) {
5401 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5402 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5403 SrcTy = cast<PointerType>(CastOp->getType());
5404 SrcPTy = SrcTy->getElementType();
5405 }
5406
5407 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00005408 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00005409 IC.getTargetData().getTypeSize(DestPTy)) {
5410
5411 // Okay, we are casting from one integer or pointer type to another of
5412 // the same size. Instead of casting the pointer before the store, cast
5413 // the value to be stored.
5414 Value *NewCast;
5415 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5416 NewCast = ConstantExpr::getCast(C, SrcPTy);
5417 else
5418 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5419 SrcPTy,
5420 SI.getOperand(0)->getName()+".c"), SI);
5421
5422 return new StoreInst(NewCast, CastOp);
5423 }
5424 }
5425 }
5426 return 0;
5427}
5428
Chris Lattner31f486c2005-01-31 05:36:43 +00005429Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5430 Value *Val = SI.getOperand(0);
5431 Value *Ptr = SI.getOperand(1);
5432
5433 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5434 removeFromWorkList(&SI);
5435 SI.eraseFromParent();
5436 ++NumCombined;
5437 return 0;
5438 }
5439
5440 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5441
5442 // store X, null -> turns into 'unreachable' in SimplifyCFG
5443 if (isa<ConstantPointerNull>(Ptr)) {
5444 if (!isa<UndefValue>(Val)) {
5445 SI.setOperand(0, UndefValue::get(Val->getType()));
5446 if (Instruction *U = dyn_cast<Instruction>(Val))
5447 WorkList.push_back(U); // Dropped a use.
5448 ++NumCombined;
5449 }
5450 return 0; // Do not modify these!
5451 }
5452
5453 // store undef, Ptr -> noop
5454 if (isa<UndefValue>(Val)) {
5455 removeFromWorkList(&SI);
5456 SI.eraseFromParent();
5457 ++NumCombined;
5458 return 0;
5459 }
5460
Chris Lattner72684fe2005-01-31 05:51:45 +00005461 // If the pointer destination is a cast, see if we can fold the cast into the
5462 // source instead.
5463 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5464 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5465 return Res;
5466 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5467 if (CE->getOpcode() == Instruction::Cast)
5468 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5469 return Res;
5470
Chris Lattner219175c2005-09-12 23:23:25 +00005471
5472 // If this store is the last instruction in the basic block, and if the block
5473 // ends with an unconditional branch, try to move it to the successor block.
5474 BasicBlock::iterator BBI = &SI; ++BBI;
5475 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5476 if (BI->isUnconditional()) {
5477 // Check to see if the successor block has exactly two incoming edges. If
5478 // so, see if the other predecessor contains a store to the same location.
5479 // if so, insert a PHI node (if needed) and move the stores down.
5480 BasicBlock *Dest = BI->getSuccessor(0);
5481
5482 pred_iterator PI = pred_begin(Dest);
5483 BasicBlock *Other = 0;
5484 if (*PI != BI->getParent())
5485 Other = *PI;
5486 ++PI;
5487 if (PI != pred_end(Dest)) {
5488 if (*PI != BI->getParent())
5489 if (Other)
5490 Other = 0;
5491 else
5492 Other = *PI;
5493 if (++PI != pred_end(Dest))
5494 Other = 0;
5495 }
5496 if (Other) { // If only one other pred...
5497 BBI = Other->getTerminator();
5498 // Make sure this other block ends in an unconditional branch and that
5499 // there is an instruction before the branch.
5500 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5501 BBI != Other->begin()) {
5502 --BBI;
5503 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5504
5505 // If this instruction is a store to the same location.
5506 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5507 // Okay, we know we can perform this transformation. Insert a PHI
5508 // node now if we need it.
5509 Value *MergedVal = OtherStore->getOperand(0);
5510 if (MergedVal != SI.getOperand(0)) {
5511 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5512 PN->reserveOperandSpace(2);
5513 PN->addIncoming(SI.getOperand(0), SI.getParent());
5514 PN->addIncoming(OtherStore->getOperand(0), Other);
5515 MergedVal = InsertNewInstBefore(PN, Dest->front());
5516 }
5517
5518 // Advance to a place where it is safe to insert the new store and
5519 // insert it.
5520 BBI = Dest->begin();
5521 while (isa<PHINode>(BBI)) ++BBI;
5522 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5523 OtherStore->isVolatile()), *BBI);
5524
5525 // Nuke the old stores.
5526 removeFromWorkList(&SI);
5527 removeFromWorkList(OtherStore);
5528 SI.eraseFromParent();
5529 OtherStore->eraseFromParent();
5530 ++NumCombined;
5531 return 0;
5532 }
5533 }
5534 }
5535 }
5536
Chris Lattner31f486c2005-01-31 05:36:43 +00005537 return 0;
5538}
5539
5540
Chris Lattner9eef8a72003-06-04 04:46:00 +00005541Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5542 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4fdd96c2005-06-18 17:37:34 +00005543 Value *X = 0;
Chris Lattnerd4252a72004-07-30 07:50:03 +00005544 BasicBlock *TrueDest;
5545 BasicBlock *FalseDest;
5546 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5547 !isa<Constant>(X)) {
5548 // Swap Destinations and condition...
5549 BI.setCondition(X);
5550 BI.setSuccessor(0, FalseDest);
5551 BI.setSuccessor(1, TrueDest);
5552 return &BI;
5553 }
5554
5555 // Cannonicalize setne -> seteq
5556 Instruction::BinaryOps Op; Value *Y;
5557 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5558 TrueDest, FalseDest)))
5559 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5560 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5561 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5562 std::string Name = I->getName(); I->setName("");
5563 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5564 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00005565 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00005566 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00005567 BI.setSuccessor(0, FalseDest);
5568 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00005569 removeFromWorkList(I);
5570 I->getParent()->getInstList().erase(I);
5571 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00005572 return &BI;
5573 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00005574
Chris Lattner9eef8a72003-06-04 04:46:00 +00005575 return 0;
5576}
Chris Lattner1085bdf2002-11-04 16:18:53 +00005577
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005578Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5579 Value *Cond = SI.getCondition();
5580 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5581 if (I->getOpcode() == Instruction::Add)
5582 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5583 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5584 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00005585 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00005586 AddRHS));
5587 SI.setOperand(0, I->getOperand(0));
5588 WorkList.push_back(I);
5589 return &SI;
5590 }
5591 }
5592 return 0;
5593}
5594
Chris Lattnerca081252001-12-14 16:52:21 +00005595
Chris Lattner99f48c62002-09-02 04:59:56 +00005596void InstCombiner::removeFromWorkList(Instruction *I) {
5597 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5598 WorkList.end());
5599}
5600
Chris Lattner39c98bb2004-12-08 23:43:58 +00005601
5602/// TryToSinkInstruction - Try to move the specified instruction from its
5603/// current block into the beginning of DestBlock, which can only happen if it's
5604/// safe to move the instruction past all of the instructions between it and the
5605/// end of its block.
5606static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5607 assert(I->hasOneUse() && "Invariants didn't hold!");
5608
5609 // Cannot move control-flow-involving instructions.
5610 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005611
Chris Lattner39c98bb2004-12-08 23:43:58 +00005612 // Do not sink alloca instructions out of the entry block.
5613 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5614 return false;
5615
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005616 // We can only sink load instructions if there is nothing between the load and
5617 // the end of block that could change the value.
5618 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5619 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5620
5621 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5622 Scan != E; ++Scan)
5623 if (Scan->mayWriteToMemory())
5624 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005625 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005626
5627 BasicBlock::iterator InsertPos = DestBlock->begin();
5628 while (isa<PHINode>(InsertPos)) ++InsertPos;
5629
Chris Lattner9f269e42005-08-08 19:11:57 +00005630 I->moveBefore(InsertPos);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005631 ++NumSunkInst;
5632 return true;
5633}
5634
Chris Lattner113f4f42002-06-25 16:13:24 +00005635bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005636 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005637 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005638
Chris Lattner4ed40f72005-07-07 20:40:38 +00005639 {
5640 // Populate the worklist with the reachable instructions.
5641 std::set<BasicBlock*> Visited;
5642 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5643 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5644 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5645 WorkList.push_back(I);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005646
Chris Lattner4ed40f72005-07-07 20:40:38 +00005647 // Do a quick scan over the function. If we find any blocks that are
5648 // unreachable, remove any instructions inside of them. This prevents
5649 // the instcombine code from having to deal with some bad special cases.
5650 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5651 if (!Visited.count(BB)) {
5652 Instruction *Term = BB->getTerminator();
5653 while (Term != BB->begin()) { // Remove instrs bottom-up
5654 BasicBlock::iterator I = Term; --I;
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005655
Chris Lattner4ed40f72005-07-07 20:40:38 +00005656 DEBUG(std::cerr << "IC: DCE: " << *I);
5657 ++NumDeadInst;
5658
5659 if (!I->use_empty())
5660 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5661 I->eraseFromParent();
5662 }
5663 }
5664 }
Chris Lattnerca081252001-12-14 16:52:21 +00005665
5666 while (!WorkList.empty()) {
5667 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5668 WorkList.pop_back();
5669
Misha Brukman632df282002-10-29 23:06:16 +00005670 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005671 // Check to see if we can DIE the instruction...
5672 if (isInstructionTriviallyDead(I)) {
5673 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005674 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005675 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005676 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005677
Chris Lattnercd517ff2005-01-28 19:32:01 +00005678 DEBUG(std::cerr << "IC: DCE: " << *I);
5679
5680 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005681 removeFromWorkList(I);
5682 continue;
5683 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005684
Misha Brukman632df282002-10-29 23:06:16 +00005685 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005686 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005687 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005688 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005689 cast<Constant>(Ptr)->isNullValue() &&
5690 !isa<ConstantPointerNull>(C) &&
5691 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005692 // If this is a constant expr gep that is effectively computing an
5693 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5694 bool isFoldableGEP = true;
5695 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5696 if (!isa<ConstantInt>(I->getOperand(i)))
5697 isFoldableGEP = false;
5698 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005699 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005700 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5701 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005702 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005703 C = ConstantExpr::getCast(C, I->getType());
5704 }
5705 }
5706
Chris Lattnercd517ff2005-01-28 19:32:01 +00005707 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5708
Chris Lattner99f48c62002-09-02 04:59:56 +00005709 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005710 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005711 ReplaceInstUsesWith(*I, C);
5712
Chris Lattner99f48c62002-09-02 04:59:56 +00005713 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005714 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005715 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005716 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005717 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005718
Chris Lattner39c98bb2004-12-08 23:43:58 +00005719 // See if we can trivially sink this instruction to a successor basic block.
5720 if (I->hasOneUse()) {
5721 BasicBlock *BB = I->getParent();
5722 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5723 if (UserParent != BB) {
5724 bool UserIsSuccessor = false;
5725 // See if the user is one of our successors.
5726 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5727 if (*SI == UserParent) {
5728 UserIsSuccessor = true;
5729 break;
5730 }
5731
5732 // If the user is one of our immediate successors, and if that successor
5733 // only has us as a predecessors (we'd have to split the critical edge
5734 // otherwise), we can keep going.
5735 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5736 next(pred_begin(UserParent)) == pred_end(UserParent))
5737 // Okay, the CFG is simple enough, try to sink this instruction.
5738 Changed |= TryToSinkInstruction(I, UserParent);
5739 }
5740 }
5741
Chris Lattnerca081252001-12-14 16:52:21 +00005742 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005743 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005744 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005745 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005746 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005747 DEBUG(std::cerr << "IC: Old = " << *I
5748 << " New = " << *Result);
5749
Chris Lattner396dbfe2004-06-09 05:08:07 +00005750 // Everything uses the new instruction now.
5751 I->replaceAllUsesWith(Result);
5752
5753 // Push the new instruction and any users onto the worklist.
5754 WorkList.push_back(Result);
5755 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005756
5757 // Move the name to the new instruction first...
5758 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005759 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005760
5761 // Insert the new instruction into the basic block...
5762 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005763 BasicBlock::iterator InsertPos = I;
5764
5765 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5766 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5767 ++InsertPos;
5768
5769 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005770
Chris Lattner63d75af2004-05-01 23:27:23 +00005771 // Make sure that we reprocess all operands now that we reduced their
5772 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005773 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5774 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5775 WorkList.push_back(OpI);
5776
Chris Lattner396dbfe2004-06-09 05:08:07 +00005777 // Instructions can end up on the worklist more than once. Make sure
5778 // we do not process an instruction that has been deleted.
5779 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005780
5781 // Erase the old instruction.
5782 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005783 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005784 DEBUG(std::cerr << "IC: MOD = " << *I);
5785
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005786 // If the instruction was modified, it's possible that it is now dead.
5787 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005788 if (isInstructionTriviallyDead(I)) {
5789 // Make sure we process all operands now that we are reducing their
5790 // use counts.
5791 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5792 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5793 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005794
Chris Lattner63d75af2004-05-01 23:27:23 +00005795 // Instructions may end up in the worklist more than once. Erase all
5796 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005797 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005798 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005799 } else {
5800 WorkList.push_back(Result);
5801 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005802 }
Chris Lattner053c0932002-05-14 15:24:07 +00005803 }
Chris Lattner260ab202002-04-18 17:39:14 +00005804 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005805 }
5806 }
5807
Chris Lattner260ab202002-04-18 17:39:14 +00005808 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005809}
5810
Brian Gaeke38b79e82004-07-27 17:43:21 +00005811FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005812 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005813}
Brian Gaeke960707c2003-11-11 22:41:34 +00005814