blob: 5a2e4ef177e7567f8fc3849adbef8c060978ce15 [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 Lattner60a65912002-02-12 21:07:25 +000048#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000054using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000055using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000056
Chris Lattner260ab202002-04-18 17:39:14 +000057namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000058 Statistic<> NumCombined ("instcombine", "Number of insts combined");
59 Statistic<> NumConstProp("instcombine", "Number of constant folds");
60 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000061 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000062
Chris Lattnerc8e66542002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000068
Chris Lattner51ea1272004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner51ea1272004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner99f48c62002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000090 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000092
Chris Lattnerf12cc842002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 }
97
Chris Lattner69193f92004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattner260ab202002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanb1c93172005-04-21 23:48:37 +0000106 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Reid Spencer279fa252004-11-28 21:31:15 +0000116 Instruction *visitSetCondInstWithCastAndConstant(BinaryOperator&I,
117 CastInst*LHSI,
118 ConstantInt* CI);
Chris Lattner0798af32005-01-13 20:14:25 +0000119 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000121 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000122 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000123 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000125 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000126 Instruction *visitCallInst(CallInst &CI);
127 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitPHINode(PHINode &PN);
129 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000130 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000131 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000132 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner31f486c2005-01-31 05:36:43 +0000133 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000134 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000135 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000136
137 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000138 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000139
Chris Lattner970c33a2003-06-19 17:00:31 +0000140 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000141 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000142 bool transformConstExprCastCall(CallSite CS);
143
Chris Lattner69193f92004-04-05 01:30:19 +0000144 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000145 // InsertNewInstBefore - insert an instruction New before instruction Old
146 // in the program. Add the new instruction to the worklist.
147 //
Chris Lattner623826c2004-09-28 21:48:02 +0000148 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000149 assert(New && New->getParent() == 0 &&
150 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000151 BasicBlock *BB = Old.getParent();
152 BB->getInstList().insert(&Old, New); // Insert inst
153 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000154 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000155 }
156
Chris Lattner7e794272004-09-24 15:21:34 +0000157 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
158 /// This also adds the cast to the worklist. Finally, this returns the
159 /// cast.
160 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
161 if (V->getType() == Ty) return V;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000162
Chris Lattner7e794272004-09-24 15:21:34 +0000163 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
164 WorkList.push_back(C);
165 return C;
166 }
167
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000168 // ReplaceInstUsesWith - This method is to be used when an instruction is
169 // found to be dead, replacable with another preexisting expression. Here
170 // we add all uses of I to the worklist, replace all uses of I with the new
171 // value, then return I, so that the inst combiner will know that I was
172 // modified.
173 //
174 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000175 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000176 if (&I != V) {
177 I.replaceAllUsesWith(V);
178 return &I;
179 } else {
180 // If we are replacing the instruction with itself, this must be in a
181 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000182 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000183 return &I;
184 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000185 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000186
187 // EraseInstFromFunction - When dealing with an instruction that has side
188 // effects or produces a void value, we can't rely on DCE to delete the
189 // instruction. Instead, visit methods should return the value returned by
190 // this function.
191 Instruction *EraseInstFromFunction(Instruction &I) {
192 assert(I.use_empty() && "Cannot erase instruction that is used!");
193 AddUsesToWorkList(I);
194 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000195 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000196 return 0; // Don't do anything with FI
197 }
198
199
Chris Lattner3ac7c262003-08-13 20:16:26 +0000200 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000201 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
202 /// InsertBefore instruction. This is specialized a bit to avoid inserting
203 /// casts that are known to not do anything...
204 ///
205 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
206 Instruction *InsertBefore);
207
Chris Lattner7fb29e12003-03-11 00:12:48 +0000208 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000209 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000210 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000211
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000212
213 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
214 // PHI node as operand #0, see if we can fold the instruction into the PHI
215 // (which is only possible if all operands to the PHI are constants).
216 Instruction *FoldOpIntoPhi(Instruction &I);
217
Chris Lattner7515cab2004-11-14 19:13:23 +0000218 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
219 // operator and they all are only used by the PHI, PHI together their
220 // inputs, and do the operation once, to the result of the PHI.
221 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
222
Chris Lattnerba1cb382003-09-19 17:17:26 +0000223 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
224 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000225
226 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
227 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000228 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000229
Chris Lattnerc8b70922002-07-26 21:12:46 +0000230 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000231}
232
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000233// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000234// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000235static unsigned getComplexity(Value *V) {
236 if (isa<Instruction>(V)) {
237 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000238 return 3;
239 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000240 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000241 if (isa<Argument>(V)) return 3;
242 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000243}
Chris Lattner260ab202002-04-18 17:39:14 +0000244
Chris Lattner7fb29e12003-03-11 00:12:48 +0000245// isOnlyUse - Return true if this instruction will be deleted if we stop using
246// it.
247static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000248 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000249}
250
Chris Lattnere79e8542004-02-23 06:38:22 +0000251// getPromotedType - Return the specified type promoted as it would be to pass
252// though a va_arg area...
253static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000254 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000255 case Type::SByteTyID:
256 case Type::ShortTyID: return Type::IntTy;
257 case Type::UByteTyID:
258 case Type::UShortTyID: return Type::UIntTy;
259 case Type::FloatTyID: return Type::DoubleTy;
260 default: return Ty;
261 }
262}
263
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000264// SimplifyCommutative - This performs a few simplifications for commutative
265// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000266//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000267// 1. Order operands such that they are listed from right (least complex) to
268// left (most complex). This puts constants before unary operators before
269// binary operators.
270//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000271// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
272// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000273//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000274bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000275 bool Changed = false;
276 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
277 Changed = !I.swapOperands();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000278
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000279 if (!I.isAssociative()) return Changed;
280 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000281 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
282 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
283 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000284 Constant *Folded = ConstantExpr::get(I.getOpcode(),
285 cast<Constant>(I.getOperand(1)),
286 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000287 I.setOperand(0, Op->getOperand(0));
288 I.setOperand(1, Folded);
289 return true;
290 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
291 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
292 isOnlyUse(Op) && isOnlyUse(Op1)) {
293 Constant *C1 = cast<Constant>(Op->getOperand(1));
294 Constant *C2 = cast<Constant>(Op1->getOperand(1));
295
296 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000297 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000298 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
299 Op1->getOperand(0),
300 Op1->getName(), &I);
301 WorkList.push_back(New);
302 I.setOperand(0, New);
303 I.setOperand(1, Folded);
304 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000305 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000306 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000307 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000308}
Chris Lattnerca081252001-12-14 16:52:21 +0000309
Chris Lattnerbb74e222003-03-10 23:06:50 +0000310// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
311// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000312//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000313static inline Value *dyn_castNegVal(Value *V) {
314 if (BinaryOperator::isNeg(V))
315 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
316
Chris Lattner9ad0d552004-12-14 20:08:06 +0000317 // Constants can be considered to be negated values if they can be folded.
318 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
319 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000320 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000321}
322
Chris Lattnerbb74e222003-03-10 23:06:50 +0000323static inline Value *dyn_castNotVal(Value *V) {
324 if (BinaryOperator::isNot(V))
325 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
326
327 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000328 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000329 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000330 return 0;
331}
332
Chris Lattner7fb29e12003-03-11 00:12:48 +0000333// dyn_castFoldableMul - If this value is a multiply that can be folded into
334// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000335// non-constant operand of the multiply, and set CST to point to the multiplier.
336// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000338static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000339 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000340 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000341 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000342 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000343 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000344 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000345 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000346 // The multiplier is really 1 << CST.
347 Constant *One = ConstantInt::get(V->getType(), 1);
348 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
349 return I->getOperand(0);
350 }
351 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000352 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000353}
Chris Lattner31ae8632002-08-14 17:51:49 +0000354
Chris Lattner0798af32005-01-13 20:14:25 +0000355/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
356/// expression, return it.
357static User *dyn_castGetElementPtr(Value *V) {
358 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
360 if (CE->getOpcode() == Instruction::GetElementPtr)
361 return cast<User>(V);
362 return false;
363}
364
Chris Lattner3082c5a2003-02-18 19:28:33 +0000365// Log2 - Calculate the log base 2 for the specified value if it is exactly a
366// power of 2.
367static unsigned Log2(uint64_t Val) {
368 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
369 unsigned Count = 0;
370 while (Val != 1) {
371 if (Val & 1) return 0; // Multiple bits set?
372 Val >>= 1;
373 ++Count;
374 }
375 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000376}
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
388// isTrueWhenEqual - Return true if the specified setcondinst instruction is
389// true when both operands are equal...
390//
391static bool isTrueWhenEqual(Instruction &I) {
392 return I.getOpcode() == Instruction::SetEQ ||
393 I.getOpcode() == Instruction::SetGE ||
394 I.getOpcode() == Instruction::SetLE;
395}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000396
397/// AssociativeOpt - Perform an optimization on an associative operator. This
398/// function is designed to check a chain of associative operators for a
399/// potential to apply a certain optimization. Since the optimization may be
400/// applicable if the expression was reassociated, this checks the chain, then
401/// reassociates the expression as necessary to expose the optimization
402/// opportunity. This makes use of a special Functor, which must define
403/// 'shouldApply' and 'apply' methods.
404///
405template<typename Functor>
406Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
407 unsigned Opcode = Root.getOpcode();
408 Value *LHS = Root.getOperand(0);
409
410 // Quick check, see if the immediate LHS matches...
411 if (F.shouldApply(LHS))
412 return F.apply(Root);
413
414 // Otherwise, if the LHS is not of the same opcode as the root, return.
415 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000416 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000417 // Should we apply this transform to the RHS?
418 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
419
420 // If not to the RHS, check to see if we should apply to the LHS...
421 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
422 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
423 ShouldApply = true;
424 }
425
426 // If the functor wants to apply the optimization to the RHS of LHSI,
427 // reassociate the expression from ((? op A) op B) to (? op (A op B))
428 if (ShouldApply) {
429 BasicBlock *BB = Root.getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000430
Chris Lattnerb8b97502003-08-13 19:01:45 +0000431 // Now all of the instructions are in the current basic block, go ahead
432 // and perform the reassociation.
433 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
434
435 // First move the selected RHS to the LHS of the root...
436 Root.setOperand(0, LHSI->getOperand(1));
437
438 // Make what used to be the LHS of the root be the user of the root...
439 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000440 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000441 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
442 return 0;
443 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000444 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000445 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000446 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
447 BasicBlock::iterator ARI = &Root; ++ARI;
448 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
449 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000450
451 // Now propagate the ExtraOperand down the chain of instructions until we
452 // get to LHSI.
453 while (TmpLHSI != LHSI) {
454 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000455 // Move the instruction to immediately before the chain we are
456 // constructing to avoid breaking dominance properties.
457 NextLHSI->getParent()->getInstList().remove(NextLHSI);
458 BB->getInstList().insert(ARI, NextLHSI);
459 ARI = NextLHSI;
460
Chris Lattnerb8b97502003-08-13 19:01:45 +0000461 Value *NextOp = NextLHSI->getOperand(1);
462 NextLHSI->setOperand(1, ExtraOperand);
463 TmpLHSI = NextLHSI;
464 ExtraOperand = NextOp;
465 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000466
Chris Lattnerb8b97502003-08-13 19:01:45 +0000467 // Now that the instructions are reassociated, have the functor perform
468 // the transformation...
469 return F.apply(Root);
470 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000471
Chris Lattnerb8b97502003-08-13 19:01:45 +0000472 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
473 }
474 return 0;
475}
476
477
478// AddRHS - Implements: X + X --> X << 1
479struct AddRHS {
480 Value *RHS;
481 AddRHS(Value *rhs) : RHS(rhs) {}
482 bool shouldApply(Value *LHS) const { return LHS == RHS; }
483 Instruction *apply(BinaryOperator &Add) const {
484 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
485 ConstantInt::get(Type::UByteTy, 1));
486 }
487};
488
489// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
490// iff C1&C2 == 0
491struct AddMaskingAnd {
492 Constant *C2;
493 AddMaskingAnd(Constant *c) : C2(c) {}
494 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000495 ConstantInt *C1;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000496 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattnerd4252a72004-07-30 07:50:03 +0000497 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000498 }
499 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000500 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000501 }
502};
503
Chris Lattner86102b82005-01-01 16:22:27 +0000504static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000505 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000506 if (isa<CastInst>(I)) {
507 if (Constant *SOC = dyn_cast<Constant>(SO))
508 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanb1c93172005-04-21 23:48:37 +0000509
Chris Lattner86102b82005-01-01 16:22:27 +0000510 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
511 SO->getName() + ".cast"), I);
512 }
513
Chris Lattner183b3362004-04-09 19:05:30 +0000514 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000515 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
516 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000517
Chris Lattner183b3362004-04-09 19:05:30 +0000518 if (Constant *SOC = dyn_cast<Constant>(SO)) {
519 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000520 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
521 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000522 }
523
524 Value *Op0 = SO, *Op1 = ConstOperand;
525 if (!ConstIsRHS)
526 std::swap(Op0, Op1);
527 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000528 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
529 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
530 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
531 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000532 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000533 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000534 abort();
535 }
Chris Lattner86102b82005-01-01 16:22:27 +0000536 return IC->InsertNewInstBefore(New, I);
537}
538
539// FoldOpIntoSelect - Given an instruction with a select as one operand and a
540// constant as the other operand, try to fold the binary operator into the
541// select arguments. This also works for Cast instructions, which obviously do
542// not have a second operand.
543static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
544 InstCombiner *IC) {
545 // Don't modify shared select instructions
546 if (!SI->hasOneUse()) return 0;
547 Value *TV = SI->getOperand(1);
548 Value *FV = SI->getOperand(2);
549
550 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner374e6592005-04-21 05:43:13 +0000551 // Bool selects with constant operands can be folded to logical ops.
552 if (SI->getType() == Type::BoolTy) return 0;
553
Chris Lattner86102b82005-01-01 16:22:27 +0000554 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
555 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
556
557 return new SelectInst(SI->getCondition(), SelectTrueVal,
558 SelectFalseVal);
559 }
560 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000561}
562
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000563
564/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
565/// node as operand #0, see if we can fold the instruction into the PHI (which
566/// is only possible if all operands to the PHI are constants).
567Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
568 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000569 unsigned NumPHIValues = PN->getNumIncomingValues();
570 if (!PN->hasOneUse() || NumPHIValues == 0 ||
571 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000572
573 // Check to see if all of the operands of the PHI are constants. If not, we
574 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000575 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000576 if (!isa<Constant>(PN->getIncomingValue(i)))
577 return 0;
578
579 // Okay, we can do the transformation: create the new PHI node.
580 PHINode *NewPN = new PHINode(I.getType(), I.getName());
581 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000582 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000583 InsertNewInstBefore(NewPN, *PN);
584
585 // Next, add all of the operands to the PHI.
586 if (I.getNumOperands() == 2) {
587 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000588 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000589 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
590 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
591 PN->getIncomingBlock(i));
592 }
593 } else {
594 assert(isa<CastInst>(I) && "Unary op should be a cast!");
595 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000596 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000597 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
598 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
599 PN->getIncomingBlock(i));
600 }
601 }
602 return ReplaceInstUsesWith(I, NewPN);
603}
604
Chris Lattner113f4f42002-06-25 16:13:24 +0000605Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000606 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000607 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000608
Chris Lattnercf4a9962004-04-10 22:01:55 +0000609 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000610 // X + undef -> undef
611 if (isa<UndefValue>(RHS))
612 return ReplaceInstUsesWith(I, RHS);
613
Chris Lattnercf4a9962004-04-10 22:01:55 +0000614 // X + 0 --> X
615 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
616 RHSC->isNullValue())
617 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000618
Chris Lattnercf4a9962004-04-10 22:01:55 +0000619 // X + (signbit) --> X ^ signbit
620 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
621 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
622 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000623 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000624 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000625 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000626
627 if (isa<PHINode>(LHS))
628 if (Instruction *NV = FoldOpIntoPhi(I))
629 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000630 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000631
Chris Lattnerb8b97502003-08-13 19:01:45 +0000632 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000633 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000634 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner47060462005-04-07 17:14:51 +0000635
636 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
637 if (RHSI->getOpcode() == Instruction::Sub)
638 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
639 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
640 }
641 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
642 if (LHSI->getOpcode() == Instruction::Sub)
643 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
644 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
645 }
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000646 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000647
Chris Lattner147e9752002-05-08 22:46:53 +0000648 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000649 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000650 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000651
652 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000653 if (!isa<Constant>(RHS))
654 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000655 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000656
Misha Brukmanb1c93172005-04-21 23:48:37 +0000657
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000658 ConstantInt *C2;
659 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
660 if (X == RHS) // X*C + X --> X * (C+1)
661 return BinaryOperator::createMul(RHS, AddOne(C2));
662
663 // X*C1 + X*C2 --> X * (C1+C2)
664 ConstantInt *C1;
665 if (X == dyn_castFoldableMul(RHS, C1))
666 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000667 }
668
669 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000670 if (dyn_castFoldableMul(RHS, C2) == LHS)
671 return BinaryOperator::createMul(LHS, AddOne(C2));
672
Chris Lattner57c8d992003-02-18 19:57:07 +0000673
Chris Lattnerb8b97502003-08-13 19:01:45 +0000674 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000675 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000676 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000677
Chris Lattnerb9cde762003-10-02 15:11:26 +0000678 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000679 Value *X;
680 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
681 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
682 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000683 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000684
Chris Lattnerbff91d92004-10-08 05:07:56 +0000685 // (X & FF00) + xx00 -> (X+xx00) & FF00
686 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
687 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
688 if (Anded == CRHS) {
689 // See if all bits from the first bit set in the Add RHS up are included
690 // in the mask. First, get the rightmost bit.
691 uint64_t AddRHSV = CRHS->getRawValue();
692
693 // Form a mask of all bits from the lowest bit added through the top.
694 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
695 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
696
697 // See if the and mask includes all of these bits.
698 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000699
Chris Lattnerbff91d92004-10-08 05:07:56 +0000700 if (AddRHSHighBits == AddRHSHighBitsAnd) {
701 // Okay, the xform is safe. Insert the new add pronto.
702 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
703 LHS->getName()), I);
704 return BinaryOperator::createAnd(NewAdd, C2);
705 }
706 }
707 }
708
Chris Lattnerd4252a72004-07-30 07:50:03 +0000709 // Try to fold constant add into select arguments.
710 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000711 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000712 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000713 }
714
Chris Lattner113f4f42002-06-25 16:13:24 +0000715 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000716}
717
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000718// isSignBit - Return true if the value represented by the constant only has the
719// highest order bit set.
720static bool isSignBit(ConstantInt *CI) {
721 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
722 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
723}
724
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000725static unsigned getTypeSizeInBits(const Type *Ty) {
726 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
727}
728
Chris Lattner022167f2004-03-13 00:11:49 +0000729/// RemoveNoopCast - Strip off nonconverting casts from the value.
730///
731static Value *RemoveNoopCast(Value *V) {
732 if (CastInst *CI = dyn_cast<CastInst>(V)) {
733 const Type *CTy = CI->getType();
734 const Type *OpTy = CI->getOperand(0)->getType();
735 if (CTy->isInteger() && OpTy->isInteger()) {
736 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
737 return RemoveNoopCast(CI->getOperand(0));
738 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
739 return RemoveNoopCast(CI->getOperand(0));
740 }
741 return V;
742}
743
Chris Lattner113f4f42002-06-25 16:13:24 +0000744Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000745 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000746
Chris Lattnere6794492002-08-12 21:17:25 +0000747 if (Op0 == Op1) // sub X, X -> 0
748 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000749
Chris Lattnere6794492002-08-12 21:17:25 +0000750 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000751 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000752 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000753
Chris Lattner81a7a232004-10-16 18:11:37 +0000754 if (isa<UndefValue>(Op0))
755 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
756 if (isa<UndefValue>(Op1))
757 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
758
Chris Lattner8f2f5982003-11-05 01:06:05 +0000759 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
760 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000761 if (C->isAllOnesValue())
762 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000763
Chris Lattner8f2f5982003-11-05 01:06:05 +0000764 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000765 Value *X;
766 if (match(Op1, m_Not(m_Value(X))))
767 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000768 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000769 // -((uint)X >> 31) -> ((int)X >> 31)
770 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000771 if (C->isNullValue()) {
772 Value *NoopCastedRHS = RemoveNoopCast(Op1);
773 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000774 if (SI->getOpcode() == Instruction::Shr)
775 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
776 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000777 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000778 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000779 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000780 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000781 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000782 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000783 // Ok, the transformation is safe. Insert a cast of the incoming
784 // value, then the new shift, then the new cast.
785 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
786 SI->getOperand(0)->getName());
787 Value *InV = InsertNewInstBefore(FirstCast, I);
788 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
789 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000790 if (NewShift->getType() == I.getType())
791 return NewShift;
792 else {
793 InV = InsertNewInstBefore(NewShift, I);
794 return new CastInst(NewShift, I.getType());
795 }
Chris Lattner92295c52004-03-12 23:53:13 +0000796 }
797 }
Chris Lattner022167f2004-03-13 00:11:49 +0000798 }
Chris Lattner183b3362004-04-09 19:05:30 +0000799
800 // Try to fold constant sub into select arguments.
801 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000802 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000803 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000804
805 if (isa<PHINode>(Op0))
806 if (Instruction *NV = FoldOpIntoPhi(I))
807 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000808 }
809
Chris Lattnera9be4492005-04-07 16:15:25 +0000810 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
811 if (Op1I->getOpcode() == Instruction::Add &&
812 !Op0->getType()->isFloatingPoint()) {
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000813 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000814 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000815 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattnera9be4492005-04-07 16:15:25 +0000816 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattnerc7f3c1a2005-04-07 16:28:01 +0000817 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
818 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
819 // C1-(X+C2) --> (C1-C2)-X
820 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
821 Op1I->getOperand(0));
822 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000823 }
824
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000825 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000826 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
827 // is not used by anyone else...
828 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000829 if (Op1I->getOpcode() == Instruction::Sub &&
830 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000831 // Swap the two operands of the subexpr...
832 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
833 Op1I->setOperand(0, IIOp1);
834 Op1I->setOperand(1, IIOp0);
Misha Brukmanb1c93172005-04-21 23:48:37 +0000835
Chris Lattner3082c5a2003-02-18 19:28:33 +0000836 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000837 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000838 }
839
840 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
841 //
842 if (Op1I->getOpcode() == Instruction::And &&
843 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
844 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
845
Chris Lattner396dbfe2004-06-09 05:08:07 +0000846 Value *NewNot =
847 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000848 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000849 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000850
Chris Lattner0aee4b72004-10-06 15:08:25 +0000851 // -(X sdiv C) -> (X sdiv -C)
852 if (Op1I->getOpcode() == Instruction::Div)
853 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattnera9be4492005-04-07 16:15:25 +0000854 if (CSI->isNullValue())
Chris Lattner0aee4b72004-10-06 15:08:25 +0000855 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanb1c93172005-04-21 23:48:37 +0000856 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner0aee4b72004-10-06 15:08:25 +0000857 ConstantExpr::getNeg(DivRHS));
858
Chris Lattner57c8d992003-02-18 19:57:07 +0000859 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000860 ConstantInt *C2;
861 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanb1c93172005-04-21 23:48:37 +0000862 Constant *CP1 =
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000863 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000864 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000865 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000866 }
Chris Lattnera9be4492005-04-07 16:15:25 +0000867 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000868
Chris Lattner47060462005-04-07 17:14:51 +0000869 if (!Op0->getType()->isFloatingPoint())
870 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
871 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner411336f2005-01-19 21:50:18 +0000872 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
873 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
874 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
875 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner47060462005-04-07 17:14:51 +0000876 } else if (Op0I->getOpcode() == Instruction::Sub) {
877 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
878 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner411336f2005-01-19 21:50:18 +0000879 }
Misha Brukmanb1c93172005-04-21 23:48:37 +0000880
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000881 ConstantInt *C1;
882 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
883 if (X == Op1) { // X*C - X --> X * (C-1)
884 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
885 return BinaryOperator::createMul(Op1, CP1);
886 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000887
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000888 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
889 if (X == dyn_castFoldableMul(Op1, C2))
890 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
891 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000892 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000893}
894
Chris Lattnere79e8542004-02-23 06:38:22 +0000895/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
896/// really just returns true if the most significant (sign) bit is set.
897static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
898 if (RHS->getType()->isSigned()) {
899 // True if source is LHS < 0 or LHS <= -1
900 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
901 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
902 } else {
903 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
904 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
905 // the size of the integer type.
906 if (Opcode == Instruction::SetGE)
907 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
908 if (Opcode == Instruction::SetGT)
909 return RHSC->getValue() ==
910 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
911 }
912 return false;
913}
914
Chris Lattner113f4f42002-06-25 16:13:24 +0000915Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000916 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000917 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000918
Chris Lattner81a7a232004-10-16 18:11:37 +0000919 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
920 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
921
Chris Lattnere6794492002-08-12 21:17:25 +0000922 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000923 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
924 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000925
926 // ((X << C1)*C2) == (X * (C2 << C1))
927 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
928 if (SI->getOpcode() == Instruction::Shl)
929 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000930 return BinaryOperator::createMul(SI->getOperand(0),
931 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanb1c93172005-04-21 23:48:37 +0000932
Chris Lattnercce81be2003-09-11 22:24:54 +0000933 if (CI->isNullValue())
934 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
935 if (CI->equalsInt(1)) // X * 1 == X
936 return ReplaceInstUsesWith(I, Op0);
937 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000938 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000939
Chris Lattnercce81be2003-09-11 22:24:54 +0000940 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000941 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
942 return new ShiftInst(Instruction::Shl, Op0,
943 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000944 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000945 if (Op1F->isNullValue())
946 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000947
Chris Lattner3082c5a2003-02-18 19:28:33 +0000948 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
949 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
950 if (Op1F->getValue() == 1.0)
951 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
952 }
Chris Lattner183b3362004-04-09 19:05:30 +0000953
954 // Try to fold constant mul into select arguments.
955 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000956 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000957 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000958
959 if (isa<PHINode>(Op0))
960 if (Instruction *NV = FoldOpIntoPhi(I))
961 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000962 }
963
Chris Lattner934a64cf2003-03-10 23:23:04 +0000964 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
965 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000966 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000967
Chris Lattner2635b522004-02-23 05:39:21 +0000968 // If one of the operands of the multiply is a cast from a boolean value, then
969 // we know the bool is either zero or one, so this is a 'masking' multiply.
970 // See if we can simplify things based on how the boolean was originally
971 // formed.
972 CastInst *BoolCast = 0;
973 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
974 if (CI->getOperand(0)->getType() == Type::BoolTy)
975 BoolCast = CI;
976 if (!BoolCast)
977 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
978 if (CI->getOperand(0)->getType() == Type::BoolTy)
979 BoolCast = CI;
980 if (BoolCast) {
981 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
982 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
983 const Type *SCOpTy = SCIOp0->getType();
984
Chris Lattnere79e8542004-02-23 06:38:22 +0000985 // If the setcc is true iff the sign bit of X is set, then convert this
986 // multiply into a shift/and combination.
987 if (isa<ConstantInt>(SCIOp1) &&
988 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000989 // Shift the X value right to turn it into "all signbits".
990 Constant *Amt = ConstantUInt::get(Type::UByteTy,
991 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000992 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000993 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000994 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
995 SCIOp0->getName()), I);
996 }
997
998 Value *V =
999 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1000 BoolCast->getOperand(0)->getName()+
1001 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +00001002
1003 // If the multiply type is not the same as the source type, sign extend
1004 // or truncate to the multiply type.
1005 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +00001006 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001007
Chris Lattner2635b522004-02-23 05:39:21 +00001008 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001009 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +00001010 }
1011 }
1012 }
1013
Chris Lattner113f4f42002-06-25 16:13:24 +00001014 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +00001015}
1016
Chris Lattner113f4f42002-06-25 16:13:24 +00001017Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001018 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +00001019
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001020 if (isa<UndefValue>(Op0)) // undef / X -> 0
1021 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1022 if (isa<UndefValue>(Op1))
1023 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1024
1025 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +00001026 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001027 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001028 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001029
Chris Lattnere20c3342004-04-26 14:01:59 +00001030 // div X, -1 == -X
1031 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001032 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +00001033
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001034 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001035 if (LHS->getOpcode() == Instruction::Div)
1036 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001037 // (X / C1) / C2 -> X / (C1*C2)
1038 return BinaryOperator::createDiv(LHS->getOperand(0),
1039 ConstantExpr::getMul(RHS, LHSRHS));
1040 }
1041
Chris Lattner3082c5a2003-02-18 19:28:33 +00001042 // Check to see if this is an unsigned division with an exact power of 2,
1043 // if so, convert to a right shift.
1044 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1045 if (uint64_t Val = C->getValue()) // Don't break X / 0
1046 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001047 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001048 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001049
Chris Lattner4ad08352004-10-09 02:50:40 +00001050 // -X/C -> X/-C
1051 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001052 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001053 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1054
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001055 if (!RHS->isNullValue()) {
1056 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001057 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001058 return R;
1059 if (isa<PHINode>(Op0))
1060 if (Instruction *NV = FoldOpIntoPhi(I))
1061 return NV;
1062 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001063 }
1064
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001065 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1066 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1067 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1068 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1069 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1070 if (STO->getValue() == 0) { // Couldn't be this argument.
1071 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001072 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001073 } else if (SFO->getValue() == 0) {
Chris Lattner42362612005-04-08 04:03:26 +00001074 I.setOperand(2, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001075 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001076 }
1077
Chris Lattner42362612005-04-08 04:03:26 +00001078 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1079 unsigned TSA = 0, FSA = 0;
1080 if ((TVA == 1 || (TSA = Log2(TVA))) && // Log2 fails for 0 & 1.
1081 (FVA == 1 || (FSA = Log2(FVA)))) {
1082 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1083 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1084 TC, SI->getName()+".t");
1085 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001086
Chris Lattner42362612005-04-08 04:03:26 +00001087 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1088 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1089 FC, SI->getName()+".f");
1090 FSI = InsertNewInstBefore(FSI, I);
1091 return new SelectInst(SI->getOperand(0), TSI, FSI);
1092 }
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001093 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001094
Chris Lattner3082c5a2003-02-18 19:28:33 +00001095 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001096 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001097 if (LHS->equalsInt(0))
1098 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1099
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001100 return 0;
1101}
1102
1103
Chris Lattner113f4f42002-06-25 16:13:24 +00001104Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001106 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001107 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001108 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001109 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001110 // X % -Y -> X % Y
1111 AddUsesToWorkList(I);
1112 I.setOperand(1, RHSNeg);
1113 return &I;
1114 }
1115
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001116 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001117 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001118 if (isa<UndefValue>(Op1))
1119 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001120
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001121 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001122 if (RHS->equalsInt(1)) // X % 1 == 0
1123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1124
1125 // Check to see if this is an unsigned remainder with an exact power of 2,
1126 // if so, convert to a bitwise and.
1127 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1128 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001129 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001130 return BinaryOperator::createAnd(Op0,
1131 ConstantUInt::get(I.getType(), Val-1));
1132
1133 if (!RHS->isNullValue()) {
1134 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001135 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001136 return R;
1137 if (isa<PHINode>(Op0))
1138 if (Instruction *NV = FoldOpIntoPhi(I))
1139 return NV;
1140 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001141 }
1142
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001143 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1144 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1145 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1146 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1147 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1148 if (STO->getValue() == 0) { // Couldn't be this argument.
1149 I.setOperand(1, SFO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001150 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001151 } else if (SFO->getValue() == 0) {
1152 I.setOperand(1, STO);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001153 return &I;
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001154 }
1155
1156 if (!(STO->getValue() & (STO->getValue()-1)) &&
1157 !(SFO->getValue() & (SFO->getValue()-1))) {
1158 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1159 SubOne(STO), SI->getName()+".t"), I);
1160 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1161 SubOne(SFO), SI->getName()+".f"), I);
1162 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1163 }
1164 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00001165
Chris Lattner3082c5a2003-02-18 19:28:33 +00001166 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001167 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001168 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001169 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1170
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001171 return 0;
1172}
1173
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001174// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001175static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001176 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1177 // Calculate -1 casted to the right type...
1178 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1179 uint64_t Val = ~0ULL; // All ones
1180 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1181 return CU->getValue() == Val-1;
1182 }
1183
1184 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001185
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001186 // Calculate 0111111111..11111
1187 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1188 int64_t Val = INT64_MAX; // All ones
1189 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1190 return CS->getValue() == Val-1;
1191}
1192
1193// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001194static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001195 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1196 return CU->getValue() == 1;
1197
1198 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001199
1200 // Calculate 1111111111000000000000
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001201 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1202 int64_t Val = -1; // All ones
1203 Val <<= TypeBits-1; // Shift over to the right spot
1204 return CS->getValue() == Val+1;
1205}
1206
Chris Lattner35167c32004-06-09 07:59:58 +00001207// isOneBitSet - Return true if there is exactly one bit set in the specified
1208// constant.
1209static bool isOneBitSet(const ConstantInt *CI) {
1210 uint64_t V = CI->getRawValue();
1211 return V && (V & (V-1)) == 0;
1212}
1213
Chris Lattner8fc5af42004-09-23 21:46:38 +00001214#if 0 // Currently unused
1215// isLowOnes - Return true if the constant is of the form 0+1+.
1216static bool isLowOnes(const ConstantInt *CI) {
1217 uint64_t V = CI->getRawValue();
1218
1219 // There won't be bits set in parts that the type doesn't contain.
1220 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1221
1222 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1223 return U && V && (U & V) == 0;
1224}
1225#endif
1226
1227// isHighOnes - Return true if the constant is of the form 1+0+.
1228// This is the same as lowones(~X).
1229static bool isHighOnes(const ConstantInt *CI) {
1230 uint64_t V = ~CI->getRawValue();
1231
1232 // There won't be bits set in parts that the type doesn't contain.
1233 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1234
1235 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1236 return U && V && (U & V) == 0;
1237}
1238
1239
Chris Lattner3ac7c262003-08-13 20:16:26 +00001240/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1241/// are carefully arranged to allow folding of expressions such as:
1242///
1243/// (A < B) | (A > B) --> (A != B)
1244///
1245/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1246/// represents that the comparison is true if A == B, and bit value '1' is true
1247/// if A < B.
1248///
1249static unsigned getSetCondCode(const SetCondInst *SCI) {
1250 switch (SCI->getOpcode()) {
1251 // False -> 0
1252 case Instruction::SetGT: return 1;
1253 case Instruction::SetEQ: return 2;
1254 case Instruction::SetGE: return 3;
1255 case Instruction::SetLT: return 4;
1256 case Instruction::SetNE: return 5;
1257 case Instruction::SetLE: return 6;
1258 // True -> 7
1259 default:
1260 assert(0 && "Invalid SetCC opcode!");
1261 return 0;
1262 }
1263}
1264
1265/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1266/// opcode and two operands into either a constant true or false, or a brand new
1267/// SetCC instruction.
1268static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1269 switch (Opcode) {
1270 case 0: return ConstantBool::False;
1271 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1272 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1273 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1274 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1275 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1276 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1277 case 7: return ConstantBool::True;
1278 default: assert(0 && "Illegal SetCCCode!"); return 0;
1279 }
1280}
1281
1282// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1283struct FoldSetCCLogical {
1284 InstCombiner &IC;
1285 Value *LHS, *RHS;
1286 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1287 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1288 bool shouldApply(Value *V) const {
1289 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1290 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1291 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1292 return false;
1293 }
1294 Instruction *apply(BinaryOperator &Log) const {
1295 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1296 if (SCI->getOperand(0) != LHS) {
1297 assert(SCI->getOperand(1) == LHS);
1298 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1299 }
1300
1301 unsigned LHSCode = getSetCondCode(SCI);
1302 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1303 unsigned Code;
1304 switch (Log.getOpcode()) {
1305 case Instruction::And: Code = LHSCode & RHSCode; break;
1306 case Instruction::Or: Code = LHSCode | RHSCode; break;
1307 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001308 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001309 }
1310
1311 Value *RV = getSetCCValue(Code, LHS, RHS);
1312 if (Instruction *I = dyn_cast<Instruction>(RV))
1313 return I;
1314 // Otherwise, it's a constant boolean value...
1315 return IC.ReplaceInstUsesWith(Log, RV);
1316 }
1317};
1318
1319
Chris Lattner86102b82005-01-01 16:22:27 +00001320/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1321/// this predicate to simplify operations downstream. V and Mask are known to
1322/// be the same type.
1323static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1324 if (isa<UndefValue>(V) || Mask->isNullValue())
1325 return true;
1326 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1327 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001328
Chris Lattner86102b82005-01-01 16:22:27 +00001329 if (Instruction *I = dyn_cast<Instruction>(V)) {
1330 switch (I->getOpcode()) {
1331 case Instruction::And:
1332 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1333 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1334 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1335 return true;
1336 break;
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001337 case Instruction::Or:
1338 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001339 return MaskedValueIsZero(I->getOperand(1), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001340 MaskedValueIsZero(I->getOperand(0), Mask);
1341 case Instruction::Select:
1342 // If the T and F values are MaskedValueIsZero, the result is also zero.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001343 return MaskedValueIsZero(I->getOperand(2), Mask) &&
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001344 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner86102b82005-01-01 16:22:27 +00001345 case Instruction::Cast: {
1346 const Type *SrcTy = I->getOperand(0)->getType();
1347 if (SrcTy->isIntegral()) {
1348 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1349 if (SrcTy->isUnsigned() && // Only handle zero ext.
1350 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1351 return true;
1352
1353 // If this is a noop cast, recurse.
1354 if (SrcTy != Type::BoolTy)
1355 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() ==I->getType()) ||
1356 SrcTy->getSignedVersion() == I->getType()) {
1357 Constant *NewMask =
1358 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1359 return MaskedValueIsZero(I->getOperand(0),
1360 cast<ConstantIntegral>(NewMask));
1361 }
1362 }
1363 break;
1364 }
1365 case Instruction::Shl:
1366 // (shl X, C1) & C2 == 0 iff (-1 << C1) & C2 == 0
1367 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1368 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1369 C1 = ConstantExpr::getShl(C1, SA);
1370 C1 = ConstantExpr::getAnd(C1, Mask);
1371 if (C1->isNullValue())
1372 return true;
1373 }
1374 break;
1375 case Instruction::Shr:
1376 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1377 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1378 if (I->getType()->isUnsigned()) {
1379 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1380 C1 = ConstantExpr::getShr(C1, SA);
1381 C1 = ConstantExpr::getAnd(C1, Mask);
1382 if (C1->isNullValue())
1383 return true;
1384 }
1385 break;
1386 }
1387 }
1388
1389 return false;
1390}
1391
Chris Lattnerba1cb382003-09-19 17:17:26 +00001392// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1393// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1394// guaranteed to be either a shift instruction or a binary operator.
1395Instruction *InstCombiner::OptAndOp(Instruction *Op,
1396 ConstantIntegral *OpRHS,
1397 ConstantIntegral *AndRHS,
1398 BinaryOperator &TheAnd) {
1399 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001400 Constant *Together = 0;
1401 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001402 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001403
Chris Lattnerba1cb382003-09-19 17:17:26 +00001404 switch (Op->getOpcode()) {
1405 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001406 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001407 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1408 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001409 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001410 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001411 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001412 }
1413 break;
1414 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001415 if (Together == AndRHS) // (X | C) & C --> C
1416 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001417
Chris Lattner86102b82005-01-01 16:22:27 +00001418 if (Op->hasOneUse() && Together != OpRHS) {
1419 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1420 std::string Op0Name = Op->getName(); Op->setName("");
1421 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1422 InsertNewInstBefore(Or, TheAnd);
1423 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001424 }
1425 break;
1426 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001427 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001428 // Adding a one to a single bit bit-field should be turned into an XOR
1429 // of the bit. First thing to check is to see if this AND is with a
1430 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001431 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001432
1433 // Clear bits that are not part of the constant.
1434 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1435
1436 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001437 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001438 // Ok, at this point, we know that we are masking the result of the
1439 // ADD down to exactly one bit. If the constant we are adding has
1440 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001441 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00001442
Chris Lattnerba1cb382003-09-19 17:17:26 +00001443 // Check to see if any bits below the one bit set in AndRHSV are set.
1444 if ((AddRHS & (AndRHSV-1)) == 0) {
1445 // If not, the only thing that can effect the output of the AND is
1446 // the bit specified by AndRHSV. If that bit is set, the effect of
1447 // the XOR is to toggle the bit. If it is clear, then the ADD has
1448 // no effect.
1449 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1450 TheAnd.setOperand(0, X);
1451 return &TheAnd;
1452 } else {
1453 std::string Name = Op->getName(); Op->setName("");
1454 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001455 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001456 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001457 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001458 }
1459 }
1460 }
1461 }
1462 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001463
1464 case Instruction::Shl: {
1465 // We know that the AND will not produce any of the bits shifted in, so if
1466 // the anded constant includes them, clear them now!
1467 //
1468 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001469 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1470 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001471
Chris Lattner7e794272004-09-24 15:21:34 +00001472 if (CI == ShlMask) { // Masking out bits that the shift already masks
1473 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1474 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001475 TheAnd.setOperand(1, CI);
1476 return &TheAnd;
1477 }
1478 break;
Misha Brukmanb1c93172005-04-21 23:48:37 +00001479 }
Chris Lattner2da29172003-09-19 19:05:02 +00001480 case Instruction::Shr:
1481 // We know that the AND will not produce any of the bits shifted in, so if
1482 // the anded constant includes them, clear them now! This only applies to
1483 // unsigned shifts, because a signed shr may bring in set bits!
1484 //
1485 if (AndRHS->getType()->isUnsigned()) {
1486 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001487 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1488 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1489
1490 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1491 return ReplaceInstUsesWith(TheAnd, Op);
1492 } else if (CI != AndRHS) {
1493 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001494 return &TheAnd;
1495 }
Chris Lattner7e794272004-09-24 15:21:34 +00001496 } else { // Signed shr.
1497 // See if this is shifting in some sign extension, then masking it out
1498 // with an and.
1499 if (Op->hasOneUse()) {
1500 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1501 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1502 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001503 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001504 // Make the argument unsigned.
1505 Value *ShVal = Op->getOperand(0);
1506 ShVal = InsertCastBefore(ShVal,
1507 ShVal->getType()->getUnsignedVersion(),
1508 TheAnd);
1509 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1510 OpRHS, Op->getName()),
1511 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001512 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1513 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1514 TheAnd.getName()),
1515 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001516 return new CastInst(ShVal, Op->getType());
1517 }
1518 }
Chris Lattner2da29172003-09-19 19:05:02 +00001519 }
1520 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001521 }
1522 return 0;
1523}
1524
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001525
Chris Lattner6862fbd2004-09-29 17:40:11 +00001526/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1527/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1528/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1529/// insert new instructions.
1530Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1531 bool Inside, Instruction &IB) {
1532 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1533 "Lo is not <= Hi in range emission code!");
1534 if (Inside) {
1535 if (Lo == Hi) // Trivially false.
1536 return new SetCondInst(Instruction::SetNE, V, V);
1537 if (cast<ConstantIntegral>(Lo)->isMinValue())
1538 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001539
Chris Lattner6862fbd2004-09-29 17:40:11 +00001540 Constant *AddCST = ConstantExpr::getNeg(Lo);
1541 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1542 InsertNewInstBefore(Add, IB);
1543 // Convert to unsigned for the comparison.
1544 const Type *UnsType = Add->getType()->getUnsignedVersion();
1545 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1546 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1547 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1548 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1549 }
1550
1551 if (Lo == Hi) // Trivially true.
1552 return new SetCondInst(Instruction::SetEQ, V, V);
1553
1554 Hi = SubOne(cast<ConstantInt>(Hi));
1555 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1556 return new SetCondInst(Instruction::SetGT, V, Hi);
1557
1558 // Emit X-Lo > Hi-Lo-1
1559 Constant *AddCST = ConstantExpr::getNeg(Lo);
1560 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1561 InsertNewInstBefore(Add, IB);
1562 // Convert to unsigned for the comparison.
1563 const Type *UnsType = Add->getType()->getUnsignedVersion();
1564 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1565 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1566 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1567 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1568}
1569
1570
Chris Lattner113f4f42002-06-25 16:13:24 +00001571Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001572 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001573 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001574
Chris Lattner81a7a232004-10-16 18:11:37 +00001575 if (isa<UndefValue>(Op1)) // X & undef -> 0
1576 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1577
Chris Lattner86102b82005-01-01 16:22:27 +00001578 // and X, X = X
1579 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001580 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001581
Chris Lattner86102b82005-01-01 16:22:27 +00001582 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001583 // and X, -1 == X
1584 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001585 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001586
Chris Lattner86102b82005-01-01 16:22:27 +00001587 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1588 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1589
1590 // If the mask is not masking out any bits, there is no reason to do the
1591 // and in the first place.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001592 ConstantIntegral *NotAndRHS =
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001593 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanb1c93172005-04-21 23:48:37 +00001594 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001595 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001596
Chris Lattnerba1cb382003-09-19 17:17:26 +00001597 // Optimize a variety of ((val OP C1) & C2) combinations...
1598 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1599 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001600 Value *Op0LHS = Op0I->getOperand(0);
1601 Value *Op0RHS = Op0I->getOperand(1);
1602 switch (Op0I->getOpcode()) {
1603 case Instruction::Xor:
1604 case Instruction::Or:
1605 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1606 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1607 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001608 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner86102b82005-01-01 16:22:27 +00001609 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanb1c93172005-04-21 23:48:37 +00001610 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001611
1612 // If the mask is only needed on one incoming arm, push it up.
1613 if (Op0I->hasOneUse()) {
1614 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1615 // Not masking anything out for the LHS, move to RHS.
1616 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1617 Op0RHS->getName()+".masked");
1618 InsertNewInstBefore(NewRHS, I);
1619 return BinaryOperator::create(
1620 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanb1c93172005-04-21 23:48:37 +00001621 }
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001622 if (!isa<Constant>(NotAndRHS) &&
1623 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1624 // Not masking anything out for the RHS, move to LHS.
1625 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1626 Op0LHS->getName()+".masked");
1627 InsertNewInstBefore(NewLHS, I);
1628 return BinaryOperator::create(
1629 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1630 }
1631 }
1632
Chris Lattner86102b82005-01-01 16:22:27 +00001633 break;
1634 case Instruction::And:
1635 // (X & V) & C2 --> 0 iff (V & C2) == 0
1636 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1637 MaskedValueIsZero(Op0RHS, AndRHS))
1638 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1639 break;
1640 }
1641
Chris Lattner16464b32003-07-23 19:25:52 +00001642 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001643 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001644 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001645 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1646 const Type *SrcTy = CI->getOperand(0)->getType();
1647
1648 // If this is an integer sign or zero extension instruction.
1649 if (SrcTy->isIntegral() &&
1650 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
1651
1652 if (SrcTy->isUnsigned()) {
1653 // See if this and is clearing out bits that are known to be zero
1654 // anyway (due to the zero extension).
1655 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1656 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1657 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1658 if (Result == Mask) // The "and" isn't doing anything, remove it.
1659 return ReplaceInstUsesWith(I, CI);
1660 if (Result != AndRHS) { // Reduce the and RHS constant.
1661 I.setOperand(1, Result);
1662 return &I;
1663 }
1664
1665 } else {
1666 if (CI->hasOneUse() && SrcTy->isInteger()) {
1667 // We can only do this if all of the sign bits brought in are masked
1668 // out. Compute this by first getting 0000011111, then inverting
1669 // it.
1670 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1671 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1672 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1673 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1674 // If the and is clearing all of the sign bits, change this to a
1675 // zero extension cast. To do this, cast the cast input to
1676 // unsigned, then to the requested size.
1677 Value *CastOp = CI->getOperand(0);
1678 Instruction *NC =
1679 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1680 CI->getName()+".uns");
1681 NC = InsertNewInstBefore(NC, I);
1682 // Finally, insert a replacement for CI.
1683 NC = new CastInst(NC, CI->getType(), CI->getName());
1684 CI->setName("");
1685 NC = InsertNewInstBefore(NC, I);
1686 WorkList.push_back(CI); // Delete CI later.
1687 I.setOperand(0, NC);
1688 return &I; // The AND operand was modified.
1689 }
1690 }
1691 }
1692 }
Chris Lattner33217db2003-07-23 19:36:21 +00001693 }
Chris Lattner183b3362004-04-09 19:05:30 +00001694
1695 // Try to fold constant and into select arguments.
1696 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001697 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001698 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001699 if (isa<PHINode>(Op0))
1700 if (Instruction *NV = FoldOpIntoPhi(I))
1701 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001702 }
1703
Chris Lattnerbb74e222003-03-10 23:06:50 +00001704 Value *Op0NotVal = dyn_castNotVal(Op0);
1705 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001706
Chris Lattner023a4832004-06-18 06:07:51 +00001707 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1708 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1709
Misha Brukman9c003d82004-07-30 12:50:08 +00001710 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001711 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001712 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1713 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001714 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001715 return BinaryOperator::createNot(Or);
1716 }
1717
Chris Lattner623826c2004-09-28 21:48:02 +00001718 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1719 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001720 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1721 return R;
1722
Chris Lattner623826c2004-09-28 21:48:02 +00001723 Value *LHSVal, *RHSVal;
1724 ConstantInt *LHSCst, *RHSCst;
1725 Instruction::BinaryOps LHSCC, RHSCC;
1726 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1727 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1728 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1729 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001730 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner623826c2004-09-28 21:48:02 +00001731 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1732 // Ensure that the larger constant is on the RHS.
1733 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1734 SetCondInst *LHS = cast<SetCondInst>(Op0);
1735 if (cast<ConstantBool>(Cmp)->getValue()) {
1736 std::swap(LHS, RHS);
1737 std::swap(LHSCst, RHSCst);
1738 std::swap(LHSCC, RHSCC);
1739 }
1740
1741 // At this point, we know we have have two setcc instructions
1742 // comparing a value against two constants and and'ing the result
1743 // together. Because of the above check, we know that we only have
1744 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1745 // FoldSetCCLogical check above), that the two constants are not
1746 // equal.
1747 assert(LHSCst != RHSCst && "Compares not folded above?");
1748
1749 switch (LHSCC) {
1750 default: assert(0 && "Unknown integer condition code!");
1751 case Instruction::SetEQ:
1752 switch (RHSCC) {
1753 default: assert(0 && "Unknown integer condition code!");
1754 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1755 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1756 return ReplaceInstUsesWith(I, ConstantBool::False);
1757 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1758 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1759 return ReplaceInstUsesWith(I, LHS);
1760 }
1761 case Instruction::SetNE:
1762 switch (RHSCC) {
1763 default: assert(0 && "Unknown integer condition code!");
1764 case Instruction::SetLT:
1765 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1766 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1767 break; // (X != 13 & X < 15) -> no change
1768 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1769 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1770 return ReplaceInstUsesWith(I, RHS);
1771 case Instruction::SetNE:
1772 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1773 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1774 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1775 LHSVal->getName()+".off");
1776 InsertNewInstBefore(Add, I);
1777 const Type *UnsType = Add->getType()->getUnsignedVersion();
1778 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1779 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1780 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1781 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1782 }
1783 break; // (X != 13 & X != 15) -> no change
1784 }
1785 break;
1786 case Instruction::SetLT:
1787 switch (RHSCC) {
1788 default: assert(0 && "Unknown integer condition code!");
1789 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1790 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1791 return ReplaceInstUsesWith(I, ConstantBool::False);
1792 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1793 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1794 return ReplaceInstUsesWith(I, LHS);
1795 }
1796 case Instruction::SetGT:
1797 switch (RHSCC) {
1798 default: assert(0 && "Unknown integer condition code!");
1799 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1800 return ReplaceInstUsesWith(I, LHS);
1801 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1802 return ReplaceInstUsesWith(I, RHS);
1803 case Instruction::SetNE:
1804 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1805 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1806 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001807 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1808 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001809 }
1810 }
1811 }
1812 }
1813
Chris Lattner113f4f42002-06-25 16:13:24 +00001814 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001815}
1816
Chris Lattner113f4f42002-06-25 16:13:24 +00001817Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001818 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001819 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001820
Chris Lattner81a7a232004-10-16 18:11:37 +00001821 if (isa<UndefValue>(Op1))
1822 return ReplaceInstUsesWith(I, // X | undef -> -1
1823 ConstantIntegral::getAllOnesValue(I.getType()));
1824
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001825 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001826 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1827 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001828
1829 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001830 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001831 // If X is known to only contain bits that already exist in RHS, just
1832 // replace this instruction with RHS directly.
1833 if (MaskedValueIsZero(Op0,
1834 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1835 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001836
Chris Lattnerd4252a72004-07-30 07:50:03 +00001837 ConstantInt *C1; Value *X;
1838 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1839 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1840 std::string Op0Name = Op0->getName(); Op0->setName("");
1841 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1842 InsertNewInstBefore(Or, I);
1843 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1844 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001845
Chris Lattnerd4252a72004-07-30 07:50:03 +00001846 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1847 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1848 std::string Op0Name = Op0->getName(); Op0->setName("");
1849 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1850 InsertNewInstBefore(Or, I);
1851 return BinaryOperator::createXor(Or,
1852 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001853 }
Chris Lattner183b3362004-04-09 19:05:30 +00001854
1855 // Try to fold constant and into select arguments.
1856 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001857 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001858 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001859 if (isa<PHINode>(Op0))
1860 if (Instruction *NV = FoldOpIntoPhi(I))
1861 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001862 }
1863
Chris Lattner812aab72003-08-12 19:11:07 +00001864 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001865 Value *A, *B; ConstantInt *C1, *C2;
1866 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1867 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1868 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001869
Chris Lattnerd4252a72004-07-30 07:50:03 +00001870 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1871 if (A == Op1) // ~A | A == -1
Misha Brukmanb1c93172005-04-21 23:48:37 +00001872 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00001873 ConstantIntegral::getAllOnesValue(I.getType()));
1874 } else {
1875 A = 0;
1876 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001877
Chris Lattnerd4252a72004-07-30 07:50:03 +00001878 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1879 if (Op0 == B)
Misha Brukmanb1c93172005-04-21 23:48:37 +00001880 return ReplaceInstUsesWith(I,
Chris Lattnerd4252a72004-07-30 07:50:03 +00001881 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001882
Misha Brukman9c003d82004-07-30 12:50:08 +00001883 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001884 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1885 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1886 I.getName()+".demorgan"), I);
1887 return BinaryOperator::createNot(And);
1888 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001889 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001890
Chris Lattner3ac7c262003-08-13 20:16:26 +00001891 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001892 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001893 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1894 return R;
1895
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001896 Value *LHSVal, *RHSVal;
1897 ConstantInt *LHSCst, *RHSCst;
1898 Instruction::BinaryOps LHSCC, RHSCC;
1899 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1900 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1901 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1902 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanb1c93172005-04-21 23:48:37 +00001903 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001904 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1905 // Ensure that the larger constant is on the RHS.
1906 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1907 SetCondInst *LHS = cast<SetCondInst>(Op0);
1908 if (cast<ConstantBool>(Cmp)->getValue()) {
1909 std::swap(LHS, RHS);
1910 std::swap(LHSCst, RHSCst);
1911 std::swap(LHSCC, RHSCC);
1912 }
1913
1914 // At this point, we know we have have two setcc instructions
1915 // comparing a value against two constants and or'ing the result
1916 // together. Because of the above check, we know that we only have
1917 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1918 // FoldSetCCLogical check above), that the two constants are not
1919 // equal.
1920 assert(LHSCst != RHSCst && "Compares not folded above?");
1921
1922 switch (LHSCC) {
1923 default: assert(0 && "Unknown integer condition code!");
1924 case Instruction::SetEQ:
1925 switch (RHSCC) {
1926 default: assert(0 && "Unknown integer condition code!");
1927 case Instruction::SetEQ:
1928 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1929 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1930 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1931 LHSVal->getName()+".off");
1932 InsertNewInstBefore(Add, I);
1933 const Type *UnsType = Add->getType()->getUnsignedVersion();
1934 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1935 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1936 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1937 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1938 }
1939 break; // (X == 13 | X == 15) -> no change
1940
Chris Lattner5c219462005-04-19 06:04:18 +00001941 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
1942 break;
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001943 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1944 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1945 return ReplaceInstUsesWith(I, RHS);
1946 }
1947 break;
1948 case Instruction::SetNE:
1949 switch (RHSCC) {
1950 default: assert(0 && "Unknown integer condition code!");
1951 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1952 return ReplaceInstUsesWith(I, RHS);
1953 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1954 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1955 return ReplaceInstUsesWith(I, LHS);
1956 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1957 return ReplaceInstUsesWith(I, ConstantBool::True);
1958 }
1959 break;
1960 case Instruction::SetLT:
1961 switch (RHSCC) {
1962 default: assert(0 && "Unknown integer condition code!");
1963 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1964 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001965 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1966 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001967 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1968 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1969 return ReplaceInstUsesWith(I, RHS);
1970 }
1971 break;
1972 case Instruction::SetGT:
1973 switch (RHSCC) {
1974 default: assert(0 && "Unknown integer condition code!");
1975 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1976 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1977 return ReplaceInstUsesWith(I, LHS);
1978 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1979 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1980 return ReplaceInstUsesWith(I, ConstantBool::True);
1981 }
1982 }
1983 }
1984 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001985 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001986}
1987
Chris Lattnerc2076352004-02-16 01:20:27 +00001988// XorSelf - Implements: X ^ X --> 0
1989struct XorSelf {
1990 Value *RHS;
1991 XorSelf(Value *rhs) : RHS(rhs) {}
1992 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1993 Instruction *apply(BinaryOperator &Xor) const {
1994 return &Xor;
1995 }
1996};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001997
1998
Chris Lattner113f4f42002-06-25 16:13:24 +00001999Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002000 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00002001 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002002
Chris Lattner81a7a232004-10-16 18:11:37 +00002003 if (isa<UndefValue>(Op1))
2004 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2005
Chris Lattnerc2076352004-02-16 01:20:27 +00002006 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2007 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2008 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00002009 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00002010 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002011
Chris Lattner97638592003-07-23 21:37:07 +00002012 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002013 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00002014 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00002015 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002016
Chris Lattner97638592003-07-23 21:37:07 +00002017 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002018 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00002019 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002020 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002021 return new SetCondInst(SCI->getInverseCondition(),
2022 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00002023
Chris Lattner8f2f5982003-11-05 01:06:05 +00002024 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002025 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2026 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002027 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2028 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002029 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002030 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002031 }
Chris Lattner023a4832004-06-18 06:07:51 +00002032
2033 // ~(~X & Y) --> (X | ~Y)
2034 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2035 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2036 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2037 Instruction *NotY =
Misha Brukmanb1c93172005-04-21 23:48:37 +00002038 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner023a4832004-06-18 06:07:51 +00002039 Op0I->getOperand(1)->getName()+".not");
2040 InsertNewInstBefore(NotY, I);
2041 return BinaryOperator::createOr(Op0NotVal, NotY);
2042 }
2043 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002044
Chris Lattner97638592003-07-23 21:37:07 +00002045 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002046 switch (Op0I->getOpcode()) {
2047 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002048 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002049 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002050 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2051 return BinaryOperator::createSub(
2052 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002053 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002054 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002055 }
Chris Lattnere5806662003-11-04 23:50:51 +00002056 break;
2057 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002058 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002059 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2060 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002061 break;
2062 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002063 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002064 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002065 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002066 break;
2067 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002068 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002069 }
Chris Lattner183b3362004-04-09 19:05:30 +00002070
2071 // Try to fold constant and into select arguments.
2072 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002073 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002074 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002075 if (isa<PHINode>(Op0))
2076 if (Instruction *NV = FoldOpIntoPhi(I))
2077 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002078 }
2079
Chris Lattnerbb74e222003-03-10 23:06:50 +00002080 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002081 if (X == Op1)
2082 return ReplaceInstUsesWith(I,
2083 ConstantIntegral::getAllOnesValue(I.getType()));
2084
Chris Lattnerbb74e222003-03-10 23:06:50 +00002085 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002086 if (X == Op0)
2087 return ReplaceInstUsesWith(I,
2088 ConstantIntegral::getAllOnesValue(I.getType()));
2089
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002090 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002091 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002092 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2093 cast<BinaryOperator>(Op1I)->swapOperands();
2094 I.swapOperands();
2095 std::swap(Op0, Op1);
2096 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2097 I.swapOperands();
2098 std::swap(Op0, Op1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002099 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002100 } else if (Op1I->getOpcode() == Instruction::Xor) {
2101 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2102 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2103 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2104 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2105 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002106
2107 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002108 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002109 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2110 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002111 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002112 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2113 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002114 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002115 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002116 } else if (Op0I->getOpcode() == Instruction::Xor) {
2117 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2118 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2119 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2120 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002121 }
2122
Chris Lattner7aa2d472004-08-01 19:42:59 +00002123 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002124 Value *A, *B; ConstantInt *C1, *C2;
2125 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2126 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002127 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002128 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002129
Chris Lattner3ac7c262003-08-13 20:16:26 +00002130 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2131 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2132 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2133 return R;
2134
Chris Lattner113f4f42002-06-25 16:13:24 +00002135 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002136}
2137
Chris Lattner6862fbd2004-09-29 17:40:11 +00002138/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2139/// overflowed for this type.
2140static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2141 ConstantInt *In2) {
2142 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2143 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2144}
2145
2146static bool isPositive(ConstantInt *C) {
2147 return cast<ConstantSInt>(C)->getValue() >= 0;
2148}
2149
2150/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2151/// overflowed for this type.
2152static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2153 ConstantInt *In2) {
2154 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2155
2156 if (In1->getType()->isUnsigned())
2157 return cast<ConstantUInt>(Result)->getValue() <
2158 cast<ConstantUInt>(In1)->getValue();
2159 if (isPositive(In1) != isPositive(In2))
2160 return false;
2161 if (isPositive(In1))
2162 return cast<ConstantSInt>(Result)->getValue() <
2163 cast<ConstantSInt>(In1)->getValue();
2164 return cast<ConstantSInt>(Result)->getValue() >
2165 cast<ConstantSInt>(In1)->getValue();
2166}
2167
Chris Lattner0798af32005-01-13 20:14:25 +00002168/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2169/// code necessary to compute the offset from the base pointer (without adding
2170/// in the base pointer). Return the result as a signed integer of intptr size.
2171static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2172 TargetData &TD = IC.getTargetData();
2173 gep_type_iterator GTI = gep_type_begin(GEP);
2174 const Type *UIntPtrTy = TD.getIntPtrType();
2175 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2176 Value *Result = Constant::getNullValue(SIntPtrTy);
2177
2178 // Build a mask for high order bits.
2179 uint64_t PtrSizeMask = ~0ULL;
2180 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2181
Chris Lattner0798af32005-01-13 20:14:25 +00002182 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2183 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002184 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002185 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2186 SIntPtrTy);
2187 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2188 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002189 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002190 Scale = ConstantExpr::getMul(OpC, Scale);
2191 if (Constant *RC = dyn_cast<Constant>(Result))
2192 Result = ConstantExpr::getAdd(RC, Scale);
2193 else {
2194 // Emit an add instruction.
2195 Result = IC.InsertNewInstBefore(
2196 BinaryOperator::createAdd(Result, Scale,
2197 GEP->getName()+".offs"), I);
2198 }
2199 }
2200 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002201 // Convert to correct type.
2202 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2203 Op->getName()+".c"), I);
2204 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002205 // We'll let instcombine(mul) convert this to a shl if possible.
2206 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2207 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002208
2209 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002210 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002211 GEP->getName()+".offs"), I);
2212 }
2213 }
2214 return Result;
2215}
2216
2217/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2218/// else. At this point we know that the GEP is on the LHS of the comparison.
2219Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2220 Instruction::BinaryOps Cond,
2221 Instruction &I) {
2222 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002223
2224 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2225 if (isa<PointerType>(CI->getOperand(0)->getType()))
2226 RHS = CI->getOperand(0);
2227
Chris Lattner0798af32005-01-13 20:14:25 +00002228 Value *PtrBase = GEPLHS->getOperand(0);
2229 if (PtrBase == RHS) {
2230 // As an optimization, we don't actually have to compute the actual value of
2231 // OFFSET if this is a seteq or setne comparison, just return whether each
2232 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002233 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2234 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002235 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2236 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002237 bool EmitIt = true;
2238 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2239 if (isa<UndefValue>(C)) // undef index -> undef.
2240 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2241 if (C->isNullValue())
2242 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002243 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2244 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanb1c93172005-04-21 23:48:37 +00002245 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002246 return ReplaceInstUsesWith(I, // No comparison is needed here.
2247 ConstantBool::get(Cond == Instruction::SetNE));
2248 }
2249
2250 if (EmitIt) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002251 Instruction *Comp =
Chris Lattner81e84172005-01-13 22:25:21 +00002252 new SetCondInst(Cond, GEPLHS->getOperand(i),
2253 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2254 if (InVal == 0)
2255 InVal = Comp;
2256 else {
2257 InVal = InsertNewInstBefore(InVal, I);
2258 InsertNewInstBefore(Comp, I);
2259 if (Cond == Instruction::SetNE) // True if any are unequal
2260 InVal = BinaryOperator::createOr(InVal, Comp);
2261 else // True if all are equal
2262 InVal = BinaryOperator::createAnd(InVal, Comp);
2263 }
2264 }
2265 }
2266
2267 if (InVal)
2268 return InVal;
2269 else
2270 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2271 ConstantBool::get(Cond == Instruction::SetEQ));
2272 }
Chris Lattner0798af32005-01-13 20:14:25 +00002273
2274 // Only lower this if the setcc is the only user of the GEP or if we expect
2275 // the result to fold to a constant!
2276 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2277 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2278 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2279 return new SetCondInst(Cond, Offset,
2280 Constant::getNullValue(Offset->getType()));
2281 }
2282 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2283 if (PtrBase != GEPRHS->getOperand(0))
2284 return 0;
2285
Chris Lattner81e84172005-01-13 22:25:21 +00002286 // If one of the GEPs has all zero indices, recurse.
2287 bool AllZeros = true;
2288 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2289 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2290 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2291 AllZeros = false;
2292 break;
2293 }
2294 if (AllZeros)
2295 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2296 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002297
2298 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002299 AllZeros = true;
2300 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2301 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2302 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2303 AllZeros = false;
2304 break;
2305 }
2306 if (AllZeros)
2307 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2308
Chris Lattner4fa89822005-01-14 00:20:05 +00002309 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2310 // If the GEPs only differ by one index, compare it.
2311 unsigned NumDifferences = 0; // Keep track of # differences.
2312 unsigned DiffOperand = 0; // The operand that differs.
2313 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2314 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002315 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSize() !=
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002316 GEPRHS->getOperand(i)->getType()->getPrimitiveSize()) {
2317 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002318 NumDifferences = 2;
2319 break;
2320 } else {
2321 if (NumDifferences++) break;
2322 DiffOperand = i;
2323 }
2324 }
2325
2326 if (NumDifferences == 0) // SAME GEP?
2327 return ReplaceInstUsesWith(I, // No comparison is needed here.
2328 ConstantBool::get(Cond == Instruction::SetEQ));
2329 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002330 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2331 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2332 if (LHSV->getType() != RHSV->getType())
2333 LHSV = InsertNewInstBefore(new CastInst(LHSV, RHSV->getType(),
2334 LHSV->getName()+".c"), I);
2335 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002336 }
2337 }
2338
Chris Lattner0798af32005-01-13 20:14:25 +00002339 // Only lower this if the setcc is the only user of the GEP or if we expect
2340 // the result to fold to a constant!
2341 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2342 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2343 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2344 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2345 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2346 return new SetCondInst(Cond, L, R);
2347 }
2348 }
2349 return 0;
2350}
2351
2352
Chris Lattner113f4f42002-06-25 16:13:24 +00002353Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002354 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002355 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2356 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002357
2358 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002359 if (Op0 == Op1)
2360 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002361
Chris Lattner81a7a232004-10-16 18:11:37 +00002362 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2363 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2364
Chris Lattner15ff1e12004-11-14 07:33:16 +00002365 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2366 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002367 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2368 isa<ConstantPointerNull>(Op0)) &&
2369 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner15ff1e12004-11-14 07:33:16 +00002370 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002371 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2372
2373 // setcc's with boolean values can always be turned into bitwise operations
2374 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002375 switch (I.getOpcode()) {
2376 default: assert(0 && "Invalid setcc instruction!");
2377 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002378 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002379 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002380 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002381 }
Chris Lattner4456da62004-08-11 00:50:51 +00002382 case Instruction::SetNE:
2383 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002384
Chris Lattner4456da62004-08-11 00:50:51 +00002385 case Instruction::SetGT:
2386 std::swap(Op0, Op1); // Change setgt -> setlt
2387 // FALL THROUGH
2388 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2389 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2390 InsertNewInstBefore(Not, I);
2391 return BinaryOperator::createAnd(Not, Op1);
2392 }
2393 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002394 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002395 // FALL THROUGH
2396 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2397 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2398 InsertNewInstBefore(Not, I);
2399 return BinaryOperator::createOr(Not, Op1);
2400 }
2401 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002402 }
2403
Chris Lattner2dd01742004-06-09 04:24:29 +00002404 // See if we are doing a comparison between a constant and an instruction that
2405 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002406 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002407 // Check to see if we are comparing against the minimum or maximum value...
2408 if (CI->isMinValue()) {
2409 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2410 return ReplaceInstUsesWith(I, ConstantBool::False);
2411 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2412 return ReplaceInstUsesWith(I, ConstantBool::True);
2413 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2414 return BinaryOperator::createSetEQ(Op0, Op1);
2415 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2416 return BinaryOperator::createSetNE(Op0, Op1);
2417
2418 } else if (CI->isMaxValue()) {
2419 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2420 return ReplaceInstUsesWith(I, ConstantBool::False);
2421 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2422 return ReplaceInstUsesWith(I, ConstantBool::True);
2423 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2424 return BinaryOperator::createSetEQ(Op0, Op1);
2425 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2426 return BinaryOperator::createSetNE(Op0, Op1);
2427
2428 // Comparing against a value really close to min or max?
2429 } else if (isMinValuePlusOne(CI)) {
2430 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2431 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2432 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2433 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2434
2435 } else if (isMaxValueMinusOne(CI)) {
2436 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2437 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2438 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2439 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2440 }
2441
2442 // If we still have a setle or setge instruction, turn it into the
2443 // appropriate setlt or setgt instruction. Since the border cases have
2444 // already been handled above, this requires little checking.
2445 //
2446 if (I.getOpcode() == Instruction::SetLE)
2447 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2448 if (I.getOpcode() == Instruction::SetGE)
2449 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2450
Chris Lattnere1e10e12004-05-25 06:32:08 +00002451 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002452 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002453 case Instruction::PHI:
2454 if (Instruction *NV = FoldOpIntoPhi(I))
2455 return NV;
2456 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002457 case Instruction::And:
2458 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2459 LHSI->getOperand(0)->hasOneUse()) {
2460 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2461 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2462 // happens a LOT in code produced by the C front-end, for bitfield
2463 // access.
2464 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2465 ConstantUInt *ShAmt;
2466 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2467 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2468 const Type *Ty = LHSI->getType();
Misha Brukmanb1c93172005-04-21 23:48:37 +00002469
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002470 // We can fold this as long as we can't shift unknown bits
2471 // into the mask. This can only happen with signed shift
2472 // rights, as they sign-extend.
2473 if (ShAmt) {
2474 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002475 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002476 if (!CanFold) {
2477 // To test for the bad case of the signed shr, see if any
2478 // of the bits shifted in could be tested after the mask.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002479 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00002480 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Misha Brukmanb1c93172005-04-21 23:48:37 +00002481 Constant *ShVal =
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002482 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2483 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2484 CanFold = true;
2485 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002486
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002487 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002488 Constant *NewCst;
2489 if (Shift->getOpcode() == Instruction::Shl)
2490 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2491 else
2492 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002493
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002494 // Check to see if we are shifting out any of the bits being
2495 // compared.
2496 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2497 // If we shifted bits out, the fold is not going to work out.
2498 // As a special case, check to see if this means that the
2499 // result is always true or false now.
2500 if (I.getOpcode() == Instruction::SetEQ)
2501 return ReplaceInstUsesWith(I, ConstantBool::False);
2502 if (I.getOpcode() == Instruction::SetNE)
2503 return ReplaceInstUsesWith(I, ConstantBool::True);
2504 } else {
2505 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002506 Constant *NewAndCST;
2507 if (Shift->getOpcode() == Instruction::Shl)
2508 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2509 else
2510 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2511 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002512 LHSI->setOperand(0, Shift->getOperand(0));
2513 WorkList.push_back(Shift); // Shift is dead.
2514 AddUsesToWorkList(I);
2515 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002516 }
2517 }
Chris Lattner35167c32004-06-09 07:59:58 +00002518 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002519 }
2520 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002521
Reid Spencer279fa252004-11-28 21:31:15 +00002522 // (setcc (cast X to larger), CI)
Chris Lattner03f06f12005-01-17 03:20:02 +00002523 case Instruction::Cast:
Misha Brukmanb1c93172005-04-21 23:48:37 +00002524 if (Instruction *R =
Chris Lattner03f06f12005-01-17 03:20:02 +00002525 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI))
2526 return R;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002527 break;
Reid Spencer279fa252004-11-28 21:31:15 +00002528
Chris Lattner272d5ca2004-09-28 18:22:15 +00002529 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2530 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2531 switch (I.getOpcode()) {
2532 default: break;
2533 case Instruction::SetEQ:
2534 case Instruction::SetNE: {
2535 // If we are comparing against bits always shifted out, the
2536 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002537 Constant *Comp =
Chris Lattner272d5ca2004-09-28 18:22:15 +00002538 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2539 if (Comp != CI) {// Comparing against a bit that we know is zero.
2540 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2541 Constant *Cst = ConstantBool::get(IsSetNE);
2542 return ReplaceInstUsesWith(I, Cst);
2543 }
2544
2545 if (LHSI->hasOneUse()) {
2546 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002547 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002548 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2549 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2550
2551 Constant *Mask;
2552 if (CI->getType()->isUnsigned()) {
2553 Mask = ConstantUInt::get(CI->getType(), Val);
2554 } else if (ShAmtVal != 0) {
2555 Mask = ConstantSInt::get(CI->getType(), Val);
2556 } else {
2557 Mask = ConstantInt::getAllOnesValue(CI->getType());
2558 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002559
Chris Lattner272d5ca2004-09-28 18:22:15 +00002560 Instruction *AndI =
2561 BinaryOperator::createAnd(LHSI->getOperand(0),
2562 Mask, LHSI->getName()+".mask");
2563 Value *And = InsertNewInstBefore(AndI, I);
2564 return new SetCondInst(I.getOpcode(), And,
2565 ConstantExpr::getUShr(CI, ShAmt));
2566 }
2567 }
2568 }
2569 }
2570 break;
2571
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002572 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002573 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002574 switch (I.getOpcode()) {
2575 default: break;
2576 case Instruction::SetEQ:
2577 case Instruction::SetNE: {
2578 // If we are comparing against bits always shifted out, the
2579 // comparison cannot succeed.
Misha Brukmanb1c93172005-04-21 23:48:37 +00002580 Constant *Comp =
Chris Lattner1023b872004-09-27 16:18:50 +00002581 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002582
Chris Lattner1023b872004-09-27 16:18:50 +00002583 if (Comp != CI) {// Comparing against a bit that we know is zero.
2584 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2585 Constant *Cst = ConstantBool::get(IsSetNE);
2586 return ReplaceInstUsesWith(I, Cst);
2587 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002588
Chris Lattner1023b872004-09-27 16:18:50 +00002589 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002590 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002591
Chris Lattner1023b872004-09-27 16:18:50 +00002592 // Otherwise strength reduce the shift into an and.
2593 uint64_t Val = ~0ULL; // All ones.
2594 Val <<= ShAmtVal; // Shift over to the right spot.
2595
2596 Constant *Mask;
2597 if (CI->getType()->isUnsigned()) {
2598 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
Chris Lattnercfe2822c2005-03-04 23:21:33 +00002599 if (TypeBits != 64)
2600 Val &= (1ULL << TypeBits)-1;
Chris Lattner1023b872004-09-27 16:18:50 +00002601 Mask = ConstantUInt::get(CI->getType(), Val);
2602 } else {
2603 Mask = ConstantSInt::get(CI->getType(), Val);
2604 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002605
Chris Lattner1023b872004-09-27 16:18:50 +00002606 Instruction *AndI =
2607 BinaryOperator::createAnd(LHSI->getOperand(0),
2608 Mask, LHSI->getName()+".mask");
2609 Value *And = InsertNewInstBefore(AndI, I);
2610 return new SetCondInst(I.getOpcode(), And,
2611 ConstantExpr::getShl(CI, ShAmt));
2612 }
2613 break;
2614 }
2615 }
2616 }
2617 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002618
Chris Lattner6862fbd2004-09-29 17:40:11 +00002619 case Instruction::Div:
2620 // Fold: (div X, C1) op C2 -> range check
2621 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2622 // Fold this div into the comparison, producing a range check.
2623 // Determine, based on the divide type, what the range is being
2624 // checked. If there is an overflow on the low or high side, remember
2625 // it, otherwise compute the range [low, hi) bounding the new value.
2626 bool LoOverflow = false, HiOverflow = 0;
2627 ConstantInt *LoBound = 0, *HiBound = 0;
2628
2629 ConstantInt *Prod;
2630 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2631
Chris Lattnera92af962004-10-11 19:40:04 +00002632 Instruction::BinaryOps Opcode = I.getOpcode();
2633
Chris Lattner6862fbd2004-09-29 17:40:11 +00002634 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2635 } else if (LHSI->getType()->isUnsigned()) { // udiv
2636 LoBound = Prod;
2637 LoOverflow = ProdOV;
2638 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2639 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2640 if (CI->isNullValue()) { // (X / pos) op 0
2641 // Can't overflow.
2642 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2643 HiBound = DivRHS;
2644 } else if (isPositive(CI)) { // (X / pos) op pos
2645 LoBound = Prod;
2646 LoOverflow = ProdOV;
2647 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2648 } else { // (X / pos) op neg
2649 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2650 LoOverflow = AddWithOverflow(LoBound, Prod,
2651 cast<ConstantInt>(DivRHSH));
2652 HiBound = Prod;
2653 HiOverflow = ProdOV;
2654 }
2655 } else { // Divisor is < 0.
2656 if (CI->isNullValue()) { // (X / neg) op 0
2657 LoBound = AddOne(DivRHS);
2658 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2659 } else if (isPositive(CI)) { // (X / neg) op pos
2660 HiOverflow = LoOverflow = ProdOV;
2661 if (!LoOverflow)
2662 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2663 HiBound = AddOne(Prod);
2664 } else { // (X / neg) op neg
2665 LoBound = Prod;
2666 LoOverflow = HiOverflow = ProdOV;
2667 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2668 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002669
Chris Lattnera92af962004-10-11 19:40:04 +00002670 // Dividing by a negate swaps the condition.
2671 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002672 }
2673
2674 if (LoBound) {
2675 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002676 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002677 default: assert(0 && "Unhandled setcc opcode!");
2678 case Instruction::SetEQ:
2679 if (LoOverflow && HiOverflow)
2680 return ReplaceInstUsesWith(I, ConstantBool::False);
2681 else if (HiOverflow)
2682 return new SetCondInst(Instruction::SetGE, X, LoBound);
2683 else if (LoOverflow)
2684 return new SetCondInst(Instruction::SetLT, X, HiBound);
2685 else
2686 return InsertRangeTest(X, LoBound, HiBound, true, I);
2687 case Instruction::SetNE:
2688 if (LoOverflow && HiOverflow)
2689 return ReplaceInstUsesWith(I, ConstantBool::True);
2690 else if (HiOverflow)
2691 return new SetCondInst(Instruction::SetLT, X, LoBound);
2692 else if (LoOverflow)
2693 return new SetCondInst(Instruction::SetGE, X, HiBound);
2694 else
2695 return InsertRangeTest(X, LoBound, HiBound, false, I);
2696 case Instruction::SetLT:
2697 if (LoOverflow)
2698 return ReplaceInstUsesWith(I, ConstantBool::False);
2699 return new SetCondInst(Instruction::SetLT, X, LoBound);
2700 case Instruction::SetGT:
2701 if (HiOverflow)
2702 return ReplaceInstUsesWith(I, ConstantBool::False);
2703 return new SetCondInst(Instruction::SetGE, X, HiBound);
2704 }
2705 }
2706 }
2707 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002708 case Instruction::Select:
2709 // If either operand of the select is a constant, we can fold the
2710 // comparison into the select arms, which will cause one to be
2711 // constant folded and the select turned into a bitwise or.
2712 Value *Op1 = 0, *Op2 = 0;
2713 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002714 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002715 // Fold the known value into the constant operand.
2716 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2717 // Insert a new SetCC of the other select operand.
2718 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002719 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002720 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002721 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002722 // Fold the known value into the constant operand.
2723 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2724 // Insert a new SetCC of the other select operand.
2725 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002726 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002727 I.getName()), I);
2728 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002729 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002730
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002731 if (Op1)
2732 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2733 break;
2734 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002735
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002736 // Simplify seteq and setne instructions...
2737 if (I.getOpcode() == Instruction::SetEQ ||
2738 I.getOpcode() == Instruction::SetNE) {
2739 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2740
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002741 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002742 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002743 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2744 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002745 case Instruction::Rem:
2746 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2747 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2748 BO->hasOneUse() &&
2749 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2750 if (unsigned L2 =
2751 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2752 const Type *UTy = BO->getType()->getUnsignedVersion();
2753 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2754 UTy, "tmp"), I);
2755 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2756 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2757 RHSCst, BO->getName()), I);
2758 return BinaryOperator::create(I.getOpcode(), NewRem,
2759 Constant::getNullValue(UTy));
2760 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002761 break;
Chris Lattner23b47b62004-07-06 07:38:18 +00002762
Chris Lattnerc992add2003-08-13 05:33:12 +00002763 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002764 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2765 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002766 if (BO->hasOneUse())
2767 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2768 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002769 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002770 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2771 // efficiently invertible, or if the add has just this one use.
2772 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002773
Chris Lattnerc992add2003-08-13 05:33:12 +00002774 if (Value *NegVal = dyn_castNegVal(BOp1))
2775 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2776 else if (Value *NegVal = dyn_castNegVal(BOp0))
2777 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002778 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002779 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2780 BO->setName("");
2781 InsertNewInstBefore(Neg, I);
2782 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2783 }
2784 }
2785 break;
2786 case Instruction::Xor:
2787 // For the xor case, we can xor two constants together, eliminating
2788 // the explicit xor.
2789 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2790 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002791 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002792
2793 // FALLTHROUGH
2794 case Instruction::Sub:
2795 // Replace (([sub|xor] A, B) != 0) with (A != B)
2796 if (CI->isNullValue())
2797 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2798 BO->getOperand(1));
2799 break;
2800
2801 case Instruction::Or:
2802 // If bits are being or'd in that are not present in the constant we
2803 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002804 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002805 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002806 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002807 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002808 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002809 break;
2810
2811 case Instruction::And:
2812 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002813 // If bits are being compared against that are and'd out, then the
2814 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002815 if (!ConstantExpr::getAnd(CI,
2816 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002817 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002818
Chris Lattner35167c32004-06-09 07:59:58 +00002819 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002820 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002821 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2822 Instruction::SetNE, Op0,
2823 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002824
Chris Lattnerc992add2003-08-13 05:33:12 +00002825 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2826 // to be a signed value as appropriate.
2827 if (isSignBit(BOC)) {
2828 Value *X = BO->getOperand(0);
2829 // If 'X' is not signed, insert a cast now...
2830 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002831 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002832 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002833 }
2834 return new SetCondInst(isSetNE ? Instruction::SetLT :
2835 Instruction::SetGE, X,
2836 Constant::getNullValue(X->getType()));
2837 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002838
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002839 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002840 if (CI->isNullValue() && isHighOnes(BOC)) {
2841 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002842 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002843
2844 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002845 if (NegX->getType()->isSigned()) {
2846 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2847 X = InsertCastBefore(X, DestTy, I);
2848 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002849 }
2850
2851 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002852 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002853 }
2854
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002855 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002856 default: break;
2857 }
2858 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002859 } else { // Not a SetEQ/SetNE
Misha Brukmanb1c93172005-04-21 23:48:37 +00002860 // If the LHS is a cast from an integral value of the same size,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002861 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2862 Value *CastOp = Cast->getOperand(0);
2863 const Type *SrcTy = CastOp->getType();
2864 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2865 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2866 SrcTySize == Cast->getType()->getPrimitiveSize()) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00002867 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattner2b55ea32004-02-23 07:16:20 +00002868 "Source and destination signednesses should differ!");
2869 if (Cast->getType()->isSigned()) {
2870 // If this is a signed comparison, check for comparisons in the
2871 // vicinity of zero.
2872 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2873 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002874 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002875 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2876 else if (I.getOpcode() == Instruction::SetGT &&
2877 cast<ConstantSInt>(CI)->getValue() == -1)
2878 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002879 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002880 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2881 } else {
2882 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2883 if (I.getOpcode() == Instruction::SetLT &&
2884 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2885 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002886 return BinaryOperator::createSetGT(CastOp,
2887 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002888 else if (I.getOpcode() == Instruction::SetGT &&
2889 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2890 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002891 return BinaryOperator::createSetLT(CastOp,
2892 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002893 }
2894 }
2895 }
Chris Lattnere967b342003-06-04 05:10:11 +00002896 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002897 }
2898
Chris Lattner0798af32005-01-13 20:14:25 +00002899 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2900 if (User *GEP = dyn_castGetElementPtr(Op0))
2901 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2902 return NI;
2903 if (User *GEP = dyn_castGetElementPtr(Op1))
2904 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2905 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2906 return NI;
2907
Chris Lattner16930792003-11-03 04:25:02 +00002908 // Test to see if the operands of the setcc are casted versions of other
2909 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002910 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2911 Value *CastOp0 = CI->getOperand(0);
2912 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002913 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002914 (I.getOpcode() == Instruction::SetEQ ||
2915 I.getOpcode() == Instruction::SetNE)) {
2916 // We keep moving the cast from the left operand over to the right
2917 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002918 Op0 = CastOp0;
Misha Brukmanb1c93172005-04-21 23:48:37 +00002919
Chris Lattner16930792003-11-03 04:25:02 +00002920 // If operand #1 is a cast instruction, see if we can eliminate it as
2921 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002922 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2923 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002924 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002925 Op1 = CI2->getOperand(0);
Misha Brukmanb1c93172005-04-21 23:48:37 +00002926
Chris Lattner16930792003-11-03 04:25:02 +00002927 // If Op1 is a constant, we can fold the cast into the constant.
2928 if (Op1->getType() != Op0->getType())
2929 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2930 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2931 } else {
2932 // Otherwise, cast the RHS right before the setcc
2933 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2934 InsertNewInstBefore(cast<Instruction>(Op1), I);
2935 }
2936 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2937 }
2938
Chris Lattner6444c372003-11-03 05:17:03 +00002939 // Handle the special case of: setcc (cast bool to X), <cst>
2940 // This comes up when you have code like
2941 // int X = A < B;
2942 // if (X) ...
2943 // For generality, we handle any zero-extension of any operand comparison
2944 // with a constant.
2945 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2946 const Type *SrcTy = CastOp0->getType();
2947 const Type *DestTy = Op0->getType();
2948 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2949 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2950 // Ok, we have an expansion of operand 0 into a new type. Get the
2951 // constant value, masink off bits which are not set in the RHS. These
2952 // could be set if the destination value is signed.
2953 uint64_t ConstVal = ConstantRHS->getRawValue();
2954 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2955
2956 // If the constant we are comparing it with has high bits set, which
2957 // don't exist in the original value, the values could never be equal,
2958 // because the source would be zero extended.
2959 unsigned SrcBits =
2960 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002961 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2962 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002963 switch (I.getOpcode()) {
2964 default: assert(0 && "Unknown comparison type!");
2965 case Instruction::SetEQ:
2966 return ReplaceInstUsesWith(I, ConstantBool::False);
2967 case Instruction::SetNE:
2968 return ReplaceInstUsesWith(I, ConstantBool::True);
2969 case Instruction::SetLT:
2970 case Instruction::SetLE:
2971 if (DestTy->isSigned() && HasSignBit)
2972 return ReplaceInstUsesWith(I, ConstantBool::False);
2973 return ReplaceInstUsesWith(I, ConstantBool::True);
2974 case Instruction::SetGT:
2975 case Instruction::SetGE:
2976 if (DestTy->isSigned() && HasSignBit)
2977 return ReplaceInstUsesWith(I, ConstantBool::True);
2978 return ReplaceInstUsesWith(I, ConstantBool::False);
2979 }
2980 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00002981
Chris Lattner6444c372003-11-03 05:17:03 +00002982 // Otherwise, we can replace the setcc with a setcc of the smaller
2983 // operand value.
2984 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2985 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2986 }
2987 }
2988 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002989 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002990}
2991
Misha Brukmanb1c93172005-04-21 23:48:37 +00002992// visitSetCondInstWithCastAndConstant - this method is part of the
Reid Spencer279fa252004-11-28 21:31:15 +00002993// visitSetCondInst method. It handles the situation where we have:
2994// (setcc (cast X to larger), CI)
Misha Brukmanb1c93172005-04-21 23:48:37 +00002995// It tries to remove the cast and even the setcc if the CI value
Reid Spencer279fa252004-11-28 21:31:15 +00002996// and range of the cast allow it.
2997Instruction *
2998InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2999 CastInst* LHSI,
3000 ConstantInt* CI) {
3001 const Type *SrcTy = LHSI->getOperand(0)->getType();
3002 const Type *DestTy = LHSI->getType();
Chris Lattner03f06f12005-01-17 03:20:02 +00003003 if (!SrcTy->isIntegral() || !DestTy->isIntegral())
3004 return 0;
3005
3006 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
3007 unsigned DestBits = DestTy->getPrimitiveSize()*8;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003008 if (SrcTy == Type::BoolTy)
Chris Lattner03f06f12005-01-17 03:20:02 +00003009 SrcBits = 1;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003010 if (DestTy == Type::BoolTy)
Chris Lattner03f06f12005-01-17 03:20:02 +00003011 DestBits = 1;
3012 if (SrcBits < DestBits) {
3013 // There are fewer bits in the source of the cast than in the result
3014 // of the cast. Any other case doesn't matter because the constant
3015 // value won't have changed due to sign extension.
3016 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
3017 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003018 // The constant value operand of the setCC before and after a
3019 // cast to the source type of the cast instruction is the same
3020 // value, so we just replace with the same setcc opcode, but
3021 // using the source value compared to the constant casted to the
3022 // source type.
Chris Lattner03f06f12005-01-17 03:20:02 +00003023 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
3024 CastInst* Cst = new CastInst(LHSI->getOperand(0),
3025 SrcTy->getUnsignedVersion(),
3026 LHSI->getName());
3027 InsertNewInstBefore(Cst,I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003028 return new SetCondInst(I.getOpcode(), Cst,
Chris Lattner03f06f12005-01-17 03:20:02 +00003029 ConstantExpr::getCast(CI,
3030 SrcTy->getUnsignedVersion()));
Reid Spencer279fa252004-11-28 21:31:15 +00003031 }
Chris Lattner03f06f12005-01-17 03:20:02 +00003032 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
3033 }
3034
Misha Brukmanb1c93172005-04-21 23:48:37 +00003035 // The constant value before and after a cast to the source type
3036 // is different, so various cases are possible depending on the
Chris Lattner03f06f12005-01-17 03:20:02 +00003037 // opcode and the signs of the types involved in the cast.
3038 switch (I.getOpcode()) {
3039 case Instruction::SetLT: {
3040 return 0;
3041 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
3042 Max = ConstantExpr::getCast(Max, DestTy);
3043 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
3044 }
3045 case Instruction::SetGT: {
3046 return 0; // FIXME! RENABLE. This breaks for (cast sbyte to uint) > 255
3047 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
3048 Min = ConstantExpr::getCast(Min, DestTy);
3049 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
3050 }
3051 case Instruction::SetEQ:
3052 // We're looking for equality, and we know the values are not
3053 // equal so replace with constant False.
3054 return ReplaceInstUsesWith(I, ConstantBool::False);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003055 case Instruction::SetNE:
Chris Lattner03f06f12005-01-17 03:20:02 +00003056 // We're testing for inequality, and we know the values are not
3057 // equal so replace with constant True.
3058 return ReplaceInstUsesWith(I, ConstantBool::True);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003059 case Instruction::SetLE:
3060 case Instruction::SetGE:
Chris Lattner03f06f12005-01-17 03:20:02 +00003061 assert(0 && "SetLE and SetGE should be handled elsewhere");
Misha Brukmanb1c93172005-04-21 23:48:37 +00003062 default:
Chris Lattner03f06f12005-01-17 03:20:02 +00003063 assert(0 && "unknown integer comparison");
Reid Spencer279fa252004-11-28 21:31:15 +00003064 }
3065 }
3066 return 0;
3067}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003068
3069
Chris Lattnere8d6c602003-03-10 19:16:08 +00003070Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003071 assert(I.getOperand(1)->getType() == Type::UByteTy);
3072 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003073 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003074
3075 // shl X, 0 == X and shr X, 0 == X
3076 // shl 0, X == 0 and shr 0, X == 0
3077 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003078 Op0 == Constant::getNullValue(Op0->getType()))
3079 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003080
Chris Lattner81a7a232004-10-16 18:11:37 +00003081 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3082 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003083 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003084 else // undef << X -> 0 AND undef >>u X -> 0
3085 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3086 }
3087 if (isa<UndefValue>(Op1)) {
3088 if (isLeftShift || I.getType()->isUnsigned())
3089 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3090 else
3091 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3092 }
3093
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003094 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3095 if (!isLeftShift)
3096 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3097 if (CSI->isAllOnesValue())
3098 return ReplaceInstUsesWith(I, CSI);
3099
Chris Lattner183b3362004-04-09 19:05:30 +00003100 // Try to fold constant and into select arguments.
3101 if (isa<Constant>(Op0))
3102 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003103 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003104 return R;
3105
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003106 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003107 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3108 // of a signed value.
3109 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00003110 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003111 if (CUI->getValue() >= TypeBits) {
3112 if (!Op0->getType()->isSigned() || isLeftShift)
3113 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3114 else {
3115 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3116 return &I;
3117 }
3118 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003119
Chris Lattnerede3fe02003-08-13 04:18:28 +00003120 // ((X*C1) << C2) == (X * (C1 << C2))
3121 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3122 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3123 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003124 return BinaryOperator::createMul(BO->getOperand(0),
3125 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanb1c93172005-04-21 23:48:37 +00003126
Chris Lattner183b3362004-04-09 19:05:30 +00003127 // Try to fold constant and into select arguments.
3128 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003129 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003130 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003131 if (isa<PHINode>(Op0))
3132 if (Instruction *NV = FoldOpIntoPhi(I))
3133 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003134
Chris Lattner86102b82005-01-01 16:22:27 +00003135 if (Op0->hasOneUse()) {
3136 // If this is a SHL of a sign-extending cast, see if we can turn the input
3137 // into a zero extending cast (a simple strength reduction).
3138 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3139 const Type *SrcTy = CI->getOperand(0)->getType();
3140 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3141 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
3142 // We can change it to a zero extension if we are shifting out all of
3143 // the sign extended bits. To check this, form a mask of all of the
3144 // sign extend bits, then shift them left and see if we have anything
3145 // left.
3146 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3147 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3148 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3149 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3150 // If the shift is nuking all of the sign bits, change this to a
3151 // zero extension cast. To do this, cast the cast input to
3152 // unsigned, then to the requested size.
3153 Value *CastOp = CI->getOperand(0);
3154 Instruction *NC =
3155 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3156 CI->getName()+".uns");
3157 NC = InsertNewInstBefore(NC, I);
3158 // Finally, insert a replacement for CI.
3159 NC = new CastInst(NC, CI->getType(), CI->getName());
3160 CI->setName("");
3161 NC = InsertNewInstBefore(NC, I);
3162 WorkList.push_back(CI); // Delete CI later.
3163 I.setOperand(0, NC);
3164 return &I; // The SHL operand was modified.
3165 }
3166 }
3167 }
3168
3169 // If the operand is an bitwise operator with a constant RHS, and the
3170 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003171 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3172 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3173 bool isValid = true; // Valid only for And, Or, Xor
3174 bool highBitSet = false; // Transform if high bit of constant set?
3175
3176 switch (Op0BO->getOpcode()) {
3177 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003178 case Instruction::Add:
3179 isValid = isLeftShift;
3180 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003181 case Instruction::Or:
3182 case Instruction::Xor:
3183 highBitSet = false;
3184 break;
3185 case Instruction::And:
3186 highBitSet = true;
3187 break;
3188 }
3189
3190 // If this is a signed shift right, and the high bit is modified
3191 // by the logical operation, do not perform the transformation.
3192 // The highBitSet boolean indicates the value of the high bit of
3193 // the constant which would cause it to be modified for this
3194 // operation.
3195 //
3196 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3197 uint64_t Val = Op0C->getRawValue();
3198 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3199 }
3200
3201 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003202 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003203
3204 Instruction *NewShift =
3205 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3206 Op0BO->getName());
3207 Op0BO->setName("");
3208 InsertNewInstBefore(NewShift, I);
3209
3210 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3211 NewRHS);
3212 }
3213 }
Chris Lattner86102b82005-01-01 16:22:27 +00003214 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003215
Chris Lattner3204d4e2003-07-24 17:52:58 +00003216 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003217 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003218 if (ConstantUInt *ShiftAmt1C =
3219 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003220 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3221 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanb1c93172005-04-21 23:48:37 +00003222
Chris Lattner3204d4e2003-07-24 17:52:58 +00003223 // Check for (A << c1) << c2 and (A >> c1) >> c2
3224 if (I.getOpcode() == Op0SI->getOpcode()) {
3225 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003226 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
3227 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00003228 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3229 ConstantUInt::get(Type::UByteTy, Amt));
3230 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003231
Chris Lattnerab780df2003-07-24 18:38:56 +00003232 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3233 // signed types, we can only support the (A >> c1) << c2 configuration,
3234 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003235 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003236 // Calculate bitmask for what gets shifted off the edge...
3237 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003238 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003239 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003240 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003241 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003242
Chris Lattner3204d4e2003-07-24 17:52:58 +00003243 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003244 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3245 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003246 InsertNewInstBefore(Mask, I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00003247
Chris Lattner3204d4e2003-07-24 17:52:58 +00003248 // Figure out what flavor of shift we should use...
3249 if (ShiftAmt1 == ShiftAmt2)
3250 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3251 else if (ShiftAmt1 < ShiftAmt2) {
3252 return new ShiftInst(I.getOpcode(), Mask,
3253 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3254 } else {
3255 return new ShiftInst(Op0SI->getOpcode(), Mask,
3256 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3257 }
3258 }
3259 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003260 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003261
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003262 return 0;
3263}
3264
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003265enum CastType {
3266 Noop = 0,
3267 Truncate = 1,
3268 Signext = 2,
3269 Zeroext = 3
3270};
3271
3272/// getCastType - In the future, we will split the cast instruction into these
3273/// various types. Until then, we have to do the analysis here.
3274static CastType getCastType(const Type *Src, const Type *Dest) {
3275 assert(Src->isIntegral() && Dest->isIntegral() &&
3276 "Only works on integral types!");
3277 unsigned SrcSize = Src->getPrimitiveSize()*8;
3278 if (Src == Type::BoolTy) SrcSize = 1;
3279 unsigned DestSize = Dest->getPrimitiveSize()*8;
3280 if (Dest == Type::BoolTy) DestSize = 1;
3281
3282 if (SrcSize == DestSize) return Noop;
3283 if (SrcSize > DestSize) return Truncate;
3284 if (Src->isSigned()) return Signext;
3285 return Zeroext;
3286}
3287
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003288
Chris Lattner48a44f72002-05-02 17:06:02 +00003289// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3290// instruction.
3291//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003292static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003293 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003294
Chris Lattner650b6da2002-08-02 20:00:25 +00003295 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanb1c93172005-04-21 23:48:37 +00003296 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003297 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003298 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003299 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003300
Chris Lattner4fbad962004-07-21 04:27:24 +00003301 // If we are casting between pointer and integer types, treat pointers as
3302 // integers of the appropriate size for the code below.
3303 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3304 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3305 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003306
Chris Lattner48a44f72002-05-02 17:06:02 +00003307 // Allow free casting and conversion of sizes as long as the sign doesn't
3308 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003309 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003310 CastType FirstCast = getCastType(SrcTy, MidTy);
3311 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003312
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003313 // Capture the effect of these two casts. If the result is a legal cast,
3314 // the CastType is stored here, otherwise a special code is used.
3315 static const unsigned CastResult[] = {
3316 // First cast is noop
3317 0, 1, 2, 3,
3318 // First cast is a truncate
3319 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3320 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003321 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003322 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003323 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003324 };
3325
3326 unsigned Result = CastResult[FirstCast*4+SecondCast];
3327 switch (Result) {
3328 default: assert(0 && "Illegal table value!");
3329 case 0:
3330 case 1:
3331 case 2:
3332 case 3:
3333 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3334 // truncates, we could eliminate more casts.
3335 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3336 case 4:
3337 return false; // Not possible to eliminate this here.
3338 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003339 // Sign or zero extend followed by truncate is always ok if the result
3340 // is a truncate or noop.
3341 CastType ResultCast = getCastType(SrcTy, DstTy);
3342 if (ResultCast == Noop || ResultCast == Truncate)
3343 return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00003344 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner1638de42004-07-21 19:50:44 +00003345 // result will match the sign/zeroextendness of the result.
3346 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003347 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003348 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003349 return false;
3350}
3351
Chris Lattner11ffd592004-07-20 05:21:00 +00003352static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003353 if (V->getType() == Ty || isa<Constant>(V)) return false;
3354 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003355 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3356 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003357 return false;
3358 return true;
3359}
3360
3361/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3362/// InsertBefore instruction. This is specialized a bit to avoid inserting
3363/// casts that are known to not do anything...
3364///
3365Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3366 Instruction *InsertBefore) {
3367 if (V->getType() == DestTy) return V;
3368 if (Constant *C = dyn_cast<Constant>(V))
3369 return ConstantExpr::getCast(C, DestTy);
3370
3371 CastInst *CI = new CastInst(V, DestTy, V->getName());
3372 InsertNewInstBefore(CI, *InsertBefore);
3373 return CI;
3374}
Chris Lattner48a44f72002-05-02 17:06:02 +00003375
3376// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003377//
Chris Lattner113f4f42002-06-25 16:13:24 +00003378Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003379 Value *Src = CI.getOperand(0);
3380
Chris Lattner48a44f72002-05-02 17:06:02 +00003381 // If the user is casting a value to the same type, eliminate this cast
3382 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003383 if (CI.getType() == Src->getType())
3384 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003385
Chris Lattner81a7a232004-10-16 18:11:37 +00003386 if (isa<UndefValue>(Src)) // cast undef -> undef
3387 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3388
Chris Lattner48a44f72002-05-02 17:06:02 +00003389 // If casting the result of another cast instruction, try to eliminate this
3390 // one!
3391 //
Chris Lattner86102b82005-01-01 16:22:27 +00003392 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3393 Value *A = CSrc->getOperand(0);
3394 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3395 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003396 // This instruction now refers directly to the cast's src operand. This
3397 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003398 CI.setOperand(0, CSrc->getOperand(0));
3399 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003400 }
3401
Chris Lattner650b6da2002-08-02 20:00:25 +00003402 // If this is an A->B->A cast, and we are dealing with integral types, try
3403 // to convert this into a logical 'and' instruction.
3404 //
Misha Brukmanb1c93172005-04-21 23:48:37 +00003405 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003406 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003407 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
3408 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()&&
3409 A->getType()->getPrimitiveSize() == CI.getType()->getPrimitiveSize()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003410 assert(CSrc->getType() != Type::ULongTy &&
3411 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00003412 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner86102b82005-01-01 16:22:27 +00003413 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3414 AndValue);
3415 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3416 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3417 if (And->getType() != CI.getType()) {
3418 And->setName(CSrc->getName()+".mask");
3419 InsertNewInstBefore(And, CI);
3420 And = new CastInst(And, CI.getType());
3421 }
3422 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003423 }
3424 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003425
Chris Lattner03841652004-05-25 04:29:21 +00003426 // If this is a cast to bool, turn it into the appropriate setne instruction.
3427 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003428 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003429 Constant::getNullValue(CI.getOperand(0)->getType()));
3430
Chris Lattnerd0d51602003-06-21 23:12:02 +00003431 // If casting the result of a getelementptr instruction with no offset, turn
3432 // this into a cast of the original pointer!
3433 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003434 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003435 bool AllZeroOperands = true;
3436 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3437 if (!isa<Constant>(GEP->getOperand(i)) ||
3438 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3439 AllZeroOperands = false;
3440 break;
3441 }
3442 if (AllZeroOperands) {
3443 CI.setOperand(0, GEP->getOperand(0));
3444 return &CI;
3445 }
3446 }
3447
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003448 // If we are casting a malloc or alloca to a pointer to a type of the same
3449 // size, rewrite the allocation instruction to allocate the "right" type.
3450 //
3451 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003452 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003453 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3454 // Get the type really allocated and the type casted to...
3455 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003456 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003457 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003458 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3459 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003460
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003461 // If the allocation is for an even multiple of the cast type size
3462 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00003463 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003464 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003465 std::string Name = AI->getName(); AI->setName("");
3466 AllocationInst *New;
3467 if (isa<MallocInst>(AI))
3468 New = new MallocInst(CastElTy, Amt, Name);
3469 else
3470 New = new AllocaInst(CastElTy, Amt, Name);
3471 InsertNewInstBefore(New, *AI);
3472 return ReplaceInstUsesWith(CI, New);
3473 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003474 }
3475 }
3476
Chris Lattner86102b82005-01-01 16:22:27 +00003477 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3478 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3479 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003480 if (isa<PHINode>(Src))
3481 if (Instruction *NV = FoldOpIntoPhi(CI))
3482 return NV;
3483
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003484 // If the source value is an instruction with only this use, we can attempt to
3485 // propagate the cast into the instruction. Also, only handle integral types
3486 // for now.
3487 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003488 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003489 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3490 const Type *DestTy = CI.getType();
3491 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3492 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3493
3494 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3495 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3496
3497 switch (SrcI->getOpcode()) {
3498 case Instruction::Add:
3499 case Instruction::Mul:
3500 case Instruction::And:
3501 case Instruction::Or:
3502 case Instruction::Xor:
3503 // If we are discarding information, or just changing the sign, rewrite.
3504 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3505 // Don't insert two casts if they cannot be eliminated. We allow two
3506 // casts to be inserted if the sizes are the same. This could only be
3507 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003508 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3509 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003510 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3511 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3512 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3513 ->getOpcode(), Op0c, Op1c);
3514 }
3515 }
3516 break;
3517 case Instruction::Shl:
3518 // Allow changing the sign of the source operand. Do not allow changing
3519 // the size of the shift, UNLESS the shift amount is a constant. We
3520 // mush not change variable sized shifts to a smaller size, because it
3521 // is undefined to shift more bits out than exist in the value.
3522 if (DestBitSize == SrcBitSize ||
3523 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3524 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3525 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3526 }
3527 break;
3528 }
3529 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003530
Chris Lattner260ab202002-04-18 17:39:14 +00003531 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003532}
3533
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003534/// GetSelectFoldableOperands - We want to turn code that looks like this:
3535/// %C = or %A, %B
3536/// %D = select %cond, %C, %A
3537/// into:
3538/// %C = select %cond, %B, 0
3539/// %D = or %A, %C
3540///
3541/// Assuming that the specified instruction is an operand to the select, return
3542/// a bitmask indicating which operands of this instruction are foldable if they
3543/// equal the other incoming value of the select.
3544///
3545static unsigned GetSelectFoldableOperands(Instruction *I) {
3546 switch (I->getOpcode()) {
3547 case Instruction::Add:
3548 case Instruction::Mul:
3549 case Instruction::And:
3550 case Instruction::Or:
3551 case Instruction::Xor:
3552 return 3; // Can fold through either operand.
3553 case Instruction::Sub: // Can only fold on the amount subtracted.
3554 case Instruction::Shl: // Can only fold on the shift amount.
3555 case Instruction::Shr:
Misha Brukmanb1c93172005-04-21 23:48:37 +00003556 return 1;
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003557 default:
3558 return 0; // Cannot fold
3559 }
3560}
3561
3562/// GetSelectFoldableConstant - For the same transformation as the previous
3563/// function, return the identity constant that goes into the select.
3564static Constant *GetSelectFoldableConstant(Instruction *I) {
3565 switch (I->getOpcode()) {
3566 default: assert(0 && "This cannot happen!"); abort();
3567 case Instruction::Add:
3568 case Instruction::Sub:
3569 case Instruction::Or:
3570 case Instruction::Xor:
3571 return Constant::getNullValue(I->getType());
3572 case Instruction::Shl:
3573 case Instruction::Shr:
3574 return Constant::getNullValue(Type::UByteTy);
3575 case Instruction::And:
3576 return ConstantInt::getAllOnesValue(I->getType());
3577 case Instruction::Mul:
3578 return ConstantInt::get(I->getType(), 1);
3579 }
3580}
3581
Chris Lattner411336f2005-01-19 21:50:18 +00003582/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3583/// have the same opcode and only one use each. Try to simplify this.
3584Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3585 Instruction *FI) {
3586 if (TI->getNumOperands() == 1) {
3587 // If this is a non-volatile load or a cast from the same type,
3588 // merge.
3589 if (TI->getOpcode() == Instruction::Cast) {
3590 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3591 return 0;
3592 } else {
3593 return 0; // unknown unary op.
3594 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003595
Chris Lattner411336f2005-01-19 21:50:18 +00003596 // Fold this by inserting a select from the input values.
3597 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3598 FI->getOperand(0), SI.getName()+".v");
3599 InsertNewInstBefore(NewSI, SI);
3600 return new CastInst(NewSI, TI->getType());
3601 }
3602
3603 // Only handle binary operators here.
3604 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3605 return 0;
3606
3607 // Figure out if the operations have any operands in common.
3608 Value *MatchOp, *OtherOpT, *OtherOpF;
3609 bool MatchIsOpZero;
3610 if (TI->getOperand(0) == FI->getOperand(0)) {
3611 MatchOp = TI->getOperand(0);
3612 OtherOpT = TI->getOperand(1);
3613 OtherOpF = FI->getOperand(1);
3614 MatchIsOpZero = true;
3615 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3616 MatchOp = TI->getOperand(1);
3617 OtherOpT = TI->getOperand(0);
3618 OtherOpF = FI->getOperand(0);
3619 MatchIsOpZero = false;
3620 } else if (!TI->isCommutative()) {
3621 return 0;
3622 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3623 MatchOp = TI->getOperand(0);
3624 OtherOpT = TI->getOperand(1);
3625 OtherOpF = FI->getOperand(0);
3626 MatchIsOpZero = true;
3627 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3628 MatchOp = TI->getOperand(1);
3629 OtherOpT = TI->getOperand(0);
3630 OtherOpF = FI->getOperand(1);
3631 MatchIsOpZero = true;
3632 } else {
3633 return 0;
3634 }
3635
3636 // If we reach here, they do have operations in common.
3637 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3638 OtherOpF, SI.getName()+".v");
3639 InsertNewInstBefore(NewSI, SI);
3640
3641 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3642 if (MatchIsOpZero)
3643 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3644 else
3645 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3646 } else {
3647 if (MatchIsOpZero)
3648 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3649 else
3650 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3651 }
3652}
3653
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003654Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003655 Value *CondVal = SI.getCondition();
3656 Value *TrueVal = SI.getTrueValue();
3657 Value *FalseVal = SI.getFalseValue();
3658
3659 // select true, X, Y -> X
3660 // select false, X, Y -> Y
3661 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003662 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003663 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003664 else {
3665 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003666 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003667 }
Chris Lattner533bc492004-03-30 19:37:13 +00003668
3669 // select C, X, X -> X
3670 if (TrueVal == FalseVal)
3671 return ReplaceInstUsesWith(SI, TrueVal);
3672
Chris Lattner81a7a232004-10-16 18:11:37 +00003673 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3674 return ReplaceInstUsesWith(SI, FalseVal);
3675 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3676 return ReplaceInstUsesWith(SI, TrueVal);
3677 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3678 if (isa<Constant>(TrueVal))
3679 return ReplaceInstUsesWith(SI, TrueVal);
3680 else
3681 return ReplaceInstUsesWith(SI, FalseVal);
3682 }
3683
Chris Lattner1c631e82004-04-08 04:43:23 +00003684 if (SI.getType() == Type::BoolTy)
3685 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3686 if (C == ConstantBool::True) {
3687 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003688 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003689 } else {
3690 // Change: A = select B, false, C --> A = and !B, C
3691 Value *NotCond =
3692 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3693 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003694 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003695 }
3696 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3697 if (C == ConstantBool::False) {
3698 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003699 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003700 } else {
3701 // Change: A = select B, C, true --> A = or !B, C
3702 Value *NotCond =
3703 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3704 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003705 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003706 }
3707 }
3708
Chris Lattner183b3362004-04-09 19:05:30 +00003709 // Selecting between two integer constants?
3710 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3711 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3712 // select C, 1, 0 -> cast C to int
3713 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3714 return new CastInst(CondVal, SI.getType());
3715 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3716 // select C, 0, 1 -> cast !C to int
3717 Value *NotCond =
3718 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003719 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003720 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003721 }
Chris Lattner35167c32004-06-09 07:59:58 +00003722
3723 // If one of the constants is zero (we know they can't both be) and we
3724 // have a setcc instruction with zero, and we have an 'and' with the
3725 // non-constant value, eliminate this whole mess. This corresponds to
3726 // cases like this: ((X & 27) ? 27 : 0)
3727 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3728 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3729 if ((IC->getOpcode() == Instruction::SetEQ ||
3730 IC->getOpcode() == Instruction::SetNE) &&
3731 isa<ConstantInt>(IC->getOperand(1)) &&
3732 cast<Constant>(IC->getOperand(1))->isNullValue())
3733 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3734 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00003735 isa<ConstantInt>(ICA->getOperand(1)) &&
3736 (ICA->getOperand(1) == TrueValC ||
3737 ICA->getOperand(1) == FalseValC) &&
Chris Lattner35167c32004-06-09 07:59:58 +00003738 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3739 // Okay, now we know that everything is set up, we just don't
3740 // know whether we have a setne or seteq and whether the true or
3741 // false val is the zero.
3742 bool ShouldNotVal = !TrueValC->isNullValue();
3743 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3744 Value *V = ICA;
3745 if (ShouldNotVal)
3746 V = InsertNewInstBefore(BinaryOperator::create(
3747 Instruction::Xor, V, ICA->getOperand(1)), SI);
3748 return ReplaceInstUsesWith(SI, V);
3749 }
Chris Lattner533bc492004-03-30 19:37:13 +00003750 }
Chris Lattner623fba12004-04-10 22:21:27 +00003751
3752 // See if we are selecting two values based on a comparison of the two values.
3753 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3754 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3755 // Transform (X == Y) ? X : Y -> Y
3756 if (SCI->getOpcode() == Instruction::SetEQ)
3757 return ReplaceInstUsesWith(SI, FalseVal);
3758 // Transform (X != Y) ? X : Y -> X
3759 if (SCI->getOpcode() == Instruction::SetNE)
3760 return ReplaceInstUsesWith(SI, TrueVal);
3761 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3762
3763 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3764 // Transform (X == Y) ? Y : X -> X
3765 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003766 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003767 // Transform (X != Y) ? Y : X -> Y
3768 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003769 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003770 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3771 }
3772 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003773
Chris Lattnera04c9042005-01-13 22:52:24 +00003774 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3775 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3776 if (TI->hasOneUse() && FI->hasOneUse()) {
3777 bool isInverse = false;
3778 Instruction *AddOp = 0, *SubOp = 0;
3779
Chris Lattner411336f2005-01-19 21:50:18 +00003780 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3781 if (TI->getOpcode() == FI->getOpcode())
3782 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3783 return IV;
3784
3785 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3786 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00003787 if (TI->getOpcode() == Instruction::Sub &&
3788 FI->getOpcode() == Instruction::Add) {
3789 AddOp = FI; SubOp = TI;
3790 } else if (FI->getOpcode() == Instruction::Sub &&
3791 TI->getOpcode() == Instruction::Add) {
3792 AddOp = TI; SubOp = FI;
3793 }
3794
3795 if (AddOp) {
3796 Value *OtherAddOp = 0;
3797 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3798 OtherAddOp = AddOp->getOperand(1);
3799 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3800 OtherAddOp = AddOp->getOperand(0);
3801 }
3802
3803 if (OtherAddOp) {
3804 // So at this point we know we have:
3805 // select C, (add X, Y), (sub X, ?)
3806 // We can do the transform profitably if either 'Y' = '?' or '?' is
3807 // a constant.
3808 if (SubOp->getOperand(1) == AddOp ||
3809 isa<Constant>(SubOp->getOperand(1))) {
3810 Value *NegVal;
3811 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3812 NegVal = ConstantExpr::getNeg(C);
3813 } else {
3814 NegVal = InsertNewInstBefore(
3815 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3816 }
3817
Chris Lattner51726c42005-01-14 17:35:12 +00003818 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00003819 Value *NewFalseOp = NegVal;
3820 if (AddOp != TI)
3821 std::swap(NewTrueOp, NewFalseOp);
3822 Instruction *NewSel =
3823 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanb1c93172005-04-21 23:48:37 +00003824
Chris Lattnera04c9042005-01-13 22:52:24 +00003825 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00003826 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00003827 }
3828 }
3829 }
3830 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00003831
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003832 // See if we can fold the select into one of our operands.
3833 if (SI.getType()->isInteger()) {
3834 // See the comment above GetSelectFoldableOperands for a description of the
3835 // transformation we are doing here.
3836 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3837 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3838 !isa<Constant>(FalseVal))
3839 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3840 unsigned OpToFold = 0;
3841 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3842 OpToFold = 1;
3843 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3844 OpToFold = 2;
3845 }
3846
3847 if (OpToFold) {
3848 Constant *C = GetSelectFoldableConstant(TVI);
3849 std::string Name = TVI->getName(); TVI->setName("");
3850 Instruction *NewSel =
3851 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3852 Name);
3853 InsertNewInstBefore(NewSel, SI);
3854 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3855 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3856 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3857 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3858 else {
3859 assert(0 && "Unknown instruction!!");
3860 }
3861 }
3862 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003863
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003864 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3865 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3866 !isa<Constant>(TrueVal))
3867 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3868 unsigned OpToFold = 0;
3869 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3870 OpToFold = 1;
3871 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3872 OpToFold = 2;
3873 }
3874
3875 if (OpToFold) {
3876 Constant *C = GetSelectFoldableConstant(FVI);
3877 std::string Name = FVI->getName(); FVI->setName("");
3878 Instruction *NewSel =
3879 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3880 Name);
3881 InsertNewInstBefore(NewSel, SI);
3882 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3883 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3884 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3885 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3886 else {
3887 assert(0 && "Unknown instruction!!");
3888 }
3889 }
3890 }
3891 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003892 return 0;
3893}
3894
3895
Chris Lattner970c33a2003-06-19 17:00:31 +00003896// CallInst simplification
3897//
3898Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003899 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3900 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003901 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3902 bool Changed = false;
3903
3904 // memmove/cpy/set of zero bytes is a noop.
3905 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3906 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3907
3908 // FIXME: Increase alignment here.
Misha Brukmanb1c93172005-04-21 23:48:37 +00003909
Chris Lattner00648e12004-10-12 04:52:52 +00003910 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3911 if (CI->getRawValue() == 1) {
3912 // Replace the instruction with just byte operations. We would
3913 // transform other cases to loads/stores, but we don't know if
3914 // alignment is sufficient.
3915 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003916 }
3917
Chris Lattner00648e12004-10-12 04:52:52 +00003918 // If we have a memmove and the source operation is a constant global,
3919 // then the source and dest pointers can't alias, so we can change this
3920 // into a call to memcpy.
3921 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3922 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3923 if (GVSrc->isConstant()) {
3924 Module *M = CI.getParent()->getParent()->getParent();
3925 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3926 CI.getCalledFunction()->getFunctionType());
3927 CI.setOperand(0, MemCpy);
3928 Changed = true;
3929 }
3930
3931 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003932 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3933 // If this stoppoint is at the same source location as the previous
3934 // stoppoint in the chain, it is not needed.
3935 if (DbgStopPointInst *PrevSPI =
3936 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3937 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3938 SPI->getColNo() == PrevSPI->getColNo()) {
3939 SPI->replaceAllUsesWith(PrevSPI);
3940 return EraseInstFromFunction(CI);
3941 }
Chris Lattner00648e12004-10-12 04:52:52 +00003942 }
3943
Chris Lattneraec3d942003-10-07 22:32:43 +00003944 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003945}
3946
3947// InvokeInst simplification
3948//
3949Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003950 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003951}
3952
Chris Lattneraec3d942003-10-07 22:32:43 +00003953// visitCallSite - Improvements for call and invoke instructions.
3954//
3955Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003956 bool Changed = false;
3957
3958 // If the callee is a constexpr cast of a function, attempt to move the cast
3959 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003960 if (transformConstExprCastCall(CS)) return 0;
3961
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003962 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003963
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003964 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3965 // This instruction is not reachable, just remove it. We insert a store to
3966 // undef so that we know that this code is not reachable, despite the fact
3967 // that we can't modify the CFG here.
3968 new StoreInst(ConstantBool::True,
3969 UndefValue::get(PointerType::get(Type::BoolTy)),
3970 CS.getInstruction());
3971
3972 if (!CS.getInstruction()->use_empty())
3973 CS.getInstruction()->
3974 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3975
3976 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3977 // Don't break the CFG, insert a dummy cond branch.
3978 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3979 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003980 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003981 return EraseInstFromFunction(*CS.getInstruction());
3982 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003983
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003984 const PointerType *PTy = cast<PointerType>(Callee->getType());
3985 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3986 if (FTy->isVarArg()) {
3987 // See if we can optimize any arguments passed through the varargs area of
3988 // the call.
3989 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3990 E = CS.arg_end(); I != E; ++I)
3991 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3992 // If this cast does not effect the value passed through the varargs
3993 // area, we can eliminate the use of the cast.
3994 Value *Op = CI->getOperand(0);
3995 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3996 *I = Op;
3997 Changed = true;
3998 }
3999 }
4000 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004001
Chris Lattner75b4d1d2003-10-07 22:54:13 +00004002 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00004003}
4004
Chris Lattner970c33a2003-06-19 17:00:31 +00004005// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4006// attempt to move the cast to the arguments of the call/invoke.
4007//
4008bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4009 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4010 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00004011 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00004012 return false;
Reid Spencer87436872004-07-18 00:38:32 +00004013 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00004014 Instruction *Caller = CS.getInstruction();
4015
4016 // Okay, this is a cast from a function to a different type. Unless doing so
4017 // would cause a type conversion of one of our arguments, change this call to
4018 // be a direct call with arguments casted to the appropriate types.
4019 //
4020 const FunctionType *FT = Callee->getFunctionType();
4021 const Type *OldRetTy = Caller->getType();
4022
Chris Lattner1f7942f2004-01-14 06:06:08 +00004023 // Check to see if we are changing the return type...
4024 if (OldRetTy != FT->getReturnType()) {
4025 if (Callee->isExternal() &&
4026 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4027 !Caller->use_empty())
4028 return false; // Cannot transform this return value...
4029
4030 // If the callsite is an invoke instruction, and the return value is used by
4031 // a PHI node in a successor, we cannot change the return type of the call
4032 // because there is no place to put the cast instruction (without breaking
4033 // the critical edge). Bail out in this case.
4034 if (!Caller->use_empty())
4035 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4036 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4037 UI != E; ++UI)
4038 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4039 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004040 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004041 return false;
4042 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004043
4044 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4045 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004046
Chris Lattner970c33a2003-06-19 17:00:31 +00004047 CallSite::arg_iterator AI = CS.arg_begin();
4048 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4049 const Type *ParamTy = FT->getParamType(i);
4050 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004051 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner970c33a2003-06-19 17:00:31 +00004052 }
4053
4054 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4055 Callee->isExternal())
4056 return false; // Do not delete arguments unless we have a function body...
4057
4058 // Okay, we decided that this is a safe thing to do: go ahead and start
4059 // inserting cast instructions as necessary...
4060 std::vector<Value*> Args;
4061 Args.reserve(NumActualArgs);
4062
4063 AI = CS.arg_begin();
4064 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4065 const Type *ParamTy = FT->getParamType(i);
4066 if ((*AI)->getType() == ParamTy) {
4067 Args.push_back(*AI);
4068 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004069 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4070 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004071 }
4072 }
4073
4074 // If the function takes more arguments than the call was taking, add them
4075 // now...
4076 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4077 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4078
4079 // If we are removing arguments to the function, emit an obnoxious warning...
4080 if (FT->getNumParams() < NumActualArgs)
4081 if (!FT->isVarArg()) {
4082 std::cerr << "WARNING: While resolving call to function '"
4083 << Callee->getName() << "' arguments were dropped!\n";
4084 } else {
4085 // Add all of the arguments in their promoted form to the arg list...
4086 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4087 const Type *PTy = getPromotedType((*AI)->getType());
4088 if (PTy != (*AI)->getType()) {
4089 // Must promote to pass through va_arg area!
4090 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4091 InsertNewInstBefore(Cast, *Caller);
4092 Args.push_back(Cast);
4093 } else {
4094 Args.push_back(*AI);
4095 }
4096 }
4097 }
4098
4099 if (FT->getReturnType() == Type::VoidTy)
4100 Caller->setName(""); // Void type should not have a name...
4101
4102 Instruction *NC;
4103 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004104 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004105 Args, Caller->getName(), Caller);
4106 } else {
4107 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4108 }
4109
4110 // Insert a cast of the return type as necessary...
4111 Value *NV = NC;
4112 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4113 if (NV->getType() != Type::VoidTy) {
4114 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004115
4116 // If this is an invoke instruction, we should insert it after the first
4117 // non-phi, instruction in the normal successor block.
4118 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4119 BasicBlock::iterator I = II->getNormalDest()->begin();
4120 while (isa<PHINode>(I)) ++I;
4121 InsertNewInstBefore(NC, *I);
4122 } else {
4123 // Otherwise, it's a call, just insert cast right after the call instr
4124 InsertNewInstBefore(NC, *Caller);
4125 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004126 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004127 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004128 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004129 }
4130 }
4131
4132 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4133 Caller->replaceAllUsesWith(NV);
4134 Caller->getParent()->getInstList().erase(Caller);
4135 removeFromWorkList(Caller);
4136 return true;
4137}
4138
4139
Chris Lattner7515cab2004-11-14 19:13:23 +00004140// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4141// operator and they all are only used by the PHI, PHI together their
4142// inputs, and do the operation once, to the result of the PHI.
4143Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4144 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4145
4146 // Scan the instruction, looking for input operations that can be folded away.
4147 // If all input operands to the phi are the same instruction (e.g. a cast from
4148 // the same type or "+42") we can pull the operation through the PHI, reducing
4149 // code size and simplifying code.
4150 Constant *ConstantOp = 0;
4151 const Type *CastSrcTy = 0;
4152 if (isa<CastInst>(FirstInst)) {
4153 CastSrcTy = FirstInst->getOperand(0)->getType();
4154 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4155 // Can fold binop or shift if the RHS is a constant.
4156 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4157 if (ConstantOp == 0) return 0;
4158 } else {
4159 return 0; // Cannot fold this operation.
4160 }
4161
4162 // Check to see if all arguments are the same operation.
4163 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4164 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4165 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4166 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4167 return 0;
4168 if (CastSrcTy) {
4169 if (I->getOperand(0)->getType() != CastSrcTy)
4170 return 0; // Cast operation must match.
4171 } else if (I->getOperand(1) != ConstantOp) {
4172 return 0;
4173 }
4174 }
4175
4176 // Okay, they are all the same operation. Create a new PHI node of the
4177 // correct type, and PHI together all of the LHS's of the instructions.
4178 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4179 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004180 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004181
4182 Value *InVal = FirstInst->getOperand(0);
4183 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004184
4185 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004186 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4187 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4188 if (NewInVal != InVal)
4189 InVal = 0;
4190 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4191 }
4192
4193 Value *PhiVal;
4194 if (InVal) {
4195 // The new PHI unions all of the same values together. This is really
4196 // common, so we handle it intelligently here for compile-time speed.
4197 PhiVal = InVal;
4198 delete NewPN;
4199 } else {
4200 InsertNewInstBefore(NewPN, PN);
4201 PhiVal = NewPN;
4202 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004203
Chris Lattner7515cab2004-11-14 19:13:23 +00004204 // Insert and return the new operation.
4205 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004206 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004207 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004208 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004209 else
4210 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004211 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004212}
Chris Lattner48a44f72002-05-02 17:06:02 +00004213
Chris Lattner71536432005-01-17 05:10:15 +00004214/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4215/// that is dead.
4216static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4217 if (PN->use_empty()) return true;
4218 if (!PN->hasOneUse()) return false;
4219
4220 // Remember this node, and if we find the cycle, return.
4221 if (!PotentiallyDeadPHIs.insert(PN).second)
4222 return true;
4223
4224 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4225 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004226
Chris Lattner71536432005-01-17 05:10:15 +00004227 return false;
4228}
4229
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004230// PHINode simplification
4231//
Chris Lattner113f4f42002-06-25 16:13:24 +00004232Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00004233 if (Value *V = hasConstantValue(&PN)) {
4234 // If V is an instruction, we have to be certain that it dominates PN.
4235 // However, because we don't have dom info, we can't do a perfect job.
4236 if (Instruction *I = dyn_cast<Instruction>(V)) {
4237 // We know that the instruction dominates the PHI if there are no undef
4238 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00004239 if (I->getParent() != &I->getParent()->getParent()->front() ||
4240 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00004241 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4242 if (isa<UndefValue>(PN.getIncomingValue(i))) {
4243 V = 0;
4244 break;
4245 }
Chris Lattnere29d6342004-10-17 21:22:38 +00004246 }
4247
4248 if (V)
4249 return ReplaceInstUsesWith(PN, V);
4250 }
Chris Lattner4db2d222004-02-16 05:07:08 +00004251
4252 // If the only user of this instruction is a cast instruction, and all of the
4253 // incoming values are constants, change this PHI to merge together the casted
4254 // constants.
4255 if (PN.hasOneUse())
4256 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4257 if (CI->getType() != PN.getType()) { // noop casts will be folded
4258 bool AllConstant = true;
4259 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4260 if (!isa<Constant>(PN.getIncomingValue(i))) {
4261 AllConstant = false;
4262 break;
4263 }
4264 if (AllConstant) {
4265 // Make a new PHI with all casted values.
4266 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4267 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4268 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4269 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4270 PN.getIncomingBlock(i));
4271 }
4272
4273 // Update the cast instruction.
4274 CI->setOperand(0, New);
4275 WorkList.push_back(CI); // revisit the cast instruction to fold.
4276 WorkList.push_back(New); // Make sure to revisit the new Phi
4277 return &PN; // PN is now dead!
4278 }
4279 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004280
4281 // If all PHI operands are the same operation, pull them through the PHI,
4282 // reducing code size.
4283 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4284 PN.getIncomingValue(0)->hasOneUse())
4285 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4286 return Result;
4287
Chris Lattner71536432005-01-17 05:10:15 +00004288 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4289 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4290 // PHI)... break the cycle.
4291 if (PN.hasOneUse())
4292 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4293 std::set<PHINode*> PotentiallyDeadPHIs;
4294 PotentiallyDeadPHIs.insert(&PN);
4295 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4296 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4297 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004298
Chris Lattner91daeb52003-12-19 05:58:40 +00004299 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004300}
4301
Chris Lattner69193f92004-04-05 01:30:19 +00004302static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4303 Instruction *InsertPoint,
4304 InstCombiner *IC) {
4305 unsigned PS = IC->getTargetData().getPointerSize();
4306 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004307 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4308 // We must insert a cast to ensure we sign-extend.
4309 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4310 V->getName()), *InsertPoint);
4311 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4312 *InsertPoint);
4313}
4314
Chris Lattner48a44f72002-05-02 17:06:02 +00004315
Chris Lattner113f4f42002-06-25 16:13:24 +00004316Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004317 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004318 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004319 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004320 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004321 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004322
Chris Lattner81a7a232004-10-16 18:11:37 +00004323 if (isa<UndefValue>(GEP.getOperand(0)))
4324 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4325
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004326 bool HasZeroPointerIndex = false;
4327 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4328 HasZeroPointerIndex = C->isNullValue();
4329
4330 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004331 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004332
Chris Lattner69193f92004-04-05 01:30:19 +00004333 // Eliminate unneeded casts for indices.
4334 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004335 gep_type_iterator GTI = gep_type_begin(GEP);
4336 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4337 if (isa<SequentialType>(*GTI)) {
4338 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4339 Value *Src = CI->getOperand(0);
4340 const Type *SrcTy = Src->getType();
4341 const Type *DestTy = CI->getType();
4342 if (Src->getType()->isInteger()) {
4343 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
4344 // We can always eliminate a cast from ulong or long to the other.
4345 // We can always eliminate a cast from uint to int or the other on
4346 // 32-bit pointer platforms.
4347 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
4348 MadeChange = true;
4349 GEP.setOperand(i, Src);
4350 }
4351 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4352 SrcTy->getPrimitiveSize() == 4) {
4353 // We can always eliminate a cast from int to [u]long. We can
4354 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4355 // pointer target.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004356 if (SrcTy->isSigned() ||
Chris Lattner2b2412d2004-04-07 18:38:20 +00004357 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
4358 MadeChange = true;
4359 GEP.setOperand(i, Src);
4360 }
Chris Lattner69193f92004-04-05 01:30:19 +00004361 }
4362 }
4363 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004364 // If we are using a wider index than needed for this platform, shrink it
4365 // to what we need. If the incoming value needs a cast instruction,
4366 // insert it. This explicit cast can make subsequent optimizations more
4367 // obvious.
4368 Value *Op = GEP.getOperand(i);
4369 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004370 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004371 GEP.setOperand(i, ConstantExpr::getCast(C,
4372 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004373 MadeChange = true;
4374 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004375 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4376 Op->getName()), GEP);
4377 GEP.setOperand(i, Op);
4378 MadeChange = true;
4379 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004380
4381 // If this is a constant idx, make sure to canonicalize it to be a signed
4382 // operand, otherwise CSE and other optimizations are pessimized.
4383 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4384 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4385 CUI->getType()->getSignedVersion()));
4386 MadeChange = true;
4387 }
Chris Lattner69193f92004-04-05 01:30:19 +00004388 }
4389 if (MadeChange) return &GEP;
4390
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004391 // Combine Indices - If the source pointer to this getelementptr instruction
4392 // is a getelementptr instruction, combine the indices of the two
4393 // getelementptr instructions into a single instruction.
4394 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004395 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004396 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004397 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004398
4399 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004400 // Note that if our source is a gep chain itself that we wait for that
4401 // chain to be resolved before we perform this transformation. This
4402 // avoids us creating a TON of code in some cases.
4403 //
4404 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4405 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4406 return 0; // Wait until our source is folded to completion.
4407
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004408 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004409
4410 // Find out whether the last index in the source GEP is a sequential idx.
4411 bool EndsWithSequential = false;
4412 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4413 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004414 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004415
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004416 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004417 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004418 // Replace: gep (gep %P, long B), long A, ...
4419 // With: T = long A+B; gep %P, T, ...
4420 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004421 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004422 if (SO1 == Constant::getNullValue(SO1->getType())) {
4423 Sum = GO1;
4424 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4425 Sum = SO1;
4426 } else {
4427 // If they aren't the same type, convert both to an integer of the
4428 // target's pointer size.
4429 if (SO1->getType() != GO1->getType()) {
4430 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4431 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4432 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4433 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4434 } else {
4435 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004436 if (SO1->getType()->getPrimitiveSize() == PS) {
4437 // Convert GO1 to SO1's type.
4438 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4439
4440 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4441 // Convert SO1 to GO1's type.
4442 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4443 } else {
4444 const Type *PT = TD->getIntPtrType();
4445 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4446 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4447 }
4448 }
4449 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004450 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4451 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4452 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004453 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4454 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004455 }
Chris Lattner69193f92004-04-05 01:30:19 +00004456 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004457
4458 // Recycle the GEP we already have if possible.
4459 if (SrcGEPOperands.size() == 2) {
4460 GEP.setOperand(0, SrcGEPOperands[0]);
4461 GEP.setOperand(1, Sum);
4462 return &GEP;
4463 } else {
4464 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4465 SrcGEPOperands.end()-1);
4466 Indices.push_back(Sum);
4467 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4468 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004469 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner69193f92004-04-05 01:30:19 +00004470 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004471 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004472 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004473 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4474 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004475 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4476 }
4477
4478 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004479 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004480
Chris Lattner5f667a62004-05-07 22:09:22 +00004481 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004482 // GEP of global variable. If all of the indices for this GEP are
4483 // constants, we can promote this to a constexpr instead of an instruction.
4484
4485 // Scan for nonconstants...
4486 std::vector<Constant*> Indices;
4487 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4488 for (; I != E && isa<Constant>(*I); ++I)
4489 Indices.push_back(cast<Constant>(*I));
4490
4491 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004492 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004493
4494 // Replace all uses of the GEP with the new constexpr...
4495 return ReplaceInstUsesWith(GEP, CE);
4496 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004497 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004498 if (CE->getOpcode() == Instruction::Cast) {
4499 if (HasZeroPointerIndex) {
4500 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4501 // into : GEP [10 x ubyte]* X, long 0, ...
4502 //
4503 // This occurs when the program declares an array extern like "int X[];"
4504 //
4505 Constant *X = CE->getOperand(0);
4506 const PointerType *CPTy = cast<PointerType>(CE->getType());
4507 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4508 if (const ArrayType *XATy =
4509 dyn_cast<ArrayType>(XTy->getElementType()))
4510 if (const ArrayType *CATy =
4511 dyn_cast<ArrayType>(CPTy->getElementType()))
4512 if (CATy->getElementType() == XATy->getElementType()) {
4513 // At this point, we know that the cast source type is a pointer
4514 // to an array of the same type as the destination pointer
4515 // array. Because the array type is never stepped over (there
4516 // is a leading zero) we can fold the cast into this GEP.
4517 GEP.setOperand(0, X);
4518 return &GEP;
4519 }
Chris Lattner0798af32005-01-13 20:14:25 +00004520 } else if (GEP.getNumOperands() == 2 &&
4521 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004522 // Transform things like:
4523 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4524 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4525 Constant *X = CE->getOperand(0);
4526 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4527 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4528 if (isa<ArrayType>(SrcElTy) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004529 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004530 TD->getTypeSize(ResElTy)) {
4531 Value *V = InsertNewInstBefore(
4532 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4533 GEP.getOperand(1), GEP.getName()), GEP);
4534 return new CastInst(V, GEP.getType());
4535 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004536 }
4537 }
Chris Lattnerca081252001-12-14 16:52:21 +00004538 }
4539
Chris Lattnerca081252001-12-14 16:52:21 +00004540 return 0;
4541}
4542
Chris Lattner1085bdf2002-11-04 16:18:53 +00004543Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4544 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4545 if (AI.isArrayAllocation()) // Check C != 1
4546 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4547 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004548 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004549
4550 // Create and insert the replacement instruction...
4551 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004552 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004553 else {
4554 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004555 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004556 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004557
4558 InsertNewInstBefore(New, AI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00004559
Chris Lattner1085bdf2002-11-04 16:18:53 +00004560 // Scan to the end of the allocation instructions, to skip over a block of
4561 // allocas if possible...
4562 //
4563 BasicBlock::iterator It = New;
4564 while (isa<AllocationInst>(*It)) ++It;
4565
4566 // Now that I is pointing to the first non-allocation-inst in the block,
4567 // insert our getelementptr instruction...
4568 //
Chris Lattner69193f92004-04-05 01:30:19 +00004569 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004570 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
4571
4572 // Now make everything use the getelementptr instead of the original
4573 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004574 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004575 } else if (isa<UndefValue>(AI.getArraySize())) {
4576 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004577 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004578
4579 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4580 // Note that we only do this for alloca's, because malloc should allocate and
4581 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanb1c93172005-04-21 23:48:37 +00004582 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattner49df6ce2004-07-02 22:55:47 +00004583 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004584 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4585
Chris Lattner1085bdf2002-11-04 16:18:53 +00004586 return 0;
4587}
4588
Chris Lattner8427bff2003-12-07 01:24:23 +00004589Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4590 Value *Op = FI.getOperand(0);
4591
4592 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4593 if (CastInst *CI = dyn_cast<CastInst>(Op))
4594 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4595 FI.setOperand(0, CI->getOperand(0));
4596 return &FI;
4597 }
4598
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004599 // free undef -> unreachable.
4600 if (isa<UndefValue>(Op)) {
4601 // Insert a new store to null because we cannot modify the CFG here.
4602 new StoreInst(ConstantBool::True,
4603 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4604 return EraseInstFromFunction(FI);
4605 }
4606
Chris Lattnerf3a36602004-02-28 04:57:37 +00004607 // If we have 'free null' delete the instruction. This can happen in stl code
4608 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004609 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004610 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004611
Chris Lattner8427bff2003-12-07 01:24:23 +00004612 return 0;
4613}
4614
4615
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004616/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4617/// constantexpr, return the constant value being addressed by the constant
4618/// expression, or null if something is funny.
4619///
4620static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004621 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004622 return 0; // Do not allow stepping over the value!
4623
4624 // Loop over all of the operands, tracking down which value we are
4625 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004626 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4627 for (++I; I != E; ++I)
4628 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4629 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4630 assert(CU->getValue() < STy->getNumElements() &&
4631 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004632 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00004633 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004634 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00004635 } else if (isa<ConstantAggregateZero>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004636 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00004637 } else if (isa<UndefValue>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004638 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004639 } else {
4640 return 0;
4641 }
4642 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4643 const ArrayType *ATy = cast<ArrayType>(*I);
4644 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4645 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004646 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004647 else if (isa<ConstantAggregateZero>(C))
4648 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004649 else if (isa<UndefValue>(C))
4650 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004651 else
4652 return 0;
4653 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004654 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004655 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004656 return C;
4657}
4658
Chris Lattner72684fe2005-01-31 05:51:45 +00004659/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattner35e24772004-07-13 01:49:43 +00004660static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4661 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004662 Value *CastOp = CI->getOperand(0);
Chris Lattner35e24772004-07-13 01:49:43 +00004663
4664 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004665 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattner35e24772004-07-13 01:49:43 +00004666 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004667
4668 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4669 // If the source is an array, the code below will not succeed. Check to
4670 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4671 // constants.
4672 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4673 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4674 if (ASrcTy->getNumElements() != 0) {
4675 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4676 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4677 SrcTy = cast<PointerType>(CastOp->getType());
4678 SrcPTy = SrcTy->getElementType();
4679 }
4680
4681 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerecfa9b52005-03-29 06:37:47 +00004682 // Do not allow turning this into a load of an integer, which is then
4683 // casted to a pointer, this pessimizes pointer analysis a lot.
4684 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004685 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004686 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanb1c93172005-04-21 23:48:37 +00004687
Chris Lattnerfe1b0b82005-01-31 04:50:46 +00004688 // Okay, we are casting from one integer or pointer type to another of
4689 // the same size. Instead of casting the pointer before the load, cast
4690 // the result of the loaded value.
4691 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
4692 CI->getName(),
4693 LI.isVolatile()),LI);
4694 // Now cast the result of the load.
4695 return new CastInst(NewLoad, LI.getType());
4696 }
Chris Lattner35e24772004-07-13 01:49:43 +00004697 }
4698 }
4699 return 0;
4700}
4701
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004702/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004703/// from this value cannot trap. If it is not obviously safe to load from the
4704/// specified pointer, we do a quick local scan of the basic block containing
4705/// ScanFrom, to determine if the address is already accessed.
4706static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4707 // If it is an alloca or global variable, it is always safe to load from.
4708 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4709
4710 // Otherwise, be a little bit agressive by scanning the local block where we
4711 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004712 // from/to. If so, the previous load or store would have already trapped,
4713 // so there is no harm doing an extra load (also, CSE will later eliminate
4714 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004715 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4716
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004717 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004718 --BBI;
4719
4720 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4721 if (LI->getOperand(0) == V) return true;
4722 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4723 if (SI->getOperand(1) == V) return true;
Misha Brukmanb1c93172005-04-21 23:48:37 +00004724
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004725 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004726 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004727}
4728
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004729Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4730 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004731
Chris Lattner81a7a232004-10-16 18:11:37 +00004732 if (Constant *C = dyn_cast<Constant>(Op)) {
4733 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004734 !LI.isVolatile()) { // load null/undef -> undef
4735 // Insert a new store to null instruction before the load to indicate that
4736 // this code is not reachable. We do this instead of inserting an
4737 // unreachable instruction directly because we cannot modify the CFG.
4738 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004739 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004740 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004741
Chris Lattner81a7a232004-10-16 18:11:37 +00004742 // Instcombine load (constant global) into the value loaded.
4743 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4744 if (GV->isConstant() && !GV->isExternal())
4745 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanb1c93172005-04-21 23:48:37 +00004746
Chris Lattner81a7a232004-10-16 18:11:37 +00004747 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4748 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4749 if (CE->getOpcode() == Instruction::GetElementPtr) {
4750 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4751 if (GV->isConstant() && !GV->isExternal())
4752 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4753 return ReplaceInstUsesWith(LI, V);
4754 } else if (CE->getOpcode() == Instruction::Cast) {
4755 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4756 return Res;
4757 }
4758 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004759
4760 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004761 if (CastInst *CI = dyn_cast<CastInst>(Op))
4762 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4763 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004764
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004765 if (!LI.isVolatile() && Op->hasOneUse()) {
4766 // Change select and PHI nodes to select values instead of addresses: this
4767 // helps alias analysis out a lot, allows many others simplifications, and
4768 // exposes redundancy in the code.
4769 //
4770 // Note that we cannot do the transformation unless we know that the
4771 // introduced loads cannot trap! Something like this is valid as long as
4772 // the condition is always false: load (select bool %C, int* null, int* %G),
4773 // but it would not be valid if we transformed it to load from null
4774 // unconditionally.
4775 //
4776 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4777 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004778 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4779 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004780 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004781 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004782 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004783 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004784 return new SelectInst(SI->getCondition(), V1, V2);
4785 }
4786
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004787 // load (select (cond, null, P)) -> load P
4788 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4789 if (C->isNullValue()) {
4790 LI.setOperand(0, SI->getOperand(2));
4791 return &LI;
4792 }
4793
4794 // load (select (cond, P, null)) -> load P
4795 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4796 if (C->isNullValue()) {
4797 LI.setOperand(0, SI->getOperand(1));
4798 return &LI;
4799 }
4800
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004801 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4802 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004803 bool Safe = PN->getParent() == LI.getParent();
4804
4805 // Scan all of the instructions between the PHI and the load to make
4806 // sure there are no instructions that might possibly alter the value
4807 // loaded from the PHI.
4808 if (Safe) {
4809 BasicBlock::iterator I = &LI;
4810 for (--I; !isa<PHINode>(I); --I)
4811 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4812 Safe = false;
4813 break;
4814 }
4815 }
4816
4817 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004818 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004819 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004820 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004821
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004822 if (Safe) {
4823 // Create the PHI.
4824 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4825 InsertNewInstBefore(NewPN, *PN);
4826 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4827
4828 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4829 BasicBlock *BB = PN->getIncomingBlock(i);
4830 Value *&TheLoad = LoadMap[BB];
4831 if (TheLoad == 0) {
4832 Value *InVal = PN->getIncomingValue(i);
4833 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4834 InVal->getName()+".val"),
4835 *BB->getTerminator());
4836 }
4837 NewPN->addIncoming(TheLoad, BB);
4838 }
4839 return ReplaceInstUsesWith(LI, NewPN);
4840 }
4841 }
4842 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004843 return 0;
4844}
4845
Chris Lattner72684fe2005-01-31 05:51:45 +00004846/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
4847/// when possible.
4848static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
4849 User *CI = cast<User>(SI.getOperand(1));
4850 Value *CastOp = CI->getOperand(0);
4851
4852 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4853 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
4854 const Type *SrcPTy = SrcTy->getElementType();
4855
4856 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
4857 // If the source is an array, the code below will not succeed. Check to
4858 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
4859 // constants.
4860 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
4861 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
4862 if (ASrcTy->getNumElements() != 0) {
4863 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
4864 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
4865 SrcTy = cast<PointerType>(CastOp->getType());
4866 SrcPTy = SrcTy->getElementType();
4867 }
4868
4869 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanb1c93172005-04-21 23:48:37 +00004870 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattner72684fe2005-01-31 05:51:45 +00004871 IC.getTargetData().getTypeSize(DestPTy)) {
4872
4873 // Okay, we are casting from one integer or pointer type to another of
4874 // the same size. Instead of casting the pointer before the store, cast
4875 // the value to be stored.
4876 Value *NewCast;
4877 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
4878 NewCast = ConstantExpr::getCast(C, SrcPTy);
4879 else
4880 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
4881 SrcPTy,
4882 SI.getOperand(0)->getName()+".c"), SI);
4883
4884 return new StoreInst(NewCast, CastOp);
4885 }
4886 }
4887 }
4888 return 0;
4889}
4890
Chris Lattner31f486c2005-01-31 05:36:43 +00004891Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
4892 Value *Val = SI.getOperand(0);
4893 Value *Ptr = SI.getOperand(1);
4894
4895 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
4896 removeFromWorkList(&SI);
4897 SI.eraseFromParent();
4898 ++NumCombined;
4899 return 0;
4900 }
4901
4902 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
4903
4904 // store X, null -> turns into 'unreachable' in SimplifyCFG
4905 if (isa<ConstantPointerNull>(Ptr)) {
4906 if (!isa<UndefValue>(Val)) {
4907 SI.setOperand(0, UndefValue::get(Val->getType()));
4908 if (Instruction *U = dyn_cast<Instruction>(Val))
4909 WorkList.push_back(U); // Dropped a use.
4910 ++NumCombined;
4911 }
4912 return 0; // Do not modify these!
4913 }
4914
4915 // store undef, Ptr -> noop
4916 if (isa<UndefValue>(Val)) {
4917 removeFromWorkList(&SI);
4918 SI.eraseFromParent();
4919 ++NumCombined;
4920 return 0;
4921 }
4922
Chris Lattner72684fe2005-01-31 05:51:45 +00004923 // If the pointer destination is a cast, see if we can fold the cast into the
4924 // source instead.
4925 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
4926 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
4927 return Res;
4928 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
4929 if (CE->getOpcode() == Instruction::Cast)
4930 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
4931 return Res;
4932
Chris Lattner31f486c2005-01-31 05:36:43 +00004933 return 0;
4934}
4935
4936
Chris Lattner9eef8a72003-06-04 04:46:00 +00004937Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4938 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004939 Value *X;
4940 BasicBlock *TrueDest;
4941 BasicBlock *FalseDest;
4942 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4943 !isa<Constant>(X)) {
4944 // Swap Destinations and condition...
4945 BI.setCondition(X);
4946 BI.setSuccessor(0, FalseDest);
4947 BI.setSuccessor(1, TrueDest);
4948 return &BI;
4949 }
4950
4951 // Cannonicalize setne -> seteq
4952 Instruction::BinaryOps Op; Value *Y;
4953 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4954 TrueDest, FalseDest)))
4955 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4956 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4957 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4958 std::string Name = I->getName(); I->setName("");
4959 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4960 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004961 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004962 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004963 BI.setSuccessor(0, FalseDest);
4964 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004965 removeFromWorkList(I);
4966 I->getParent()->getInstList().erase(I);
4967 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004968 return &BI;
4969 }
Misha Brukmanb1c93172005-04-21 23:48:37 +00004970
Chris Lattner9eef8a72003-06-04 04:46:00 +00004971 return 0;
4972}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004973
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004974Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4975 Value *Cond = SI.getCondition();
4976 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4977 if (I->getOpcode() == Instruction::Add)
4978 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4979 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4980 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004981 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004982 AddRHS));
4983 SI.setOperand(0, I->getOperand(0));
4984 WorkList.push_back(I);
4985 return &SI;
4986 }
4987 }
4988 return 0;
4989}
4990
Chris Lattnerca081252001-12-14 16:52:21 +00004991
Chris Lattner99f48c62002-09-02 04:59:56 +00004992void InstCombiner::removeFromWorkList(Instruction *I) {
4993 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4994 WorkList.end());
4995}
4996
Chris Lattner39c98bb2004-12-08 23:43:58 +00004997
4998/// TryToSinkInstruction - Try to move the specified instruction from its
4999/// current block into the beginning of DestBlock, which can only happen if it's
5000/// safe to move the instruction past all of the instructions between it and the
5001/// end of its block.
5002static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5003 assert(I->hasOneUse() && "Invariants didn't hold!");
5004
5005 // Cannot move control-flow-involving instructions.
5006 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +00005007
Chris Lattner39c98bb2004-12-08 23:43:58 +00005008 // Do not sink alloca instructions out of the entry block.
5009 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5010 return false;
5011
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005012 // We can only sink load instructions if there is nothing between the load and
5013 // the end of block that could change the value.
5014 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5015 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5016
5017 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5018 Scan != E; ++Scan)
5019 if (Scan->mayWriteToMemory())
5020 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00005021 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00005022
5023 BasicBlock::iterator InsertPos = DestBlock->begin();
5024 while (isa<PHINode>(InsertPos)) ++InsertPos;
5025
5026 BasicBlock *SrcBlock = I->getParent();
Misha Brukmanb1c93172005-04-21 23:48:37 +00005027 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
Chris Lattner39c98bb2004-12-08 23:43:58 +00005028 ++NumSunkInst;
5029 return true;
5030}
5031
Chris Lattner113f4f42002-06-25 16:13:24 +00005032bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00005033 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00005034 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00005035
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005036 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
5037 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00005038
Chris Lattnerca081252001-12-14 16:52:21 +00005039
5040 while (!WorkList.empty()) {
5041 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5042 WorkList.pop_back();
5043
Misha Brukman632df282002-10-29 23:06:16 +00005044 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00005045 // Check to see if we can DIE the instruction...
5046 if (isInstructionTriviallyDead(I)) {
5047 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005048 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00005049 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00005050 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005051
Chris Lattnercd517ff2005-01-28 19:32:01 +00005052 DEBUG(std::cerr << "IC: DCE: " << *I);
5053
5054 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005055 removeFromWorkList(I);
5056 continue;
5057 }
Chris Lattner99f48c62002-09-02 04:59:56 +00005058
Misha Brukman632df282002-10-29 23:06:16 +00005059 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00005060 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005061 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00005062 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005063 cast<Constant>(Ptr)->isNullValue() &&
5064 !isa<ConstantPointerNull>(C) &&
5065 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00005066 // If this is a constant expr gep that is effectively computing an
5067 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5068 bool isFoldableGEP = true;
5069 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5070 if (!isa<ConstantInt>(I->getOperand(i)))
5071 isFoldableGEP = false;
5072 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00005073 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00005074 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5075 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00005076 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00005077 C = ConstantExpr::getCast(C, I->getType());
5078 }
5079 }
5080
Chris Lattnercd517ff2005-01-28 19:32:01 +00005081 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5082
Chris Lattner99f48c62002-09-02 04:59:56 +00005083 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00005084 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00005085 ReplaceInstUsesWith(*I, C);
5086
Chris Lattner99f48c62002-09-02 04:59:56 +00005087 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005088 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00005089 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005090 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00005091 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005092
Chris Lattner39c98bb2004-12-08 23:43:58 +00005093 // See if we can trivially sink this instruction to a successor basic block.
5094 if (I->hasOneUse()) {
5095 BasicBlock *BB = I->getParent();
5096 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5097 if (UserParent != BB) {
5098 bool UserIsSuccessor = false;
5099 // See if the user is one of our successors.
5100 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5101 if (*SI == UserParent) {
5102 UserIsSuccessor = true;
5103 break;
5104 }
5105
5106 // If the user is one of our immediate successors, and if that successor
5107 // only has us as a predecessors (we'd have to split the critical edge
5108 // otherwise), we can keep going.
5109 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5110 next(pred_begin(UserParent)) == pred_end(UserParent))
5111 // Okay, the CFG is simple enough, try to sink this instruction.
5112 Changed |= TryToSinkInstruction(I, UserParent);
5113 }
5114 }
5115
Chris Lattnerca081252001-12-14 16:52:21 +00005116 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005117 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00005118 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00005119 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00005120 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005121 DEBUG(std::cerr << "IC: Old = " << *I
5122 << " New = " << *Result);
5123
Chris Lattner396dbfe2004-06-09 05:08:07 +00005124 // Everything uses the new instruction now.
5125 I->replaceAllUsesWith(Result);
5126
5127 // Push the new instruction and any users onto the worklist.
5128 WorkList.push_back(Result);
5129 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005130
5131 // Move the name to the new instruction first...
5132 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00005133 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005134
5135 // Insert the new instruction into the basic block...
5136 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00005137 BasicBlock::iterator InsertPos = I;
5138
5139 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5140 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5141 ++InsertPos;
5142
5143 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005144
Chris Lattner63d75af2004-05-01 23:27:23 +00005145 // Make sure that we reprocess all operands now that we reduced their
5146 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005147 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5148 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5149 WorkList.push_back(OpI);
5150
Chris Lattner396dbfe2004-06-09 05:08:07 +00005151 // Instructions can end up on the worklist more than once. Make sure
5152 // we do not process an instruction that has been deleted.
5153 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005154
5155 // Erase the old instruction.
5156 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005157 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005158 DEBUG(std::cerr << "IC: MOD = " << *I);
5159
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005160 // If the instruction was modified, it's possible that it is now dead.
5161 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005162 if (isInstructionTriviallyDead(I)) {
5163 // Make sure we process all operands now that we are reducing their
5164 // use counts.
5165 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5166 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5167 WorkList.push_back(OpI);
Misha Brukmanb1c93172005-04-21 23:48:37 +00005168
Chris Lattner63d75af2004-05-01 23:27:23 +00005169 // Instructions may end up in the worklist more than once. Erase all
5170 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005171 removeFromWorkList(I);
Chris Lattner31f486c2005-01-31 05:36:43 +00005172 I->eraseFromParent();
Chris Lattner396dbfe2004-06-09 05:08:07 +00005173 } else {
5174 WorkList.push_back(Result);
5175 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005176 }
Chris Lattner053c0932002-05-14 15:24:07 +00005177 }
Chris Lattner260ab202002-04-18 17:39:14 +00005178 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005179 }
5180 }
5181
Chris Lattner260ab202002-04-18 17:39:14 +00005182 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005183}
5184
Brian Gaeke38b79e82004-07-27 17:43:21 +00005185FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005186 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005187}
Brian Gaeke960707c2003-11-11 22:41:34 +00005188