blob: 6312f426dd3775025e1027eba3e7a3af3b7567fd [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// 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.
7//
8//===----------------------------------------------------------------------===//
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
106 //
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 Lattner9eef8a72003-06-04 04:46:00 +0000133 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000134 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000135
136 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000137 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000138
Chris Lattner970c33a2003-06-19 17:00:31 +0000139 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000140 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000141 bool transformConstExprCastCall(CallSite CS);
142
Chris Lattner69193f92004-04-05 01:30:19 +0000143 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000144 // InsertNewInstBefore - insert an instruction New before instruction Old
145 // in the program. Add the new instruction to the worklist.
146 //
Chris Lattner623826c2004-09-28 21:48:02 +0000147 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000148 assert(New && New->getParent() == 0 &&
149 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000150 BasicBlock *BB = Old.getParent();
151 BB->getInstList().insert(&Old, New); // Insert inst
152 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000153 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000154 }
155
Chris Lattner7e794272004-09-24 15:21:34 +0000156 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
157 /// This also adds the cast to the worklist. Finally, this returns the
158 /// cast.
159 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
160 if (V->getType() == Ty) return V;
161
162 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
163 WorkList.push_back(C);
164 return C;
165 }
166
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000167 // ReplaceInstUsesWith - This method is to be used when an instruction is
168 // found to be dead, replacable with another preexisting expression. Here
169 // we add all uses of I to the worklist, replace all uses of I with the new
170 // value, then return I, so that the inst combiner will know that I was
171 // modified.
172 //
173 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000174 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000175 if (&I != V) {
176 I.replaceAllUsesWith(V);
177 return &I;
178 } else {
179 // If we are replacing the instruction with itself, this must be in a
180 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000181 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000182 return &I;
183 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000184 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000185
186 // EraseInstFromFunction - When dealing with an instruction that has side
187 // effects or produces a void value, we can't rely on DCE to delete the
188 // instruction. Instead, visit methods should return the value returned by
189 // this function.
190 Instruction *EraseInstFromFunction(Instruction &I) {
191 assert(I.use_empty() && "Cannot erase instruction that is used!");
192 AddUsesToWorkList(I);
193 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000194 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000195 return 0; // Don't do anything with FI
196 }
197
198
Chris Lattner3ac7c262003-08-13 20:16:26 +0000199 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000200 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
201 /// InsertBefore instruction. This is specialized a bit to avoid inserting
202 /// casts that are known to not do anything...
203 ///
204 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
205 Instruction *InsertBefore);
206
Chris Lattner7fb29e12003-03-11 00:12:48 +0000207 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000208 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000209 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000210
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000211
212 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
213 // PHI node as operand #0, see if we can fold the instruction into the PHI
214 // (which is only possible if all operands to the PHI are constants).
215 Instruction *FoldOpIntoPhi(Instruction &I);
216
Chris Lattner7515cab2004-11-14 19:13:23 +0000217 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
218 // operator and they all are only used by the PHI, PHI together their
219 // inputs, and do the operation once, to the result of the PHI.
220 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
221
Chris Lattnerba1cb382003-09-19 17:17:26 +0000222 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
223 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000224
225 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
226 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000227 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000228
Chris Lattnerc8b70922002-07-26 21:12:46 +0000229 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000230}
231
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000232// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000233// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000234static unsigned getComplexity(Value *V) {
235 if (isa<Instruction>(V)) {
236 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000237 return 3;
238 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000239 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000240 if (isa<Argument>(V)) return 3;
241 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000242}
Chris Lattner260ab202002-04-18 17:39:14 +0000243
Chris Lattner7fb29e12003-03-11 00:12:48 +0000244// isOnlyUse - Return true if this instruction will be deleted if we stop using
245// it.
246static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000247 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000248}
249
Chris Lattnere79e8542004-02-23 06:38:22 +0000250// getPromotedType - Return the specified type promoted as it would be to pass
251// though a va_arg area...
252static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000253 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000254 case Type::SByteTyID:
255 case Type::ShortTyID: return Type::IntTy;
256 case Type::UByteTyID:
257 case Type::UShortTyID: return Type::UIntTy;
258 case Type::FloatTyID: return Type::DoubleTy;
259 default: return Ty;
260 }
261}
262
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000263// SimplifyCommutative - This performs a few simplifications for commutative
264// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000265//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000266// 1. Order operands such that they are listed from right (least complex) to
267// left (most complex). This puts constants before unary operators before
268// binary operators.
269//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000270// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
271// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000273bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000274 bool Changed = false;
275 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
276 Changed = !I.swapOperands();
277
278 if (!I.isAssociative()) return Changed;
279 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000280 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
281 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
282 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000283 Constant *Folded = ConstantExpr::get(I.getOpcode(),
284 cast<Constant>(I.getOperand(1)),
285 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000286 I.setOperand(0, Op->getOperand(0));
287 I.setOperand(1, Folded);
288 return true;
289 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
290 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
291 isOnlyUse(Op) && isOnlyUse(Op1)) {
292 Constant *C1 = cast<Constant>(Op->getOperand(1));
293 Constant *C2 = cast<Constant>(Op1->getOperand(1));
294
295 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000296 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000297 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
298 Op1->getOperand(0),
299 Op1->getName(), &I);
300 WorkList.push_back(New);
301 I.setOperand(0, New);
302 I.setOperand(1, Folded);
303 return true;
304 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000305 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000306 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000307}
Chris Lattnerca081252001-12-14 16:52:21 +0000308
Chris Lattnerbb74e222003-03-10 23:06:50 +0000309// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
310// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000311//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000312static inline Value *dyn_castNegVal(Value *V) {
313 if (BinaryOperator::isNeg(V))
314 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
315
Chris Lattner9ad0d552004-12-14 20:08:06 +0000316 // Constants can be considered to be negated values if they can be folded.
317 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
318 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000319 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000320}
321
Chris Lattnerbb74e222003-03-10 23:06:50 +0000322static inline Value *dyn_castNotVal(Value *V) {
323 if (BinaryOperator::isNot(V))
324 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
325
326 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000327 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000328 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000329 return 0;
330}
331
Chris Lattner7fb29e12003-03-11 00:12:48 +0000332// dyn_castFoldableMul - If this value is a multiply that can be folded into
333// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000334// non-constant operand of the multiply, and set CST to point to the multiplier.
335// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000336//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000337static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000338 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000339 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000340 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000341 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000342 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000343 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000344 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000345 // The multiplier is really 1 << CST.
346 Constant *One = ConstantInt::get(V->getType(), 1);
347 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
348 return I->getOperand(0);
349 }
350 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000351 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000352}
Chris Lattner31ae8632002-08-14 17:51:49 +0000353
Chris Lattner0798af32005-01-13 20:14:25 +0000354/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
355/// expression, return it.
356static User *dyn_castGetElementPtr(Value *V) {
357 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
358 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
359 if (CE->getOpcode() == Instruction::GetElementPtr)
360 return cast<User>(V);
361 return false;
362}
363
Chris Lattner3082c5a2003-02-18 19:28:33 +0000364// Log2 - Calculate the log base 2 for the specified value if it is exactly a
365// power of 2.
366static unsigned Log2(uint64_t Val) {
367 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
368 unsigned Count = 0;
369 while (Val != 1) {
370 if (Val & 1) return 0; // Multiple bits set?
371 Val >>= 1;
372 ++Count;
373 }
374 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000375}
376
Chris Lattner623826c2004-09-28 21:48:02 +0000377// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000378static ConstantInt *AddOne(ConstantInt *C) {
379 return cast<ConstantInt>(ConstantExpr::getAdd(C,
380 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000381}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000382static ConstantInt *SubOne(ConstantInt *C) {
383 return cast<ConstantInt>(ConstantExpr::getSub(C,
384 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000385}
386
387// isTrueWhenEqual - Return true if the specified setcondinst instruction is
388// true when both operands are equal...
389//
390static bool isTrueWhenEqual(Instruction &I) {
391 return I.getOpcode() == Instruction::SetEQ ||
392 I.getOpcode() == Instruction::SetGE ||
393 I.getOpcode() == Instruction::SetLE;
394}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000395
396/// AssociativeOpt - Perform an optimization on an associative operator. This
397/// function is designed to check a chain of associative operators for a
398/// potential to apply a certain optimization. Since the optimization may be
399/// applicable if the expression was reassociated, this checks the chain, then
400/// reassociates the expression as necessary to expose the optimization
401/// opportunity. This makes use of a special Functor, which must define
402/// 'shouldApply' and 'apply' methods.
403///
404template<typename Functor>
405Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
406 unsigned Opcode = Root.getOpcode();
407 Value *LHS = Root.getOperand(0);
408
409 // Quick check, see if the immediate LHS matches...
410 if (F.shouldApply(LHS))
411 return F.apply(Root);
412
413 // Otherwise, if the LHS is not of the same opcode as the root, return.
414 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000415 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000416 // Should we apply this transform to the RHS?
417 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
418
419 // If not to the RHS, check to see if we should apply to the LHS...
420 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
421 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
422 ShouldApply = true;
423 }
424
425 // If the functor wants to apply the optimization to the RHS of LHSI,
426 // reassociate the expression from ((? op A) op B) to (? op (A op B))
427 if (ShouldApply) {
428 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000429
430 // Now all of the instructions are in the current basic block, go ahead
431 // and perform the reassociation.
432 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
433
434 // First move the selected RHS to the LHS of the root...
435 Root.setOperand(0, LHSI->getOperand(1));
436
437 // Make what used to be the LHS of the root be the user of the root...
438 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000439 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000440 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
441 return 0;
442 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000443 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000444 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000445 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
446 BasicBlock::iterator ARI = &Root; ++ARI;
447 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
448 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000449
450 // Now propagate the ExtraOperand down the chain of instructions until we
451 // get to LHSI.
452 while (TmpLHSI != LHSI) {
453 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000454 // Move the instruction to immediately before the chain we are
455 // constructing to avoid breaking dominance properties.
456 NextLHSI->getParent()->getInstList().remove(NextLHSI);
457 BB->getInstList().insert(ARI, NextLHSI);
458 ARI = NextLHSI;
459
Chris Lattnerb8b97502003-08-13 19:01:45 +0000460 Value *NextOp = NextLHSI->getOperand(1);
461 NextLHSI->setOperand(1, ExtraOperand);
462 TmpLHSI = NextLHSI;
463 ExtraOperand = NextOp;
464 }
465
466 // Now that the instructions are reassociated, have the functor perform
467 // the transformation...
468 return F.apply(Root);
469 }
470
471 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
472 }
473 return 0;
474}
475
476
477// AddRHS - Implements: X + X --> X << 1
478struct AddRHS {
479 Value *RHS;
480 AddRHS(Value *rhs) : RHS(rhs) {}
481 bool shouldApply(Value *LHS) const { return LHS == RHS; }
482 Instruction *apply(BinaryOperator &Add) const {
483 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
484 ConstantInt::get(Type::UByteTy, 1));
485 }
486};
487
488// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
489// iff C1&C2 == 0
490struct AddMaskingAnd {
491 Constant *C2;
492 AddMaskingAnd(Constant *c) : C2(c) {}
493 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000494 ConstantInt *C1;
495 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
496 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000497 }
498 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000499 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000500 }
501};
502
Chris Lattner86102b82005-01-01 16:22:27 +0000503static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000504 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000505 if (isa<CastInst>(I)) {
506 if (Constant *SOC = dyn_cast<Constant>(SO))
507 return ConstantExpr::getCast(SOC, I.getType());
508
509 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
510 SO->getName() + ".cast"), I);
511 }
512
Chris Lattner183b3362004-04-09 19:05:30 +0000513 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000514 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
515 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000516
Chris Lattner183b3362004-04-09 19:05:30 +0000517 if (Constant *SOC = dyn_cast<Constant>(SO)) {
518 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000519 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
520 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000521 }
522
523 Value *Op0 = SO, *Op1 = ConstOperand;
524 if (!ConstIsRHS)
525 std::swap(Op0, Op1);
526 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
528 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
529 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
530 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000531 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000532 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000533 abort();
534 }
Chris Lattner86102b82005-01-01 16:22:27 +0000535 return IC->InsertNewInstBefore(New, I);
536}
537
538// FoldOpIntoSelect - Given an instruction with a select as one operand and a
539// constant as the other operand, try to fold the binary operator into the
540// select arguments. This also works for Cast instructions, which obviously do
541// not have a second operand.
542static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
543 InstCombiner *IC) {
544 // Don't modify shared select instructions
545 if (!SI->hasOneUse()) return 0;
546 Value *TV = SI->getOperand(1);
547 Value *FV = SI->getOperand(2);
548
549 if (isa<Constant>(TV) || isa<Constant>(FV)) {
550 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
551 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
552
553 return new SelectInst(SI->getCondition(), SelectTrueVal,
554 SelectFalseVal);
555 }
556 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000557}
558
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000559
560/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
561/// node as operand #0, see if we can fold the instruction into the PHI (which
562/// is only possible if all operands to the PHI are constants).
563Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
564 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000565 unsigned NumPHIValues = PN->getNumIncomingValues();
566 if (!PN->hasOneUse() || NumPHIValues == 0 ||
567 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000568
569 // Check to see if all of the operands of the PHI are constants. If not, we
570 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000571 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000572 if (!isa<Constant>(PN->getIncomingValue(i)))
573 return 0;
574
575 // Okay, we can do the transformation: create the new PHI node.
576 PHINode *NewPN = new PHINode(I.getType(), I.getName());
577 I.setName("");
578 NewPN->op_reserve(PN->getNumOperands());
579 InsertNewInstBefore(NewPN, *PN);
580
581 // Next, add all of the operands to the PHI.
582 if (I.getNumOperands() == 2) {
583 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000584 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000585 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
586 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
587 PN->getIncomingBlock(i));
588 }
589 } else {
590 assert(isa<CastInst>(I) && "Unary op should be a cast!");
591 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000592 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000593 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
594 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
595 PN->getIncomingBlock(i));
596 }
597 }
598 return ReplaceInstUsesWith(I, NewPN);
599}
600
Chris Lattner113f4f42002-06-25 16:13:24 +0000601Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000602 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000603 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000604
Chris Lattnercf4a9962004-04-10 22:01:55 +0000605 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000606 // X + undef -> undef
607 if (isa<UndefValue>(RHS))
608 return ReplaceInstUsesWith(I, RHS);
609
Chris Lattnercf4a9962004-04-10 22:01:55 +0000610 // X + 0 --> X
611 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
612 RHSC->isNullValue())
613 return ReplaceInstUsesWith(I, LHS);
614
615 // X + (signbit) --> X ^ signbit
616 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
617 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
618 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000619 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000620 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000621 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000622
623 if (isa<PHINode>(LHS))
624 if (Instruction *NV = FoldOpIntoPhi(I))
625 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000626 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000627
Chris Lattnerb8b97502003-08-13 19:01:45 +0000628 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000629 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000630 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000631 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000632
Chris Lattner147e9752002-05-08 22:46:53 +0000633 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000634 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000635 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000636
637 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000638 if (!isa<Constant>(RHS))
639 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000640 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000641
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000642 ConstantInt *C2;
643 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
644 if (X == RHS) // X*C + X --> X * (C+1)
645 return BinaryOperator::createMul(RHS, AddOne(C2));
646
647 // X*C1 + X*C2 --> X * (C1+C2)
648 ConstantInt *C1;
649 if (X == dyn_castFoldableMul(RHS, C1))
650 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000651 }
652
653 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000654 if (dyn_castFoldableMul(RHS, C2) == LHS)
655 return BinaryOperator::createMul(LHS, AddOne(C2));
656
Chris Lattner57c8d992003-02-18 19:57:07 +0000657
Chris Lattnerb8b97502003-08-13 19:01:45 +0000658 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000659 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000660 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000661
Chris Lattnerb9cde762003-10-02 15:11:26 +0000662 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000663 Value *X;
664 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
665 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
666 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000667 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000668
Chris Lattnerbff91d92004-10-08 05:07:56 +0000669 // (X & FF00) + xx00 -> (X+xx00) & FF00
670 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
671 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
672 if (Anded == CRHS) {
673 // See if all bits from the first bit set in the Add RHS up are included
674 // in the mask. First, get the rightmost bit.
675 uint64_t AddRHSV = CRHS->getRawValue();
676
677 // Form a mask of all bits from the lowest bit added through the top.
678 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
679 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
680
681 // See if the and mask includes all of these bits.
682 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
683
684 if (AddRHSHighBits == AddRHSHighBitsAnd) {
685 // Okay, the xform is safe. Insert the new add pronto.
686 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
687 LHS->getName()), I);
688 return BinaryOperator::createAnd(NewAdd, C2);
689 }
690 }
691 }
692
Chris Lattnerd4252a72004-07-30 07:50:03 +0000693 // Try to fold constant add into select arguments.
694 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000695 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000696 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000697 }
698
Chris Lattner113f4f42002-06-25 16:13:24 +0000699 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000700}
701
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000702// isSignBit - Return true if the value represented by the constant only has the
703// highest order bit set.
704static bool isSignBit(ConstantInt *CI) {
705 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
706 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
707}
708
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000709static unsigned getTypeSizeInBits(const Type *Ty) {
710 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
711}
712
Chris Lattner022167f2004-03-13 00:11:49 +0000713/// RemoveNoopCast - Strip off nonconverting casts from the value.
714///
715static Value *RemoveNoopCast(Value *V) {
716 if (CastInst *CI = dyn_cast<CastInst>(V)) {
717 const Type *CTy = CI->getType();
718 const Type *OpTy = CI->getOperand(0)->getType();
719 if (CTy->isInteger() && OpTy->isInteger()) {
720 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
721 return RemoveNoopCast(CI->getOperand(0));
722 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
723 return RemoveNoopCast(CI->getOperand(0));
724 }
725 return V;
726}
727
Chris Lattner113f4f42002-06-25 16:13:24 +0000728Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000729 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000730
Chris Lattnere6794492002-08-12 21:17:25 +0000731 if (Op0 == Op1) // sub X, X -> 0
732 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000733
Chris Lattnere6794492002-08-12 21:17:25 +0000734 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000735 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000736 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000737
Chris Lattner81a7a232004-10-16 18:11:37 +0000738 if (isa<UndefValue>(Op0))
739 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
740 if (isa<UndefValue>(Op1))
741 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
742
Chris Lattner8f2f5982003-11-05 01:06:05 +0000743 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
744 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000745 if (C->isAllOnesValue())
746 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000747
Chris Lattner8f2f5982003-11-05 01:06:05 +0000748 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000749 Value *X;
750 if (match(Op1, m_Not(m_Value(X))))
751 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000752 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000753 // -((uint)X >> 31) -> ((int)X >> 31)
754 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000755 if (C->isNullValue()) {
756 Value *NoopCastedRHS = RemoveNoopCast(Op1);
757 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000758 if (SI->getOpcode() == Instruction::Shr)
759 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
760 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000761 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000762 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000763 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000764 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000765 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000766 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000767 // Ok, the transformation is safe. Insert a cast of the incoming
768 // value, then the new shift, then the new cast.
769 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
770 SI->getOperand(0)->getName());
771 Value *InV = InsertNewInstBefore(FirstCast, I);
772 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
773 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000774 if (NewShift->getType() == I.getType())
775 return NewShift;
776 else {
777 InV = InsertNewInstBefore(NewShift, I);
778 return new CastInst(NewShift, I.getType());
779 }
Chris Lattner92295c52004-03-12 23:53:13 +0000780 }
781 }
Chris Lattner022167f2004-03-13 00:11:49 +0000782 }
Chris Lattner183b3362004-04-09 19:05:30 +0000783
784 // Try to fold constant sub into select arguments.
785 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000786 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000787 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000788
789 if (isa<PHINode>(Op0))
790 if (Instruction *NV = FoldOpIntoPhi(I))
791 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000792 }
793
Chris Lattner3082c5a2003-02-18 19:28:33 +0000794 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000795 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000796 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
797 // is not used by anyone else...
798 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000799 if (Op1I->getOpcode() == Instruction::Sub &&
800 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000801 // Swap the two operands of the subexpr...
802 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
803 Op1I->setOperand(0, IIOp1);
804 Op1I->setOperand(1, IIOp0);
805
806 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000807 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000808 }
809
810 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
811 //
812 if (Op1I->getOpcode() == Instruction::And &&
813 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
814 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
815
Chris Lattner396dbfe2004-06-09 05:08:07 +0000816 Value *NewNot =
817 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000818 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000819 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000820
Chris Lattner0aee4b72004-10-06 15:08:25 +0000821 // -(X sdiv C) -> (X sdiv -C)
822 if (Op1I->getOpcode() == Instruction::Div)
823 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
824 if (CSI->getValue() == 0)
825 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
826 return BinaryOperator::createDiv(Op1I->getOperand(0),
827 ConstantExpr::getNeg(DivRHS));
828
Chris Lattner57c8d992003-02-18 19:57:07 +0000829 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000830 ConstantInt *C2;
831 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
832 Constant *CP1 =
833 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000834 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000835 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000836 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000837
Chris Lattner411336f2005-01-19 21:50:18 +0000838 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
839 if (Op0I->getOpcode() == Instruction::Add)
840 if (!Op0->getType()->isFloatingPoint()) {
841 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
842 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
843 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
844 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
845 }
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000846
847 ConstantInt *C1;
848 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
849 if (X == Op1) { // X*C - X --> X * (C-1)
850 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
851 return BinaryOperator::createMul(Op1, CP1);
852 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000853
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000854 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
855 if (X == dyn_castFoldableMul(Op1, C2))
856 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
857 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000858 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000859}
860
Chris Lattnere79e8542004-02-23 06:38:22 +0000861/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
862/// really just returns true if the most significant (sign) bit is set.
863static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
864 if (RHS->getType()->isSigned()) {
865 // True if source is LHS < 0 or LHS <= -1
866 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
867 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
868 } else {
869 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
870 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
871 // the size of the integer type.
872 if (Opcode == Instruction::SetGE)
873 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
874 if (Opcode == Instruction::SetGT)
875 return RHSC->getValue() ==
876 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
877 }
878 return false;
879}
880
Chris Lattner113f4f42002-06-25 16:13:24 +0000881Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000882 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000883 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000884
Chris Lattner81a7a232004-10-16 18:11:37 +0000885 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
886 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
887
Chris Lattnere6794492002-08-12 21:17:25 +0000888 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000889 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
890 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000891
892 // ((X << C1)*C2) == (X * (C2 << C1))
893 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
894 if (SI->getOpcode() == Instruction::Shl)
895 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000896 return BinaryOperator::createMul(SI->getOperand(0),
897 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000898
Chris Lattnercce81be2003-09-11 22:24:54 +0000899 if (CI->isNullValue())
900 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
901 if (CI->equalsInt(1)) // X * 1 == X
902 return ReplaceInstUsesWith(I, Op0);
903 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000904 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000905
Chris Lattnercce81be2003-09-11 22:24:54 +0000906 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000907 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
908 return new ShiftInst(Instruction::Shl, Op0,
909 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000910 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000911 if (Op1F->isNullValue())
912 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000913
Chris Lattner3082c5a2003-02-18 19:28:33 +0000914 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
915 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
916 if (Op1F->getValue() == 1.0)
917 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
918 }
Chris Lattner183b3362004-04-09 19:05:30 +0000919
920 // Try to fold constant mul into select arguments.
921 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000922 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000923 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000924
925 if (isa<PHINode>(Op0))
926 if (Instruction *NV = FoldOpIntoPhi(I))
927 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000928 }
929
Chris Lattner934a64cf2003-03-10 23:23:04 +0000930 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
931 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000932 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000933
Chris Lattner2635b522004-02-23 05:39:21 +0000934 // If one of the operands of the multiply is a cast from a boolean value, then
935 // we know the bool is either zero or one, so this is a 'masking' multiply.
936 // See if we can simplify things based on how the boolean was originally
937 // formed.
938 CastInst *BoolCast = 0;
939 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
940 if (CI->getOperand(0)->getType() == Type::BoolTy)
941 BoolCast = CI;
942 if (!BoolCast)
943 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
944 if (CI->getOperand(0)->getType() == Type::BoolTy)
945 BoolCast = CI;
946 if (BoolCast) {
947 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
948 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
949 const Type *SCOpTy = SCIOp0->getType();
950
Chris Lattnere79e8542004-02-23 06:38:22 +0000951 // If the setcc is true iff the sign bit of X is set, then convert this
952 // multiply into a shift/and combination.
953 if (isa<ConstantInt>(SCIOp1) &&
954 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000955 // Shift the X value right to turn it into "all signbits".
956 Constant *Amt = ConstantUInt::get(Type::UByteTy,
957 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000958 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000959 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000960 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
961 SCIOp0->getName()), I);
962 }
963
964 Value *V =
965 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
966 BoolCast->getOperand(0)->getName()+
967 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000968
969 // If the multiply type is not the same as the source type, sign extend
970 // or truncate to the multiply type.
971 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000972 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000973
974 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000975 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000976 }
977 }
978 }
979
Chris Lattner113f4f42002-06-25 16:13:24 +0000980 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000981}
982
Chris Lattner113f4f42002-06-25 16:13:24 +0000983Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +0000985
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000986 if (isa<UndefValue>(Op0)) // undef / X -> 0
987 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
988 if (isa<UndefValue>(Op1))
989 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
990
991 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000992 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000993 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000994 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000995
Chris Lattnere20c3342004-04-26 14:01:59 +0000996 // div X, -1 == -X
997 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000998 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +0000999
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001000 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001001 if (LHS->getOpcode() == Instruction::Div)
1002 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001003 // (X / C1) / C2 -> X / (C1*C2)
1004 return BinaryOperator::createDiv(LHS->getOperand(0),
1005 ConstantExpr::getMul(RHS, LHSRHS));
1006 }
1007
Chris Lattner3082c5a2003-02-18 19:28:33 +00001008 // Check to see if this is an unsigned division with an exact power of 2,
1009 // if so, convert to a right shift.
1010 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1011 if (uint64_t Val = C->getValue()) // Don't break X / 0
1012 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001013 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001014 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001015
Chris Lattner4ad08352004-10-09 02:50:40 +00001016 // -X/C -> X/-C
1017 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001018 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001019 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1020
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001021 if (!RHS->isNullValue()) {
1022 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001023 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001024 return R;
1025 if (isa<PHINode>(Op0))
1026 if (Instruction *NV = FoldOpIntoPhi(I))
1027 return NV;
1028 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001029 }
1030
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001031 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1032 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1033 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1034 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1035 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1036 if (STO->getValue() == 0) { // Couldn't be this argument.
1037 I.setOperand(1, SFO);
1038 return &I;
1039 } else if (SFO->getValue() == 0) {
1040 I.setOperand(1, STO);
1041 return &I;
1042 }
1043
1044 if (uint64_t TSA = Log2(STO->getValue()))
1045 if (uint64_t FSA = Log2(SFO->getValue())) {
1046 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1047 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1048 TC, SI->getName()+".t");
1049 TSI = InsertNewInstBefore(TSI, I);
1050
1051 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1052 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1053 FC, SI->getName()+".f");
1054 FSI = InsertNewInstBefore(FSI, I);
1055 return new SelectInst(SI->getOperand(0), TSI, FSI);
1056 }
1057 }
1058
Chris Lattner3082c5a2003-02-18 19:28:33 +00001059 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001060 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001061 if (LHS->equalsInt(0))
1062 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1063
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001064 return 0;
1065}
1066
1067
Chris Lattner113f4f42002-06-25 16:13:24 +00001068Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001069 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001070 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001071 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001072 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001073 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001074 // X % -Y -> X % Y
1075 AddUsesToWorkList(I);
1076 I.setOperand(1, RHSNeg);
1077 return &I;
1078 }
1079
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001080 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001081 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001082 if (isa<UndefValue>(Op1))
1083 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001084
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001085 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001086 if (RHS->equalsInt(1)) // X % 1 == 0
1087 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1088
1089 // Check to see if this is an unsigned remainder with an exact power of 2,
1090 // if so, convert to a bitwise and.
1091 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1092 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001093 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001094 return BinaryOperator::createAnd(Op0,
1095 ConstantUInt::get(I.getType(), Val-1));
1096
1097 if (!RHS->isNullValue()) {
1098 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001099 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001100 return R;
1101 if (isa<PHINode>(Op0))
1102 if (Instruction *NV = FoldOpIntoPhi(I))
1103 return NV;
1104 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001105 }
1106
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001107 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1108 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1109 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1110 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1111 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1112 if (STO->getValue() == 0) { // Couldn't be this argument.
1113 I.setOperand(1, SFO);
1114 return &I;
1115 } else if (SFO->getValue() == 0) {
1116 I.setOperand(1, STO);
1117 return &I;
1118 }
1119
1120 if (!(STO->getValue() & (STO->getValue()-1)) &&
1121 !(SFO->getValue() & (SFO->getValue()-1))) {
1122 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1123 SubOne(STO), SI->getName()+".t"), I);
1124 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1125 SubOne(SFO), SI->getName()+".f"), I);
1126 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1127 }
1128 }
1129
Chris Lattner3082c5a2003-02-18 19:28:33 +00001130 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001131 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001132 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001133 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1134
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001135 return 0;
1136}
1137
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001138// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001139static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001140 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1141 // Calculate -1 casted to the right type...
1142 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1143 uint64_t Val = ~0ULL; // All ones
1144 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1145 return CU->getValue() == Val-1;
1146 }
1147
1148 const ConstantSInt *CS = cast<ConstantSInt>(C);
1149
1150 // Calculate 0111111111..11111
1151 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1152 int64_t Val = INT64_MAX; // All ones
1153 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1154 return CS->getValue() == Val-1;
1155}
1156
1157// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001158static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001159 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1160 return CU->getValue() == 1;
1161
1162 const ConstantSInt *CS = cast<ConstantSInt>(C);
1163
1164 // Calculate 1111111111000000000000
1165 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1166 int64_t Val = -1; // All ones
1167 Val <<= TypeBits-1; // Shift over to the right spot
1168 return CS->getValue() == Val+1;
1169}
1170
Chris Lattner35167c32004-06-09 07:59:58 +00001171// isOneBitSet - Return true if there is exactly one bit set in the specified
1172// constant.
1173static bool isOneBitSet(const ConstantInt *CI) {
1174 uint64_t V = CI->getRawValue();
1175 return V && (V & (V-1)) == 0;
1176}
1177
Chris Lattner8fc5af42004-09-23 21:46:38 +00001178#if 0 // Currently unused
1179// isLowOnes - Return true if the constant is of the form 0+1+.
1180static bool isLowOnes(const ConstantInt *CI) {
1181 uint64_t V = CI->getRawValue();
1182
1183 // There won't be bits set in parts that the type doesn't contain.
1184 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1185
1186 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1187 return U && V && (U & V) == 0;
1188}
1189#endif
1190
1191// isHighOnes - Return true if the constant is of the form 1+0+.
1192// This is the same as lowones(~X).
1193static bool isHighOnes(const ConstantInt *CI) {
1194 uint64_t V = ~CI->getRawValue();
1195
1196 // There won't be bits set in parts that the type doesn't contain.
1197 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1198
1199 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1200 return U && V && (U & V) == 0;
1201}
1202
1203
Chris Lattner3ac7c262003-08-13 20:16:26 +00001204/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1205/// are carefully arranged to allow folding of expressions such as:
1206///
1207/// (A < B) | (A > B) --> (A != B)
1208///
1209/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1210/// represents that the comparison is true if A == B, and bit value '1' is true
1211/// if A < B.
1212///
1213static unsigned getSetCondCode(const SetCondInst *SCI) {
1214 switch (SCI->getOpcode()) {
1215 // False -> 0
1216 case Instruction::SetGT: return 1;
1217 case Instruction::SetEQ: return 2;
1218 case Instruction::SetGE: return 3;
1219 case Instruction::SetLT: return 4;
1220 case Instruction::SetNE: return 5;
1221 case Instruction::SetLE: return 6;
1222 // True -> 7
1223 default:
1224 assert(0 && "Invalid SetCC opcode!");
1225 return 0;
1226 }
1227}
1228
1229/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1230/// opcode and two operands into either a constant true or false, or a brand new
1231/// SetCC instruction.
1232static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1233 switch (Opcode) {
1234 case 0: return ConstantBool::False;
1235 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1236 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1237 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1238 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1239 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1240 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1241 case 7: return ConstantBool::True;
1242 default: assert(0 && "Illegal SetCCCode!"); return 0;
1243 }
1244}
1245
1246// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1247struct FoldSetCCLogical {
1248 InstCombiner &IC;
1249 Value *LHS, *RHS;
1250 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1251 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1252 bool shouldApply(Value *V) const {
1253 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1254 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1255 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1256 return false;
1257 }
1258 Instruction *apply(BinaryOperator &Log) const {
1259 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1260 if (SCI->getOperand(0) != LHS) {
1261 assert(SCI->getOperand(1) == LHS);
1262 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1263 }
1264
1265 unsigned LHSCode = getSetCondCode(SCI);
1266 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1267 unsigned Code;
1268 switch (Log.getOpcode()) {
1269 case Instruction::And: Code = LHSCode & RHSCode; break;
1270 case Instruction::Or: Code = LHSCode | RHSCode; break;
1271 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001272 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001273 }
1274
1275 Value *RV = getSetCCValue(Code, LHS, RHS);
1276 if (Instruction *I = dyn_cast<Instruction>(RV))
1277 return I;
1278 // Otherwise, it's a constant boolean value...
1279 return IC.ReplaceInstUsesWith(Log, RV);
1280 }
1281};
1282
1283
Chris Lattner86102b82005-01-01 16:22:27 +00001284/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1285/// this predicate to simplify operations downstream. V and Mask are known to
1286/// be the same type.
1287static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1288 if (isa<UndefValue>(V) || Mask->isNullValue())
1289 return true;
1290 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1291 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
1292
1293 if (Instruction *I = dyn_cast<Instruction>(V)) {
1294 switch (I->getOpcode()) {
1295 case Instruction::And:
1296 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1297 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1298 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1299 return true;
1300 break;
1301 case Instruction::Cast: {
1302 const Type *SrcTy = I->getOperand(0)->getType();
1303 if (SrcTy->isIntegral()) {
1304 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1305 if (SrcTy->isUnsigned() && // Only handle zero ext.
1306 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1307 return true;
1308
1309 // If this is a noop cast, recurse.
1310 if (SrcTy != Type::BoolTy)
1311 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() ==I->getType()) ||
1312 SrcTy->getSignedVersion() == I->getType()) {
1313 Constant *NewMask =
1314 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1315 return MaskedValueIsZero(I->getOperand(0),
1316 cast<ConstantIntegral>(NewMask));
1317 }
1318 }
1319 break;
1320 }
1321 case Instruction::Shl:
1322 // (shl X, C1) & C2 == 0 iff (-1 << C1) & C2 == 0
1323 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1324 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1325 C1 = ConstantExpr::getShl(C1, SA);
1326 C1 = ConstantExpr::getAnd(C1, Mask);
1327 if (C1->isNullValue())
1328 return true;
1329 }
1330 break;
1331 case Instruction::Shr:
1332 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1333 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1334 if (I->getType()->isUnsigned()) {
1335 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1336 C1 = ConstantExpr::getShr(C1, SA);
1337 C1 = ConstantExpr::getAnd(C1, Mask);
1338 if (C1->isNullValue())
1339 return true;
1340 }
1341 break;
1342 }
1343 }
1344
1345 return false;
1346}
1347
Chris Lattnerba1cb382003-09-19 17:17:26 +00001348// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1349// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1350// guaranteed to be either a shift instruction or a binary operator.
1351Instruction *InstCombiner::OptAndOp(Instruction *Op,
1352 ConstantIntegral *OpRHS,
1353 ConstantIntegral *AndRHS,
1354 BinaryOperator &TheAnd) {
1355 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001356 Constant *Together = 0;
1357 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001358 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001359
Chris Lattnerba1cb382003-09-19 17:17:26 +00001360 switch (Op->getOpcode()) {
1361 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001362 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001363 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1364 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001365 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001366 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001367 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001368 }
1369 break;
1370 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001371 if (Together == AndRHS) // (X | C) & C --> C
1372 return ReplaceInstUsesWith(TheAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001373
Chris Lattner86102b82005-01-01 16:22:27 +00001374 if (Op->hasOneUse() && Together != OpRHS) {
1375 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1376 std::string Op0Name = Op->getName(); Op->setName("");
1377 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1378 InsertNewInstBefore(Or, TheAnd);
1379 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001380 }
1381 break;
1382 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001383 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001384 // Adding a one to a single bit bit-field should be turned into an XOR
1385 // of the bit. First thing to check is to see if this AND is with a
1386 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001387 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001388
1389 // Clear bits that are not part of the constant.
1390 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1391
1392 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001393 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001394 // Ok, at this point, we know that we are masking the result of the
1395 // ADD down to exactly one bit. If the constant we are adding has
1396 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001397 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001398
1399 // Check to see if any bits below the one bit set in AndRHSV are set.
1400 if ((AddRHS & (AndRHSV-1)) == 0) {
1401 // If not, the only thing that can effect the output of the AND is
1402 // the bit specified by AndRHSV. If that bit is set, the effect of
1403 // the XOR is to toggle the bit. If it is clear, then the ADD has
1404 // no effect.
1405 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1406 TheAnd.setOperand(0, X);
1407 return &TheAnd;
1408 } else {
1409 std::string Name = Op->getName(); Op->setName("");
1410 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001411 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001412 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001413 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001414 }
1415 }
1416 }
1417 }
1418 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001419
1420 case Instruction::Shl: {
1421 // We know that the AND will not produce any of the bits shifted in, so if
1422 // the anded constant includes them, clear them now!
1423 //
1424 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001425 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1426 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1427
1428 if (CI == ShlMask) { // Masking out bits that the shift already masks
1429 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1430 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001431 TheAnd.setOperand(1, CI);
1432 return &TheAnd;
1433 }
1434 break;
1435 }
1436 case Instruction::Shr:
1437 // We know that the AND will not produce any of the bits shifted in, so if
1438 // the anded constant includes them, clear them now! This only applies to
1439 // unsigned shifts, because a signed shr may bring in set bits!
1440 //
1441 if (AndRHS->getType()->isUnsigned()) {
1442 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001443 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1444 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1445
1446 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1447 return ReplaceInstUsesWith(TheAnd, Op);
1448 } else if (CI != AndRHS) {
1449 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001450 return &TheAnd;
1451 }
Chris Lattner7e794272004-09-24 15:21:34 +00001452 } else { // Signed shr.
1453 // See if this is shifting in some sign extension, then masking it out
1454 // with an and.
1455 if (Op->hasOneUse()) {
1456 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1457 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1458 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001459 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001460 // Make the argument unsigned.
1461 Value *ShVal = Op->getOperand(0);
1462 ShVal = InsertCastBefore(ShVal,
1463 ShVal->getType()->getUnsignedVersion(),
1464 TheAnd);
1465 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1466 OpRHS, Op->getName()),
1467 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001468 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1469 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1470 TheAnd.getName()),
1471 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001472 return new CastInst(ShVal, Op->getType());
1473 }
1474 }
Chris Lattner2da29172003-09-19 19:05:02 +00001475 }
1476 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001477 }
1478 return 0;
1479}
1480
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001481
Chris Lattner6862fbd2004-09-29 17:40:11 +00001482/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1483/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1484/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1485/// insert new instructions.
1486Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1487 bool Inside, Instruction &IB) {
1488 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1489 "Lo is not <= Hi in range emission code!");
1490 if (Inside) {
1491 if (Lo == Hi) // Trivially false.
1492 return new SetCondInst(Instruction::SetNE, V, V);
1493 if (cast<ConstantIntegral>(Lo)->isMinValue())
1494 return new SetCondInst(Instruction::SetLT, V, Hi);
1495
1496 Constant *AddCST = ConstantExpr::getNeg(Lo);
1497 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1498 InsertNewInstBefore(Add, IB);
1499 // Convert to unsigned for the comparison.
1500 const Type *UnsType = Add->getType()->getUnsignedVersion();
1501 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1502 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1503 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1504 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1505 }
1506
1507 if (Lo == Hi) // Trivially true.
1508 return new SetCondInst(Instruction::SetEQ, V, V);
1509
1510 Hi = SubOne(cast<ConstantInt>(Hi));
1511 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1512 return new SetCondInst(Instruction::SetGT, V, Hi);
1513
1514 // Emit X-Lo > Hi-Lo-1
1515 Constant *AddCST = ConstantExpr::getNeg(Lo);
1516 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1517 InsertNewInstBefore(Add, IB);
1518 // Convert to unsigned for the comparison.
1519 const Type *UnsType = Add->getType()->getUnsignedVersion();
1520 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1521 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1522 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1523 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1524}
1525
1526
Chris Lattner113f4f42002-06-25 16:13:24 +00001527Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001528 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001529 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001530
Chris Lattner81a7a232004-10-16 18:11:37 +00001531 if (isa<UndefValue>(Op1)) // X & undef -> 0
1532 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1533
Chris Lattner86102b82005-01-01 16:22:27 +00001534 // and X, X = X
1535 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001536 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001537
1538 // and X, -1 == X
Chris Lattner86102b82005-01-01 16:22:27 +00001539 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
1540 if (AndRHS->isAllOnesValue()) // and X, -1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001541 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001542
Chris Lattner86102b82005-01-01 16:22:27 +00001543 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1544 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1545
1546 // If the mask is not masking out any bits, there is no reason to do the
1547 // and in the first place.
1548 if (MaskedValueIsZero(Op0,
1549 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS))))
1550 return ReplaceInstUsesWith(I, Op0);
1551
Chris Lattnerba1cb382003-09-19 17:17:26 +00001552 // Optimize a variety of ((val OP C1) & C2) combinations...
1553 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1554 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001555 Value *Op0LHS = Op0I->getOperand(0);
1556 Value *Op0RHS = Op0I->getOperand(1);
1557 switch (Op0I->getOpcode()) {
1558 case Instruction::Xor:
1559 case Instruction::Or:
1560 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1561 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1562 if (MaskedValueIsZero(Op0LHS, AndRHS))
1563 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1564 if (MaskedValueIsZero(Op0RHS, AndRHS))
1565 return BinaryOperator::createAnd(Op0LHS, AndRHS);
1566 break;
1567 case Instruction::And:
1568 // (X & V) & C2 --> 0 iff (V & C2) == 0
1569 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1570 MaskedValueIsZero(Op0RHS, AndRHS))
1571 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1572 break;
1573 }
1574
Chris Lattner16464b32003-07-23 19:25:52 +00001575 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001576 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001577 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001578 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1579 const Type *SrcTy = CI->getOperand(0)->getType();
1580
1581 // If this is an integer sign or zero extension instruction.
1582 if (SrcTy->isIntegral() &&
1583 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
1584
1585 if (SrcTy->isUnsigned()) {
1586 // See if this and is clearing out bits that are known to be zero
1587 // anyway (due to the zero extension).
1588 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1589 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1590 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1591 if (Result == Mask) // The "and" isn't doing anything, remove it.
1592 return ReplaceInstUsesWith(I, CI);
1593 if (Result != AndRHS) { // Reduce the and RHS constant.
1594 I.setOperand(1, Result);
1595 return &I;
1596 }
1597
1598 } else {
1599 if (CI->hasOneUse() && SrcTy->isInteger()) {
1600 // We can only do this if all of the sign bits brought in are masked
1601 // out. Compute this by first getting 0000011111, then inverting
1602 // it.
1603 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1604 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1605 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1606 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1607 // If the and is clearing all of the sign bits, change this to a
1608 // zero extension cast. To do this, cast the cast input to
1609 // unsigned, then to the requested size.
1610 Value *CastOp = CI->getOperand(0);
1611 Instruction *NC =
1612 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1613 CI->getName()+".uns");
1614 NC = InsertNewInstBefore(NC, I);
1615 // Finally, insert a replacement for CI.
1616 NC = new CastInst(NC, CI->getType(), CI->getName());
1617 CI->setName("");
1618 NC = InsertNewInstBefore(NC, I);
1619 WorkList.push_back(CI); // Delete CI later.
1620 I.setOperand(0, NC);
1621 return &I; // The AND operand was modified.
1622 }
1623 }
1624 }
1625 }
Chris Lattner33217db2003-07-23 19:36:21 +00001626 }
Chris Lattner183b3362004-04-09 19:05:30 +00001627
1628 // Try to fold constant and into select arguments.
1629 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001630 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001631 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001632 if (isa<PHINode>(Op0))
1633 if (Instruction *NV = FoldOpIntoPhi(I))
1634 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001635 }
1636
Chris Lattnerbb74e222003-03-10 23:06:50 +00001637 Value *Op0NotVal = dyn_castNotVal(Op0);
1638 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001639
Chris Lattner023a4832004-06-18 06:07:51 +00001640 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1641 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1642
Misha Brukman9c003d82004-07-30 12:50:08 +00001643 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001644 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001645 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1646 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001647 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001648 return BinaryOperator::createNot(Or);
1649 }
1650
Chris Lattner623826c2004-09-28 21:48:02 +00001651 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1652 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001653 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1654 return R;
1655
Chris Lattner623826c2004-09-28 21:48:02 +00001656 Value *LHSVal, *RHSVal;
1657 ConstantInt *LHSCst, *RHSCst;
1658 Instruction::BinaryOps LHSCC, RHSCC;
1659 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1660 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1661 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1662 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1663 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1664 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1665 // Ensure that the larger constant is on the RHS.
1666 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1667 SetCondInst *LHS = cast<SetCondInst>(Op0);
1668 if (cast<ConstantBool>(Cmp)->getValue()) {
1669 std::swap(LHS, RHS);
1670 std::swap(LHSCst, RHSCst);
1671 std::swap(LHSCC, RHSCC);
1672 }
1673
1674 // At this point, we know we have have two setcc instructions
1675 // comparing a value against two constants and and'ing the result
1676 // together. Because of the above check, we know that we only have
1677 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1678 // FoldSetCCLogical check above), that the two constants are not
1679 // equal.
1680 assert(LHSCst != RHSCst && "Compares not folded above?");
1681
1682 switch (LHSCC) {
1683 default: assert(0 && "Unknown integer condition code!");
1684 case Instruction::SetEQ:
1685 switch (RHSCC) {
1686 default: assert(0 && "Unknown integer condition code!");
1687 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1688 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1689 return ReplaceInstUsesWith(I, ConstantBool::False);
1690 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1691 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1692 return ReplaceInstUsesWith(I, LHS);
1693 }
1694 case Instruction::SetNE:
1695 switch (RHSCC) {
1696 default: assert(0 && "Unknown integer condition code!");
1697 case Instruction::SetLT:
1698 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1699 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1700 break; // (X != 13 & X < 15) -> no change
1701 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1702 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1703 return ReplaceInstUsesWith(I, RHS);
1704 case Instruction::SetNE:
1705 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1706 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1707 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1708 LHSVal->getName()+".off");
1709 InsertNewInstBefore(Add, I);
1710 const Type *UnsType = Add->getType()->getUnsignedVersion();
1711 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1712 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1713 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1714 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1715 }
1716 break; // (X != 13 & X != 15) -> no change
1717 }
1718 break;
1719 case Instruction::SetLT:
1720 switch (RHSCC) {
1721 default: assert(0 && "Unknown integer condition code!");
1722 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1723 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1724 return ReplaceInstUsesWith(I, ConstantBool::False);
1725 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1726 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1727 return ReplaceInstUsesWith(I, LHS);
1728 }
1729 case Instruction::SetGT:
1730 switch (RHSCC) {
1731 default: assert(0 && "Unknown integer condition code!");
1732 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1733 return ReplaceInstUsesWith(I, LHS);
1734 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1735 return ReplaceInstUsesWith(I, RHS);
1736 case Instruction::SetNE:
1737 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1738 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1739 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001740 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1741 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001742 }
1743 }
1744 }
1745 }
1746
Chris Lattner113f4f42002-06-25 16:13:24 +00001747 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001748}
1749
Chris Lattner113f4f42002-06-25 16:13:24 +00001750Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001751 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001752 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001753
Chris Lattner81a7a232004-10-16 18:11:37 +00001754 if (isa<UndefValue>(Op1))
1755 return ReplaceInstUsesWith(I, // X | undef -> -1
1756 ConstantIntegral::getAllOnesValue(I.getType()));
1757
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001758 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001759 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1760 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001761
1762 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001763 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001764 // If X is known to only contain bits that already exist in RHS, just
1765 // replace this instruction with RHS directly.
1766 if (MaskedValueIsZero(Op0,
1767 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1768 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001769
Chris Lattnerd4252a72004-07-30 07:50:03 +00001770 ConstantInt *C1; Value *X;
1771 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1772 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1773 std::string Op0Name = Op0->getName(); Op0->setName("");
1774 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1775 InsertNewInstBefore(Or, I);
1776 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1777 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001778
Chris Lattnerd4252a72004-07-30 07:50:03 +00001779 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1780 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1781 std::string Op0Name = Op0->getName(); Op0->setName("");
1782 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1783 InsertNewInstBefore(Or, I);
1784 return BinaryOperator::createXor(Or,
1785 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001786 }
Chris Lattner183b3362004-04-09 19:05:30 +00001787
1788 // Try to fold constant and into select arguments.
1789 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001790 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001791 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001792 if (isa<PHINode>(Op0))
1793 if (Instruction *NV = FoldOpIntoPhi(I))
1794 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001795 }
1796
Chris Lattner812aab72003-08-12 19:11:07 +00001797 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001798 Value *A, *B; ConstantInt *C1, *C2;
1799 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1800 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1801 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001802
Chris Lattnerd4252a72004-07-30 07:50:03 +00001803 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1804 if (A == Op1) // ~A | A == -1
1805 return ReplaceInstUsesWith(I,
1806 ConstantIntegral::getAllOnesValue(I.getType()));
1807 } else {
1808 A = 0;
1809 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001810
Chris Lattnerd4252a72004-07-30 07:50:03 +00001811 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1812 if (Op0 == B)
1813 return ReplaceInstUsesWith(I,
1814 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001815
Misha Brukman9c003d82004-07-30 12:50:08 +00001816 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001817 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1818 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1819 I.getName()+".demorgan"), I);
1820 return BinaryOperator::createNot(And);
1821 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001822 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001823
Chris Lattner3ac7c262003-08-13 20:16:26 +00001824 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001825 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001826 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1827 return R;
1828
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001829 Value *LHSVal, *RHSVal;
1830 ConstantInt *LHSCst, *RHSCst;
1831 Instruction::BinaryOps LHSCC, RHSCC;
1832 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1833 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1834 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1835 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1836 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1837 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1838 // Ensure that the larger constant is on the RHS.
1839 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1840 SetCondInst *LHS = cast<SetCondInst>(Op0);
1841 if (cast<ConstantBool>(Cmp)->getValue()) {
1842 std::swap(LHS, RHS);
1843 std::swap(LHSCst, RHSCst);
1844 std::swap(LHSCC, RHSCC);
1845 }
1846
1847 // At this point, we know we have have two setcc instructions
1848 // comparing a value against two constants and or'ing the result
1849 // together. Because of the above check, we know that we only have
1850 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1851 // FoldSetCCLogical check above), that the two constants are not
1852 // equal.
1853 assert(LHSCst != RHSCst && "Compares not folded above?");
1854
1855 switch (LHSCC) {
1856 default: assert(0 && "Unknown integer condition code!");
1857 case Instruction::SetEQ:
1858 switch (RHSCC) {
1859 default: assert(0 && "Unknown integer condition code!");
1860 case Instruction::SetEQ:
1861 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1862 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1863 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1864 LHSVal->getName()+".off");
1865 InsertNewInstBefore(Add, I);
1866 const Type *UnsType = Add->getType()->getUnsignedVersion();
1867 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1868 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1869 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1870 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1871 }
1872 break; // (X == 13 | X == 15) -> no change
1873
1874 case Instruction::SetGT:
1875 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1876 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1877 break; // (X == 13 | X > 15) -> no change
1878 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1879 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1880 return ReplaceInstUsesWith(I, RHS);
1881 }
1882 break;
1883 case Instruction::SetNE:
1884 switch (RHSCC) {
1885 default: assert(0 && "Unknown integer condition code!");
1886 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1887 return ReplaceInstUsesWith(I, RHS);
1888 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1889 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1890 return ReplaceInstUsesWith(I, LHS);
1891 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1892 return ReplaceInstUsesWith(I, ConstantBool::True);
1893 }
1894 break;
1895 case Instruction::SetLT:
1896 switch (RHSCC) {
1897 default: assert(0 && "Unknown integer condition code!");
1898 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1899 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001900 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1901 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001902 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1903 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1904 return ReplaceInstUsesWith(I, RHS);
1905 }
1906 break;
1907 case Instruction::SetGT:
1908 switch (RHSCC) {
1909 default: assert(0 && "Unknown integer condition code!");
1910 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1911 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1912 return ReplaceInstUsesWith(I, LHS);
1913 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1914 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1915 return ReplaceInstUsesWith(I, ConstantBool::True);
1916 }
1917 }
1918 }
1919 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001920 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001921}
1922
Chris Lattnerc2076352004-02-16 01:20:27 +00001923// XorSelf - Implements: X ^ X --> 0
1924struct XorSelf {
1925 Value *RHS;
1926 XorSelf(Value *rhs) : RHS(rhs) {}
1927 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1928 Instruction *apply(BinaryOperator &Xor) const {
1929 return &Xor;
1930 }
1931};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001932
1933
Chris Lattner113f4f42002-06-25 16:13:24 +00001934Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001935 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001936 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001937
Chris Lattner81a7a232004-10-16 18:11:37 +00001938 if (isa<UndefValue>(Op1))
1939 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1940
Chris Lattnerc2076352004-02-16 01:20:27 +00001941 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1942 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1943 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001944 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001945 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001946
Chris Lattner97638592003-07-23 21:37:07 +00001947 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001948 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001949 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001950 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001951
Chris Lattner97638592003-07-23 21:37:07 +00001952 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001953 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001954 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001955 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001956 return new SetCondInst(SCI->getInverseCondition(),
1957 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001958
Chris Lattner8f2f5982003-11-05 01:06:05 +00001959 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001960 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1961 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001962 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1963 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001964 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001965 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001966 }
Chris Lattner023a4832004-06-18 06:07:51 +00001967
1968 // ~(~X & Y) --> (X | ~Y)
1969 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1970 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1971 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1972 Instruction *NotY =
1973 BinaryOperator::createNot(Op0I->getOperand(1),
1974 Op0I->getOperand(1)->getName()+".not");
1975 InsertNewInstBefore(NotY, I);
1976 return BinaryOperator::createOr(Op0NotVal, NotY);
1977 }
1978 }
Chris Lattner97638592003-07-23 21:37:07 +00001979
1980 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001981 switch (Op0I->getOpcode()) {
1982 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001983 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001984 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001985 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1986 return BinaryOperator::createSub(
1987 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001988 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001989 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001990 }
Chris Lattnere5806662003-11-04 23:50:51 +00001991 break;
1992 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001993 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001994 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1995 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001996 break;
1997 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001998 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001999 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002000 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002001 break;
2002 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002003 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002004 }
Chris Lattner183b3362004-04-09 19:05:30 +00002005
2006 // Try to fold constant and into select arguments.
2007 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002008 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002009 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002010 if (isa<PHINode>(Op0))
2011 if (Instruction *NV = FoldOpIntoPhi(I))
2012 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002013 }
2014
Chris Lattnerbb74e222003-03-10 23:06:50 +00002015 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002016 if (X == Op1)
2017 return ReplaceInstUsesWith(I,
2018 ConstantIntegral::getAllOnesValue(I.getType()));
2019
Chris Lattnerbb74e222003-03-10 23:06:50 +00002020 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002021 if (X == Op0)
2022 return ReplaceInstUsesWith(I,
2023 ConstantIntegral::getAllOnesValue(I.getType()));
2024
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002025 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002026 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002027 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2028 cast<BinaryOperator>(Op1I)->swapOperands();
2029 I.swapOperands();
2030 std::swap(Op0, Op1);
2031 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2032 I.swapOperands();
2033 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00002034 }
2035 } else if (Op1I->getOpcode() == Instruction::Xor) {
2036 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2037 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2038 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2039 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2040 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002041
2042 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002043 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002044 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2045 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002046 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002047 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2048 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002049 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002050 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002051 } else if (Op0I->getOpcode() == Instruction::Xor) {
2052 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2053 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2054 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2055 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002056 }
2057
Chris Lattner7aa2d472004-08-01 19:42:59 +00002058 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002059 Value *A, *B; ConstantInt *C1, *C2;
2060 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2061 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002062 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002063 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002064
Chris Lattner3ac7c262003-08-13 20:16:26 +00002065 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2066 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2067 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2068 return R;
2069
Chris Lattner113f4f42002-06-25 16:13:24 +00002070 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002071}
2072
Chris Lattner6862fbd2004-09-29 17:40:11 +00002073/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2074/// overflowed for this type.
2075static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2076 ConstantInt *In2) {
2077 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2078 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2079}
2080
2081static bool isPositive(ConstantInt *C) {
2082 return cast<ConstantSInt>(C)->getValue() >= 0;
2083}
2084
2085/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2086/// overflowed for this type.
2087static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2088 ConstantInt *In2) {
2089 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2090
2091 if (In1->getType()->isUnsigned())
2092 return cast<ConstantUInt>(Result)->getValue() <
2093 cast<ConstantUInt>(In1)->getValue();
2094 if (isPositive(In1) != isPositive(In2))
2095 return false;
2096 if (isPositive(In1))
2097 return cast<ConstantSInt>(Result)->getValue() <
2098 cast<ConstantSInt>(In1)->getValue();
2099 return cast<ConstantSInt>(Result)->getValue() >
2100 cast<ConstantSInt>(In1)->getValue();
2101}
2102
Chris Lattner0798af32005-01-13 20:14:25 +00002103/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2104/// code necessary to compute the offset from the base pointer (without adding
2105/// in the base pointer). Return the result as a signed integer of intptr size.
2106static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2107 TargetData &TD = IC.getTargetData();
2108 gep_type_iterator GTI = gep_type_begin(GEP);
2109 const Type *UIntPtrTy = TD.getIntPtrType();
2110 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2111 Value *Result = Constant::getNullValue(SIntPtrTy);
2112
2113 // Build a mask for high order bits.
2114 uint64_t PtrSizeMask = ~0ULL;
2115 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2116
Chris Lattner0798af32005-01-13 20:14:25 +00002117 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2118 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002119 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002120 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2121 SIntPtrTy);
2122 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2123 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002124 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002125 Scale = ConstantExpr::getMul(OpC, Scale);
2126 if (Constant *RC = dyn_cast<Constant>(Result))
2127 Result = ConstantExpr::getAdd(RC, Scale);
2128 else {
2129 // Emit an add instruction.
2130 Result = IC.InsertNewInstBefore(
2131 BinaryOperator::createAdd(Result, Scale,
2132 GEP->getName()+".offs"), I);
2133 }
2134 }
2135 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002136 // Convert to correct type.
2137 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2138 Op->getName()+".c"), I);
2139 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002140 // We'll let instcombine(mul) convert this to a shl if possible.
2141 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2142 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002143
2144 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002145 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002146 GEP->getName()+".offs"), I);
2147 }
2148 }
2149 return Result;
2150}
2151
2152/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2153/// else. At this point we know that the GEP is on the LHS of the comparison.
2154Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2155 Instruction::BinaryOps Cond,
2156 Instruction &I) {
2157 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002158
2159 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2160 if (isa<PointerType>(CI->getOperand(0)->getType()))
2161 RHS = CI->getOperand(0);
2162
Chris Lattner0798af32005-01-13 20:14:25 +00002163 Value *PtrBase = GEPLHS->getOperand(0);
2164 if (PtrBase == RHS) {
2165 // As an optimization, we don't actually have to compute the actual value of
2166 // OFFSET if this is a seteq or setne comparison, just return whether each
2167 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002168 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2169 Instruction *InVal = 0;
2170 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) {
2171 bool EmitIt = true;
2172 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2173 if (isa<UndefValue>(C)) // undef index -> undef.
2174 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2175 if (C->isNullValue())
2176 EmitIt = false;
2177 else if (isa<ConstantInt>(C))
2178 return ReplaceInstUsesWith(I, // No comparison is needed here.
2179 ConstantBool::get(Cond == Instruction::SetNE));
2180 }
2181
2182 if (EmitIt) {
2183 Instruction *Comp =
2184 new SetCondInst(Cond, GEPLHS->getOperand(i),
2185 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2186 if (InVal == 0)
2187 InVal = Comp;
2188 else {
2189 InVal = InsertNewInstBefore(InVal, I);
2190 InsertNewInstBefore(Comp, I);
2191 if (Cond == Instruction::SetNE) // True if any are unequal
2192 InVal = BinaryOperator::createOr(InVal, Comp);
2193 else // True if all are equal
2194 InVal = BinaryOperator::createAnd(InVal, Comp);
2195 }
2196 }
2197 }
2198
2199 if (InVal)
2200 return InVal;
2201 else
2202 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2203 ConstantBool::get(Cond == Instruction::SetEQ));
2204 }
Chris Lattner0798af32005-01-13 20:14:25 +00002205
2206 // Only lower this if the setcc is the only user of the GEP or if we expect
2207 // the result to fold to a constant!
2208 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2209 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2210 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2211 return new SetCondInst(Cond, Offset,
2212 Constant::getNullValue(Offset->getType()));
2213 }
2214 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2215 if (PtrBase != GEPRHS->getOperand(0))
2216 return 0;
2217
Chris Lattner81e84172005-01-13 22:25:21 +00002218 // If one of the GEPs has all zero indices, recurse.
2219 bool AllZeros = true;
2220 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2221 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2222 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2223 AllZeros = false;
2224 break;
2225 }
2226 if (AllZeros)
2227 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2228 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002229
2230 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002231 AllZeros = true;
2232 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2233 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2234 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2235 AllZeros = false;
2236 break;
2237 }
2238 if (AllZeros)
2239 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2240
Chris Lattner4fa89822005-01-14 00:20:05 +00002241 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2242 // If the GEPs only differ by one index, compare it.
2243 unsigned NumDifferences = 0; // Keep track of # differences.
2244 unsigned DiffOperand = 0; // The operand that differs.
2245 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2246 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2247 if (GEPLHS->getOperand(i)->getType() !=
2248 GEPRHS->getOperand(i)->getType()) {
2249 // Irreconsilable differences.
2250 NumDifferences = 2;
2251 break;
2252 } else {
2253 if (NumDifferences++) break;
2254 DiffOperand = i;
2255 }
2256 }
2257
2258 if (NumDifferences == 0) // SAME GEP?
2259 return ReplaceInstUsesWith(I, // No comparison is needed here.
2260 ConstantBool::get(Cond == Instruction::SetEQ));
2261 else if (NumDifferences == 1) {
2262 return new SetCondInst(Cond, GEPLHS->getOperand(DiffOperand),
2263 GEPRHS->getOperand(DiffOperand));
2264 }
2265 }
2266
Chris Lattner0798af32005-01-13 20:14:25 +00002267 // Only lower this if the setcc is the only user of the GEP or if we expect
2268 // the result to fold to a constant!
2269 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2270 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2271 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2272 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2273 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2274 return new SetCondInst(Cond, L, R);
2275 }
2276 }
2277 return 0;
2278}
2279
2280
Chris Lattner113f4f42002-06-25 16:13:24 +00002281Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002282 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2284 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002285
2286 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002287 if (Op0 == Op1)
2288 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002289
Chris Lattner81a7a232004-10-16 18:11:37 +00002290 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2291 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2292
Chris Lattner15ff1e12004-11-14 07:33:16 +00002293 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2294 // addresses never equal each other! We already know that Op0 != Op1.
2295 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2296 isa<ConstantPointerNull>(Op0)) &&
2297 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2298 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002299 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2300
2301 // setcc's with boolean values can always be turned into bitwise operations
2302 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002303 switch (I.getOpcode()) {
2304 default: assert(0 && "Invalid setcc instruction!");
2305 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002306 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002307 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002308 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002309 }
Chris Lattner4456da62004-08-11 00:50:51 +00002310 case Instruction::SetNE:
2311 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002312
Chris Lattner4456da62004-08-11 00:50:51 +00002313 case Instruction::SetGT:
2314 std::swap(Op0, Op1); // Change setgt -> setlt
2315 // FALL THROUGH
2316 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2317 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2318 InsertNewInstBefore(Not, I);
2319 return BinaryOperator::createAnd(Not, Op1);
2320 }
2321 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002322 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002323 // FALL THROUGH
2324 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2325 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2326 InsertNewInstBefore(Not, I);
2327 return BinaryOperator::createOr(Not, Op1);
2328 }
2329 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002330 }
2331
Chris Lattner2dd01742004-06-09 04:24:29 +00002332 // See if we are doing a comparison between a constant and an instruction that
2333 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002334 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002335 // Check to see if we are comparing against the minimum or maximum value...
2336 if (CI->isMinValue()) {
2337 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2338 return ReplaceInstUsesWith(I, ConstantBool::False);
2339 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2340 return ReplaceInstUsesWith(I, ConstantBool::True);
2341 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2342 return BinaryOperator::createSetEQ(Op0, Op1);
2343 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2344 return BinaryOperator::createSetNE(Op0, Op1);
2345
2346 } else if (CI->isMaxValue()) {
2347 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2348 return ReplaceInstUsesWith(I, ConstantBool::False);
2349 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2350 return ReplaceInstUsesWith(I, ConstantBool::True);
2351 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2352 return BinaryOperator::createSetEQ(Op0, Op1);
2353 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2354 return BinaryOperator::createSetNE(Op0, Op1);
2355
2356 // Comparing against a value really close to min or max?
2357 } else if (isMinValuePlusOne(CI)) {
2358 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2359 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2360 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2361 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2362
2363 } else if (isMaxValueMinusOne(CI)) {
2364 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2365 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2366 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2367 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2368 }
2369
2370 // If we still have a setle or setge instruction, turn it into the
2371 // appropriate setlt or setgt instruction. Since the border cases have
2372 // already been handled above, this requires little checking.
2373 //
2374 if (I.getOpcode() == Instruction::SetLE)
2375 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2376 if (I.getOpcode() == Instruction::SetGE)
2377 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2378
Chris Lattnere1e10e12004-05-25 06:32:08 +00002379 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002380 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002381 case Instruction::PHI:
2382 if (Instruction *NV = FoldOpIntoPhi(I))
2383 return NV;
2384 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002385 case Instruction::And:
2386 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2387 LHSI->getOperand(0)->hasOneUse()) {
2388 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2389 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2390 // happens a LOT in code produced by the C front-end, for bitfield
2391 // access.
2392 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2393 ConstantUInt *ShAmt;
2394 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2395 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2396 const Type *Ty = LHSI->getType();
2397
2398 // We can fold this as long as we can't shift unknown bits
2399 // into the mask. This can only happen with signed shift
2400 // rights, as they sign-extend.
2401 if (ShAmt) {
2402 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002403 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002404 if (!CanFold) {
2405 // To test for the bad case of the signed shr, see if any
2406 // of the bits shifted in could be tested after the mask.
2407 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00002408 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002409 Constant *ShVal =
2410 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2411 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2412 CanFold = true;
2413 }
2414
2415 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002416 Constant *NewCst;
2417 if (Shift->getOpcode() == Instruction::Shl)
2418 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2419 else
2420 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002421
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002422 // Check to see if we are shifting out any of the bits being
2423 // compared.
2424 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2425 // If we shifted bits out, the fold is not going to work out.
2426 // As a special case, check to see if this means that the
2427 // result is always true or false now.
2428 if (I.getOpcode() == Instruction::SetEQ)
2429 return ReplaceInstUsesWith(I, ConstantBool::False);
2430 if (I.getOpcode() == Instruction::SetNE)
2431 return ReplaceInstUsesWith(I, ConstantBool::True);
2432 } else {
2433 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002434 Constant *NewAndCST;
2435 if (Shift->getOpcode() == Instruction::Shl)
2436 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2437 else
2438 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2439 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002440 LHSI->setOperand(0, Shift->getOperand(0));
2441 WorkList.push_back(Shift); // Shift is dead.
2442 AddUsesToWorkList(I);
2443 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002444 }
2445 }
Chris Lattner35167c32004-06-09 07:59:58 +00002446 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002447 }
2448 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002449
Reid Spencer279fa252004-11-28 21:31:15 +00002450 // (setcc (cast X to larger), CI)
Chris Lattner03f06f12005-01-17 03:20:02 +00002451 case Instruction::Cast:
2452 if (Instruction *R =
2453 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI))
2454 return R;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002455 break;
Reid Spencer279fa252004-11-28 21:31:15 +00002456
Chris Lattner272d5ca2004-09-28 18:22:15 +00002457 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2458 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2459 switch (I.getOpcode()) {
2460 default: break;
2461 case Instruction::SetEQ:
2462 case Instruction::SetNE: {
2463 // If we are comparing against bits always shifted out, the
2464 // comparison cannot succeed.
2465 Constant *Comp =
2466 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2467 if (Comp != CI) {// Comparing against a bit that we know is zero.
2468 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2469 Constant *Cst = ConstantBool::get(IsSetNE);
2470 return ReplaceInstUsesWith(I, Cst);
2471 }
2472
2473 if (LHSI->hasOneUse()) {
2474 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002475 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002476 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2477 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2478
2479 Constant *Mask;
2480 if (CI->getType()->isUnsigned()) {
2481 Mask = ConstantUInt::get(CI->getType(), Val);
2482 } else if (ShAmtVal != 0) {
2483 Mask = ConstantSInt::get(CI->getType(), Val);
2484 } else {
2485 Mask = ConstantInt::getAllOnesValue(CI->getType());
2486 }
2487
2488 Instruction *AndI =
2489 BinaryOperator::createAnd(LHSI->getOperand(0),
2490 Mask, LHSI->getName()+".mask");
2491 Value *And = InsertNewInstBefore(AndI, I);
2492 return new SetCondInst(I.getOpcode(), And,
2493 ConstantExpr::getUShr(CI, ShAmt));
2494 }
2495 }
2496 }
2497 }
2498 break;
2499
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002500 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002501 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002502 switch (I.getOpcode()) {
2503 default: break;
2504 case Instruction::SetEQ:
2505 case Instruction::SetNE: {
2506 // If we are comparing against bits always shifted out, the
2507 // comparison cannot succeed.
2508 Constant *Comp =
2509 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2510
2511 if (Comp != CI) {// Comparing against a bit that we know is zero.
2512 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2513 Constant *Cst = ConstantBool::get(IsSetNE);
2514 return ReplaceInstUsesWith(I, Cst);
2515 }
2516
2517 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002518 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002519
Chris Lattner1023b872004-09-27 16:18:50 +00002520 // Otherwise strength reduce the shift into an and.
2521 uint64_t Val = ~0ULL; // All ones.
2522 Val <<= ShAmtVal; // Shift over to the right spot.
2523
2524 Constant *Mask;
2525 if (CI->getType()->isUnsigned()) {
2526 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2527 Val &= (1ULL << TypeBits)-1;
2528 Mask = ConstantUInt::get(CI->getType(), Val);
2529 } else {
2530 Mask = ConstantSInt::get(CI->getType(), Val);
2531 }
2532
2533 Instruction *AndI =
2534 BinaryOperator::createAnd(LHSI->getOperand(0),
2535 Mask, LHSI->getName()+".mask");
2536 Value *And = InsertNewInstBefore(AndI, I);
2537 return new SetCondInst(I.getOpcode(), And,
2538 ConstantExpr::getShl(CI, ShAmt));
2539 }
2540 break;
2541 }
2542 }
2543 }
2544 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002545
Chris Lattner6862fbd2004-09-29 17:40:11 +00002546 case Instruction::Div:
2547 // Fold: (div X, C1) op C2 -> range check
2548 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2549 // Fold this div into the comparison, producing a range check.
2550 // Determine, based on the divide type, what the range is being
2551 // checked. If there is an overflow on the low or high side, remember
2552 // it, otherwise compute the range [low, hi) bounding the new value.
2553 bool LoOverflow = false, HiOverflow = 0;
2554 ConstantInt *LoBound = 0, *HiBound = 0;
2555
2556 ConstantInt *Prod;
2557 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2558
Chris Lattnera92af962004-10-11 19:40:04 +00002559 Instruction::BinaryOps Opcode = I.getOpcode();
2560
Chris Lattner6862fbd2004-09-29 17:40:11 +00002561 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2562 } else if (LHSI->getType()->isUnsigned()) { // udiv
2563 LoBound = Prod;
2564 LoOverflow = ProdOV;
2565 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2566 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2567 if (CI->isNullValue()) { // (X / pos) op 0
2568 // Can't overflow.
2569 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2570 HiBound = DivRHS;
2571 } else if (isPositive(CI)) { // (X / pos) op pos
2572 LoBound = Prod;
2573 LoOverflow = ProdOV;
2574 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2575 } else { // (X / pos) op neg
2576 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2577 LoOverflow = AddWithOverflow(LoBound, Prod,
2578 cast<ConstantInt>(DivRHSH));
2579 HiBound = Prod;
2580 HiOverflow = ProdOV;
2581 }
2582 } else { // Divisor is < 0.
2583 if (CI->isNullValue()) { // (X / neg) op 0
2584 LoBound = AddOne(DivRHS);
2585 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2586 } else if (isPositive(CI)) { // (X / neg) op pos
2587 HiOverflow = LoOverflow = ProdOV;
2588 if (!LoOverflow)
2589 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2590 HiBound = AddOne(Prod);
2591 } else { // (X / neg) op neg
2592 LoBound = Prod;
2593 LoOverflow = HiOverflow = ProdOV;
2594 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2595 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002596
Chris Lattnera92af962004-10-11 19:40:04 +00002597 // Dividing by a negate swaps the condition.
2598 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002599 }
2600
2601 if (LoBound) {
2602 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002603 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002604 default: assert(0 && "Unhandled setcc opcode!");
2605 case Instruction::SetEQ:
2606 if (LoOverflow && HiOverflow)
2607 return ReplaceInstUsesWith(I, ConstantBool::False);
2608 else if (HiOverflow)
2609 return new SetCondInst(Instruction::SetGE, X, LoBound);
2610 else if (LoOverflow)
2611 return new SetCondInst(Instruction::SetLT, X, HiBound);
2612 else
2613 return InsertRangeTest(X, LoBound, HiBound, true, I);
2614 case Instruction::SetNE:
2615 if (LoOverflow && HiOverflow)
2616 return ReplaceInstUsesWith(I, ConstantBool::True);
2617 else if (HiOverflow)
2618 return new SetCondInst(Instruction::SetLT, X, LoBound);
2619 else if (LoOverflow)
2620 return new SetCondInst(Instruction::SetGE, X, HiBound);
2621 else
2622 return InsertRangeTest(X, LoBound, HiBound, false, I);
2623 case Instruction::SetLT:
2624 if (LoOverflow)
2625 return ReplaceInstUsesWith(I, ConstantBool::False);
2626 return new SetCondInst(Instruction::SetLT, X, LoBound);
2627 case Instruction::SetGT:
2628 if (HiOverflow)
2629 return ReplaceInstUsesWith(I, ConstantBool::False);
2630 return new SetCondInst(Instruction::SetGE, X, HiBound);
2631 }
2632 }
2633 }
2634 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002635 case Instruction::Select:
2636 // If either operand of the select is a constant, we can fold the
2637 // comparison into the select arms, which will cause one to be
2638 // constant folded and the select turned into a bitwise or.
2639 Value *Op1 = 0, *Op2 = 0;
2640 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002641 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002642 // Fold the known value into the constant operand.
2643 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2644 // Insert a new SetCC of the other select operand.
2645 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002646 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002647 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002648 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002649 // Fold the known value into the constant operand.
2650 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2651 // Insert a new SetCC of the other select operand.
2652 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002653 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002654 I.getName()), I);
2655 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002656 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002657
2658 if (Op1)
2659 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2660 break;
2661 }
2662
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002663 // Simplify seteq and setne instructions...
2664 if (I.getOpcode() == Instruction::SetEQ ||
2665 I.getOpcode() == Instruction::SetNE) {
2666 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2667
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002668 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002669 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002670 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2671 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002672 case Instruction::Rem:
2673 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2674 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2675 BO->hasOneUse() &&
2676 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2677 if (unsigned L2 =
2678 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2679 const Type *UTy = BO->getType()->getUnsignedVersion();
2680 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2681 UTy, "tmp"), I);
2682 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2683 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2684 RHSCst, BO->getName()), I);
2685 return BinaryOperator::create(I.getOpcode(), NewRem,
2686 Constant::getNullValue(UTy));
2687 }
2688 break;
2689
Chris Lattnerc992add2003-08-13 05:33:12 +00002690 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002691 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2692 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002693 if (BO->hasOneUse())
2694 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2695 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002696 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002697 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2698 // efficiently invertible, or if the add has just this one use.
2699 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002700
Chris Lattnerc992add2003-08-13 05:33:12 +00002701 if (Value *NegVal = dyn_castNegVal(BOp1))
2702 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2703 else if (Value *NegVal = dyn_castNegVal(BOp0))
2704 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002705 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002706 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2707 BO->setName("");
2708 InsertNewInstBefore(Neg, I);
2709 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2710 }
2711 }
2712 break;
2713 case Instruction::Xor:
2714 // For the xor case, we can xor two constants together, eliminating
2715 // the explicit xor.
2716 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2717 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002718 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002719
2720 // FALLTHROUGH
2721 case Instruction::Sub:
2722 // Replace (([sub|xor] A, B) != 0) with (A != B)
2723 if (CI->isNullValue())
2724 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2725 BO->getOperand(1));
2726 break;
2727
2728 case Instruction::Or:
2729 // If bits are being or'd in that are not present in the constant we
2730 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002731 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002732 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002733 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002734 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002735 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002736 break;
2737
2738 case Instruction::And:
2739 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002740 // If bits are being compared against that are and'd out, then the
2741 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002742 if (!ConstantExpr::getAnd(CI,
2743 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002744 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002745
Chris Lattner35167c32004-06-09 07:59:58 +00002746 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002747 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002748 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2749 Instruction::SetNE, Op0,
2750 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002751
Chris Lattnerc992add2003-08-13 05:33:12 +00002752 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2753 // to be a signed value as appropriate.
2754 if (isSignBit(BOC)) {
2755 Value *X = BO->getOperand(0);
2756 // If 'X' is not signed, insert a cast now...
2757 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002758 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002759 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002760 }
2761 return new SetCondInst(isSetNE ? Instruction::SetLT :
2762 Instruction::SetGE, X,
2763 Constant::getNullValue(X->getType()));
2764 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002765
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002766 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002767 if (CI->isNullValue() && isHighOnes(BOC)) {
2768 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002769 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002770
2771 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002772 if (NegX->getType()->isSigned()) {
2773 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2774 X = InsertCastBefore(X, DestTy, I);
2775 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002776 }
2777
2778 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002779 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002780 }
2781
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002782 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002783 default: break;
2784 }
2785 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002786 } else { // Not a SetEQ/SetNE
2787 // If the LHS is a cast from an integral value of the same size,
2788 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2789 Value *CastOp = Cast->getOperand(0);
2790 const Type *SrcTy = CastOp->getType();
2791 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2792 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2793 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2794 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2795 "Source and destination signednesses should differ!");
2796 if (Cast->getType()->isSigned()) {
2797 // If this is a signed comparison, check for comparisons in the
2798 // vicinity of zero.
2799 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2800 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002801 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002802 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2803 else if (I.getOpcode() == Instruction::SetGT &&
2804 cast<ConstantSInt>(CI)->getValue() == -1)
2805 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002806 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002807 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2808 } else {
2809 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2810 if (I.getOpcode() == Instruction::SetLT &&
2811 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2812 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002813 return BinaryOperator::createSetGT(CastOp,
2814 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002815 else if (I.getOpcode() == Instruction::SetGT &&
2816 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2817 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002818 return BinaryOperator::createSetLT(CastOp,
2819 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002820 }
2821 }
2822 }
Chris Lattnere967b342003-06-04 05:10:11 +00002823 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002824 }
2825
Chris Lattner0798af32005-01-13 20:14:25 +00002826 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2827 if (User *GEP = dyn_castGetElementPtr(Op0))
2828 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2829 return NI;
2830 if (User *GEP = dyn_castGetElementPtr(Op1))
2831 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2832 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2833 return NI;
2834
Chris Lattner16930792003-11-03 04:25:02 +00002835 // Test to see if the operands of the setcc are casted versions of other
2836 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002837 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2838 Value *CastOp0 = CI->getOperand(0);
2839 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002840 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002841 (I.getOpcode() == Instruction::SetEQ ||
2842 I.getOpcode() == Instruction::SetNE)) {
2843 // We keep moving the cast from the left operand over to the right
2844 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002845 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002846
2847 // If operand #1 is a cast instruction, see if we can eliminate it as
2848 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002849 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2850 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002851 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002852 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002853
2854 // If Op1 is a constant, we can fold the cast into the constant.
2855 if (Op1->getType() != Op0->getType())
2856 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2857 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2858 } else {
2859 // Otherwise, cast the RHS right before the setcc
2860 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2861 InsertNewInstBefore(cast<Instruction>(Op1), I);
2862 }
2863 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2864 }
2865
Chris Lattner6444c372003-11-03 05:17:03 +00002866 // Handle the special case of: setcc (cast bool to X), <cst>
2867 // This comes up when you have code like
2868 // int X = A < B;
2869 // if (X) ...
2870 // For generality, we handle any zero-extension of any operand comparison
2871 // with a constant.
2872 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2873 const Type *SrcTy = CastOp0->getType();
2874 const Type *DestTy = Op0->getType();
2875 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2876 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2877 // Ok, we have an expansion of operand 0 into a new type. Get the
2878 // constant value, masink off bits which are not set in the RHS. These
2879 // could be set if the destination value is signed.
2880 uint64_t ConstVal = ConstantRHS->getRawValue();
2881 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2882
2883 // If the constant we are comparing it with has high bits set, which
2884 // don't exist in the original value, the values could never be equal,
2885 // because the source would be zero extended.
2886 unsigned SrcBits =
2887 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002888 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2889 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002890 switch (I.getOpcode()) {
2891 default: assert(0 && "Unknown comparison type!");
2892 case Instruction::SetEQ:
2893 return ReplaceInstUsesWith(I, ConstantBool::False);
2894 case Instruction::SetNE:
2895 return ReplaceInstUsesWith(I, ConstantBool::True);
2896 case Instruction::SetLT:
2897 case Instruction::SetLE:
2898 if (DestTy->isSigned() && HasSignBit)
2899 return ReplaceInstUsesWith(I, ConstantBool::False);
2900 return ReplaceInstUsesWith(I, ConstantBool::True);
2901 case Instruction::SetGT:
2902 case Instruction::SetGE:
2903 if (DestTy->isSigned() && HasSignBit)
2904 return ReplaceInstUsesWith(I, ConstantBool::True);
2905 return ReplaceInstUsesWith(I, ConstantBool::False);
2906 }
2907 }
2908
2909 // Otherwise, we can replace the setcc with a setcc of the smaller
2910 // operand value.
2911 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2912 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2913 }
2914 }
2915 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002916 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002917}
2918
Reid Spencer279fa252004-11-28 21:31:15 +00002919// visitSetCondInstWithCastAndConstant - this method is part of the
2920// visitSetCondInst method. It handles the situation where we have:
2921// (setcc (cast X to larger), CI)
2922// It tries to remove the cast and even the setcc if the CI value
2923// and range of the cast allow it.
2924Instruction *
2925InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2926 CastInst* LHSI,
2927 ConstantInt* CI) {
2928 const Type *SrcTy = LHSI->getOperand(0)->getType();
2929 const Type *DestTy = LHSI->getType();
Chris Lattner03f06f12005-01-17 03:20:02 +00002930 if (!SrcTy->isIntegral() || !DestTy->isIntegral())
2931 return 0;
2932
2933 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2934 unsigned DestBits = DestTy->getPrimitiveSize()*8;
2935 if (SrcTy == Type::BoolTy)
2936 SrcBits = 1;
2937 if (DestTy == Type::BoolTy)
2938 DestBits = 1;
2939 if (SrcBits < DestBits) {
2940 // There are fewer bits in the source of the cast than in the result
2941 // of the cast. Any other case doesn't matter because the constant
2942 // value won't have changed due to sign extension.
2943 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2944 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
2945 // The constant value operand of the setCC before and after a
2946 // cast to the source type of the cast instruction is the same
2947 // value, so we just replace with the same setcc opcode, but
2948 // using the source value compared to the constant casted to the
2949 // source type.
2950 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
2951 CastInst* Cst = new CastInst(LHSI->getOperand(0),
2952 SrcTy->getUnsignedVersion(),
2953 LHSI->getName());
2954 InsertNewInstBefore(Cst,I);
2955 return new SetCondInst(I.getOpcode(), Cst,
2956 ConstantExpr::getCast(CI,
2957 SrcTy->getUnsignedVersion()));
Reid Spencer279fa252004-11-28 21:31:15 +00002958 }
Chris Lattner03f06f12005-01-17 03:20:02 +00002959 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
2960 }
2961
2962 // The constant value before and after a cast to the source type
2963 // is different, so various cases are possible depending on the
2964 // opcode and the signs of the types involved in the cast.
2965 switch (I.getOpcode()) {
2966 case Instruction::SetLT: {
2967 return 0;
2968 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
2969 Max = ConstantExpr::getCast(Max, DestTy);
2970 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2971 }
2972 case Instruction::SetGT: {
2973 return 0; // FIXME! RENABLE. This breaks for (cast sbyte to uint) > 255
2974 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
2975 Min = ConstantExpr::getCast(Min, DestTy);
2976 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2977 }
2978 case Instruction::SetEQ:
2979 // We're looking for equality, and we know the values are not
2980 // equal so replace with constant False.
2981 return ReplaceInstUsesWith(I, ConstantBool::False);
2982 case Instruction::SetNE:
2983 // We're testing for inequality, and we know the values are not
2984 // equal so replace with constant True.
2985 return ReplaceInstUsesWith(I, ConstantBool::True);
2986 case Instruction::SetLE:
2987 case Instruction::SetGE:
2988 assert(0 && "SetLE and SetGE should be handled elsewhere");
2989 default:
2990 assert(0 && "unknown integer comparison");
Reid Spencer279fa252004-11-28 21:31:15 +00002991 }
2992 }
2993 return 0;
2994}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002995
2996
Chris Lattnere8d6c602003-03-10 19:16:08 +00002997Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002998 assert(I.getOperand(1)->getType() == Type::UByteTy);
2999 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003000 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003001
3002 // shl X, 0 == X and shr X, 0 == X
3003 // shl 0, X == 0 and shr 0, X == 0
3004 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003005 Op0 == Constant::getNullValue(Op0->getType()))
3006 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003007
Chris Lattner81a7a232004-10-16 18:11:37 +00003008 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3009 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003010 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003011 else // undef << X -> 0 AND undef >>u X -> 0
3012 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3013 }
3014 if (isa<UndefValue>(Op1)) {
3015 if (isLeftShift || I.getType()->isUnsigned())
3016 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3017 else
3018 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3019 }
3020
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003021 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3022 if (!isLeftShift)
3023 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3024 if (CSI->isAllOnesValue())
3025 return ReplaceInstUsesWith(I, CSI);
3026
Chris Lattner183b3362004-04-09 19:05:30 +00003027 // Try to fold constant and into select arguments.
3028 if (isa<Constant>(Op0))
3029 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003030 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003031 return R;
3032
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003033 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003034 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3035 // of a signed value.
3036 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00003037 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003038 if (CUI->getValue() >= TypeBits) {
3039 if (!Op0->getType()->isSigned() || isLeftShift)
3040 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3041 else {
3042 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3043 return &I;
3044 }
3045 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003046
Chris Lattnerede3fe02003-08-13 04:18:28 +00003047 // ((X*C1) << C2) == (X * (C1 << C2))
3048 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3049 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3050 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003051 return BinaryOperator::createMul(BO->getOperand(0),
3052 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00003053
Chris Lattner183b3362004-04-09 19:05:30 +00003054 // Try to fold constant and into select arguments.
3055 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003056 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003057 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003058 if (isa<PHINode>(Op0))
3059 if (Instruction *NV = FoldOpIntoPhi(I))
3060 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003061
Chris Lattner86102b82005-01-01 16:22:27 +00003062 if (Op0->hasOneUse()) {
3063 // If this is a SHL of a sign-extending cast, see if we can turn the input
3064 // into a zero extending cast (a simple strength reduction).
3065 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3066 const Type *SrcTy = CI->getOperand(0)->getType();
3067 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3068 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
3069 // We can change it to a zero extension if we are shifting out all of
3070 // the sign extended bits. To check this, form a mask of all of the
3071 // sign extend bits, then shift them left and see if we have anything
3072 // left.
3073 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3074 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3075 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3076 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3077 // If the shift is nuking all of the sign bits, change this to a
3078 // zero extension cast. To do this, cast the cast input to
3079 // unsigned, then to the requested size.
3080 Value *CastOp = CI->getOperand(0);
3081 Instruction *NC =
3082 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3083 CI->getName()+".uns");
3084 NC = InsertNewInstBefore(NC, I);
3085 // Finally, insert a replacement for CI.
3086 NC = new CastInst(NC, CI->getType(), CI->getName());
3087 CI->setName("");
3088 NC = InsertNewInstBefore(NC, I);
3089 WorkList.push_back(CI); // Delete CI later.
3090 I.setOperand(0, NC);
3091 return &I; // The SHL operand was modified.
3092 }
3093 }
3094 }
3095
3096 // If the operand is an bitwise operator with a constant RHS, and the
3097 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003098 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3099 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3100 bool isValid = true; // Valid only for And, Or, Xor
3101 bool highBitSet = false; // Transform if high bit of constant set?
3102
3103 switch (Op0BO->getOpcode()) {
3104 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003105 case Instruction::Add:
3106 isValid = isLeftShift;
3107 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003108 case Instruction::Or:
3109 case Instruction::Xor:
3110 highBitSet = false;
3111 break;
3112 case Instruction::And:
3113 highBitSet = true;
3114 break;
3115 }
3116
3117 // If this is a signed shift right, and the high bit is modified
3118 // by the logical operation, do not perform the transformation.
3119 // The highBitSet boolean indicates the value of the high bit of
3120 // the constant which would cause it to be modified for this
3121 // operation.
3122 //
3123 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3124 uint64_t Val = Op0C->getRawValue();
3125 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3126 }
3127
3128 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003129 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003130
3131 Instruction *NewShift =
3132 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3133 Op0BO->getName());
3134 Op0BO->setName("");
3135 InsertNewInstBefore(NewShift, I);
3136
3137 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3138 NewRHS);
3139 }
3140 }
Chris Lattner86102b82005-01-01 16:22:27 +00003141 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003142
Chris Lattner3204d4e2003-07-24 17:52:58 +00003143 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003144 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003145 if (ConstantUInt *ShiftAmt1C =
3146 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003147 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3148 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003149
3150 // Check for (A << c1) << c2 and (A >> c1) >> c2
3151 if (I.getOpcode() == Op0SI->getOpcode()) {
3152 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003153 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
3154 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00003155 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3156 ConstantUInt::get(Type::UByteTy, Amt));
3157 }
3158
Chris Lattnerab780df2003-07-24 18:38:56 +00003159 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3160 // signed types, we can only support the (A >> c1) << c2 configuration,
3161 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003162 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003163 // Calculate bitmask for what gets shifted off the edge...
3164 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003165 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003166 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003167 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003168 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00003169
3170 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003171 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3172 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003173 InsertNewInstBefore(Mask, I);
3174
3175 // Figure out what flavor of shift we should use...
3176 if (ShiftAmt1 == ShiftAmt2)
3177 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3178 else if (ShiftAmt1 < ShiftAmt2) {
3179 return new ShiftInst(I.getOpcode(), Mask,
3180 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3181 } else {
3182 return new ShiftInst(Op0SI->getOpcode(), Mask,
3183 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3184 }
3185 }
3186 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003187 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003188
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003189 return 0;
3190}
3191
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003192enum CastType {
3193 Noop = 0,
3194 Truncate = 1,
3195 Signext = 2,
3196 Zeroext = 3
3197};
3198
3199/// getCastType - In the future, we will split the cast instruction into these
3200/// various types. Until then, we have to do the analysis here.
3201static CastType getCastType(const Type *Src, const Type *Dest) {
3202 assert(Src->isIntegral() && Dest->isIntegral() &&
3203 "Only works on integral types!");
3204 unsigned SrcSize = Src->getPrimitiveSize()*8;
3205 if (Src == Type::BoolTy) SrcSize = 1;
3206 unsigned DestSize = Dest->getPrimitiveSize()*8;
3207 if (Dest == Type::BoolTy) DestSize = 1;
3208
3209 if (SrcSize == DestSize) return Noop;
3210 if (SrcSize > DestSize) return Truncate;
3211 if (Src->isSigned()) return Signext;
3212 return Zeroext;
3213}
3214
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003215
Chris Lattner48a44f72002-05-02 17:06:02 +00003216// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3217// instruction.
3218//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003219static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003220 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003221
Chris Lattner650b6da2002-08-02 20:00:25 +00003222 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3223 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003224 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003225 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003226 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003227
Chris Lattner4fbad962004-07-21 04:27:24 +00003228 // If we are casting between pointer and integer types, treat pointers as
3229 // integers of the appropriate size for the code below.
3230 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3231 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3232 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003233
Chris Lattner48a44f72002-05-02 17:06:02 +00003234 // Allow free casting and conversion of sizes as long as the sign doesn't
3235 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003236 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003237 CastType FirstCast = getCastType(SrcTy, MidTy);
3238 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003239
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003240 // Capture the effect of these two casts. If the result is a legal cast,
3241 // the CastType is stored here, otherwise a special code is used.
3242 static const unsigned CastResult[] = {
3243 // First cast is noop
3244 0, 1, 2, 3,
3245 // First cast is a truncate
3246 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3247 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003248 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003249 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003250 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003251 };
3252
3253 unsigned Result = CastResult[FirstCast*4+SecondCast];
3254 switch (Result) {
3255 default: assert(0 && "Illegal table value!");
3256 case 0:
3257 case 1:
3258 case 2:
3259 case 3:
3260 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3261 // truncates, we could eliminate more casts.
3262 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3263 case 4:
3264 return false; // Not possible to eliminate this here.
3265 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003266 // Sign or zero extend followed by truncate is always ok if the result
3267 // is a truncate or noop.
3268 CastType ResultCast = getCastType(SrcTy, DstTy);
3269 if (ResultCast == Noop || ResultCast == Truncate)
3270 return true;
3271 // Otherwise we are still growing the value, we are only safe if the
3272 // result will match the sign/zeroextendness of the result.
3273 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003274 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003275 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003276 return false;
3277}
3278
Chris Lattner11ffd592004-07-20 05:21:00 +00003279static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003280 if (V->getType() == Ty || isa<Constant>(V)) return false;
3281 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003282 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3283 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003284 return false;
3285 return true;
3286}
3287
3288/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3289/// InsertBefore instruction. This is specialized a bit to avoid inserting
3290/// casts that are known to not do anything...
3291///
3292Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3293 Instruction *InsertBefore) {
3294 if (V->getType() == DestTy) return V;
3295 if (Constant *C = dyn_cast<Constant>(V))
3296 return ConstantExpr::getCast(C, DestTy);
3297
3298 CastInst *CI = new CastInst(V, DestTy, V->getName());
3299 InsertNewInstBefore(CI, *InsertBefore);
3300 return CI;
3301}
Chris Lattner48a44f72002-05-02 17:06:02 +00003302
3303// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003304//
Chris Lattner113f4f42002-06-25 16:13:24 +00003305Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003306 Value *Src = CI.getOperand(0);
3307
Chris Lattner48a44f72002-05-02 17:06:02 +00003308 // If the user is casting a value to the same type, eliminate this cast
3309 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003310 if (CI.getType() == Src->getType())
3311 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003312
Chris Lattner81a7a232004-10-16 18:11:37 +00003313 if (isa<UndefValue>(Src)) // cast undef -> undef
3314 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3315
Chris Lattner48a44f72002-05-02 17:06:02 +00003316 // If casting the result of another cast instruction, try to eliminate this
3317 // one!
3318 //
Chris Lattner86102b82005-01-01 16:22:27 +00003319 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3320 Value *A = CSrc->getOperand(0);
3321 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3322 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003323 // This instruction now refers directly to the cast's src operand. This
3324 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003325 CI.setOperand(0, CSrc->getOperand(0));
3326 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003327 }
3328
Chris Lattner650b6da2002-08-02 20:00:25 +00003329 // If this is an A->B->A cast, and we are dealing with integral types, try
3330 // to convert this into a logical 'and' instruction.
3331 //
Chris Lattner86102b82005-01-01 16:22:27 +00003332 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003333 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003334 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
3335 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()&&
3336 A->getType()->getPrimitiveSize() == CI.getType()->getPrimitiveSize()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003337 assert(CSrc->getType() != Type::ULongTy &&
3338 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00003339 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner86102b82005-01-01 16:22:27 +00003340 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3341 AndValue);
3342 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3343 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3344 if (And->getType() != CI.getType()) {
3345 And->setName(CSrc->getName()+".mask");
3346 InsertNewInstBefore(And, CI);
3347 And = new CastInst(And, CI.getType());
3348 }
3349 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003350 }
3351 }
Chris Lattner86102b82005-01-01 16:22:27 +00003352
Chris Lattner03841652004-05-25 04:29:21 +00003353 // If this is a cast to bool, turn it into the appropriate setne instruction.
3354 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003355 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003356 Constant::getNullValue(CI.getOperand(0)->getType()));
3357
Chris Lattnerd0d51602003-06-21 23:12:02 +00003358 // If casting the result of a getelementptr instruction with no offset, turn
3359 // this into a cast of the original pointer!
3360 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003361 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003362 bool AllZeroOperands = true;
3363 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3364 if (!isa<Constant>(GEP->getOperand(i)) ||
3365 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3366 AllZeroOperands = false;
3367 break;
3368 }
3369 if (AllZeroOperands) {
3370 CI.setOperand(0, GEP->getOperand(0));
3371 return &CI;
3372 }
3373 }
3374
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003375 // If we are casting a malloc or alloca to a pointer to a type of the same
3376 // size, rewrite the allocation instruction to allocate the "right" type.
3377 //
3378 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003379 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003380 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3381 // Get the type really allocated and the type casted to...
3382 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003383 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003384 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003385 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3386 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003387
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003388 // If the allocation is for an even multiple of the cast type size
3389 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
3390 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003391 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003392 std::string Name = AI->getName(); AI->setName("");
3393 AllocationInst *New;
3394 if (isa<MallocInst>(AI))
3395 New = new MallocInst(CastElTy, Amt, Name);
3396 else
3397 New = new AllocaInst(CastElTy, Amt, Name);
3398 InsertNewInstBefore(New, *AI);
3399 return ReplaceInstUsesWith(CI, New);
3400 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003401 }
3402 }
3403
Chris Lattner86102b82005-01-01 16:22:27 +00003404 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3405 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3406 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003407 if (isa<PHINode>(Src))
3408 if (Instruction *NV = FoldOpIntoPhi(CI))
3409 return NV;
3410
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003411 // If the source value is an instruction with only this use, we can attempt to
3412 // propagate the cast into the instruction. Also, only handle integral types
3413 // for now.
3414 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003415 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003416 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3417 const Type *DestTy = CI.getType();
3418 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3419 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3420
3421 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3422 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3423
3424 switch (SrcI->getOpcode()) {
3425 case Instruction::Add:
3426 case Instruction::Mul:
3427 case Instruction::And:
3428 case Instruction::Or:
3429 case Instruction::Xor:
3430 // If we are discarding information, or just changing the sign, rewrite.
3431 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3432 // Don't insert two casts if they cannot be eliminated. We allow two
3433 // casts to be inserted if the sizes are the same. This could only be
3434 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003435 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3436 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003437 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3438 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3439 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3440 ->getOpcode(), Op0c, Op1c);
3441 }
3442 }
3443 break;
3444 case Instruction::Shl:
3445 // Allow changing the sign of the source operand. Do not allow changing
3446 // the size of the shift, UNLESS the shift amount is a constant. We
3447 // mush not change variable sized shifts to a smaller size, because it
3448 // is undefined to shift more bits out than exist in the value.
3449 if (DestBitSize == SrcBitSize ||
3450 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3451 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3452 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3453 }
3454 break;
3455 }
3456 }
3457
Chris Lattner260ab202002-04-18 17:39:14 +00003458 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003459}
3460
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003461/// GetSelectFoldableOperands - We want to turn code that looks like this:
3462/// %C = or %A, %B
3463/// %D = select %cond, %C, %A
3464/// into:
3465/// %C = select %cond, %B, 0
3466/// %D = or %A, %C
3467///
3468/// Assuming that the specified instruction is an operand to the select, return
3469/// a bitmask indicating which operands of this instruction are foldable if they
3470/// equal the other incoming value of the select.
3471///
3472static unsigned GetSelectFoldableOperands(Instruction *I) {
3473 switch (I->getOpcode()) {
3474 case Instruction::Add:
3475 case Instruction::Mul:
3476 case Instruction::And:
3477 case Instruction::Or:
3478 case Instruction::Xor:
3479 return 3; // Can fold through either operand.
3480 case Instruction::Sub: // Can only fold on the amount subtracted.
3481 case Instruction::Shl: // Can only fold on the shift amount.
3482 case Instruction::Shr:
3483 return 1;
3484 default:
3485 return 0; // Cannot fold
3486 }
3487}
3488
3489/// GetSelectFoldableConstant - For the same transformation as the previous
3490/// function, return the identity constant that goes into the select.
3491static Constant *GetSelectFoldableConstant(Instruction *I) {
3492 switch (I->getOpcode()) {
3493 default: assert(0 && "This cannot happen!"); abort();
3494 case Instruction::Add:
3495 case Instruction::Sub:
3496 case Instruction::Or:
3497 case Instruction::Xor:
3498 return Constant::getNullValue(I->getType());
3499 case Instruction::Shl:
3500 case Instruction::Shr:
3501 return Constant::getNullValue(Type::UByteTy);
3502 case Instruction::And:
3503 return ConstantInt::getAllOnesValue(I->getType());
3504 case Instruction::Mul:
3505 return ConstantInt::get(I->getType(), 1);
3506 }
3507}
3508
Chris Lattner411336f2005-01-19 21:50:18 +00003509/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3510/// have the same opcode and only one use each. Try to simplify this.
3511Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3512 Instruction *FI) {
3513 if (TI->getNumOperands() == 1) {
3514 // If this is a non-volatile load or a cast from the same type,
3515 // merge.
3516 if (TI->getOpcode() == Instruction::Cast) {
3517 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3518 return 0;
3519 } else {
3520 return 0; // unknown unary op.
3521 }
3522
3523 // Fold this by inserting a select from the input values.
3524 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3525 FI->getOperand(0), SI.getName()+".v");
3526 InsertNewInstBefore(NewSI, SI);
3527 return new CastInst(NewSI, TI->getType());
3528 }
3529
3530 // Only handle binary operators here.
3531 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3532 return 0;
3533
3534 // Figure out if the operations have any operands in common.
3535 Value *MatchOp, *OtherOpT, *OtherOpF;
3536 bool MatchIsOpZero;
3537 if (TI->getOperand(0) == FI->getOperand(0)) {
3538 MatchOp = TI->getOperand(0);
3539 OtherOpT = TI->getOperand(1);
3540 OtherOpF = FI->getOperand(1);
3541 MatchIsOpZero = true;
3542 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3543 MatchOp = TI->getOperand(1);
3544 OtherOpT = TI->getOperand(0);
3545 OtherOpF = FI->getOperand(0);
3546 MatchIsOpZero = false;
3547 } else if (!TI->isCommutative()) {
3548 return 0;
3549 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3550 MatchOp = TI->getOperand(0);
3551 OtherOpT = TI->getOperand(1);
3552 OtherOpF = FI->getOperand(0);
3553 MatchIsOpZero = true;
3554 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3555 MatchOp = TI->getOperand(1);
3556 OtherOpT = TI->getOperand(0);
3557 OtherOpF = FI->getOperand(1);
3558 MatchIsOpZero = true;
3559 } else {
3560 return 0;
3561 }
3562
3563 // If we reach here, they do have operations in common.
3564 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3565 OtherOpF, SI.getName()+".v");
3566 InsertNewInstBefore(NewSI, SI);
3567
3568 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3569 if (MatchIsOpZero)
3570 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3571 else
3572 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3573 } else {
3574 if (MatchIsOpZero)
3575 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3576 else
3577 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3578 }
3579}
3580
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003581Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003582 Value *CondVal = SI.getCondition();
3583 Value *TrueVal = SI.getTrueValue();
3584 Value *FalseVal = SI.getFalseValue();
3585
3586 // select true, X, Y -> X
3587 // select false, X, Y -> Y
3588 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003589 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003590 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003591 else {
3592 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003593 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003594 }
Chris Lattner533bc492004-03-30 19:37:13 +00003595
3596 // select C, X, X -> X
3597 if (TrueVal == FalseVal)
3598 return ReplaceInstUsesWith(SI, TrueVal);
3599
Chris Lattner81a7a232004-10-16 18:11:37 +00003600 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3601 return ReplaceInstUsesWith(SI, FalseVal);
3602 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3603 return ReplaceInstUsesWith(SI, TrueVal);
3604 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3605 if (isa<Constant>(TrueVal))
3606 return ReplaceInstUsesWith(SI, TrueVal);
3607 else
3608 return ReplaceInstUsesWith(SI, FalseVal);
3609 }
3610
Chris Lattner1c631e82004-04-08 04:43:23 +00003611 if (SI.getType() == Type::BoolTy)
3612 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3613 if (C == ConstantBool::True) {
3614 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003615 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003616 } else {
3617 // Change: A = select B, false, C --> A = and !B, C
3618 Value *NotCond =
3619 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3620 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003621 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003622 }
3623 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3624 if (C == ConstantBool::False) {
3625 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003626 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003627 } else {
3628 // Change: A = select B, C, true --> A = or !B, C
3629 Value *NotCond =
3630 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3631 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003632 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003633 }
3634 }
3635
Chris Lattner183b3362004-04-09 19:05:30 +00003636 // Selecting between two integer constants?
3637 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3638 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3639 // select C, 1, 0 -> cast C to int
3640 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3641 return new CastInst(CondVal, SI.getType());
3642 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3643 // select C, 0, 1 -> cast !C to int
3644 Value *NotCond =
3645 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003646 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003647 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003648 }
Chris Lattner35167c32004-06-09 07:59:58 +00003649
3650 // If one of the constants is zero (we know they can't both be) and we
3651 // have a setcc instruction with zero, and we have an 'and' with the
3652 // non-constant value, eliminate this whole mess. This corresponds to
3653 // cases like this: ((X & 27) ? 27 : 0)
3654 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3655 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3656 if ((IC->getOpcode() == Instruction::SetEQ ||
3657 IC->getOpcode() == Instruction::SetNE) &&
3658 isa<ConstantInt>(IC->getOperand(1)) &&
3659 cast<Constant>(IC->getOperand(1))->isNullValue())
3660 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3661 if (ICA->getOpcode() == Instruction::And &&
3662 isa<ConstantInt>(ICA->getOperand(1)) &&
3663 (ICA->getOperand(1) == TrueValC ||
3664 ICA->getOperand(1) == FalseValC) &&
3665 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3666 // Okay, now we know that everything is set up, we just don't
3667 // know whether we have a setne or seteq and whether the true or
3668 // false val is the zero.
3669 bool ShouldNotVal = !TrueValC->isNullValue();
3670 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3671 Value *V = ICA;
3672 if (ShouldNotVal)
3673 V = InsertNewInstBefore(BinaryOperator::create(
3674 Instruction::Xor, V, ICA->getOperand(1)), SI);
3675 return ReplaceInstUsesWith(SI, V);
3676 }
Chris Lattner533bc492004-03-30 19:37:13 +00003677 }
Chris Lattner623fba12004-04-10 22:21:27 +00003678
3679 // See if we are selecting two values based on a comparison of the two values.
3680 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3681 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3682 // Transform (X == Y) ? X : Y -> Y
3683 if (SCI->getOpcode() == Instruction::SetEQ)
3684 return ReplaceInstUsesWith(SI, FalseVal);
3685 // Transform (X != Y) ? X : Y -> X
3686 if (SCI->getOpcode() == Instruction::SetNE)
3687 return ReplaceInstUsesWith(SI, TrueVal);
3688 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3689
3690 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3691 // Transform (X == Y) ? Y : X -> X
3692 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003693 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003694 // Transform (X != Y) ? Y : X -> Y
3695 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003696 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003697 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3698 }
3699 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003700
Chris Lattnera04c9042005-01-13 22:52:24 +00003701 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3702 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3703 if (TI->hasOneUse() && FI->hasOneUse()) {
3704 bool isInverse = false;
3705 Instruction *AddOp = 0, *SubOp = 0;
3706
Chris Lattner411336f2005-01-19 21:50:18 +00003707 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3708 if (TI->getOpcode() == FI->getOpcode())
3709 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3710 return IV;
3711
3712 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3713 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00003714 if (TI->getOpcode() == Instruction::Sub &&
3715 FI->getOpcode() == Instruction::Add) {
3716 AddOp = FI; SubOp = TI;
3717 } else if (FI->getOpcode() == Instruction::Sub &&
3718 TI->getOpcode() == Instruction::Add) {
3719 AddOp = TI; SubOp = FI;
3720 }
3721
3722 if (AddOp) {
3723 Value *OtherAddOp = 0;
3724 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3725 OtherAddOp = AddOp->getOperand(1);
3726 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3727 OtherAddOp = AddOp->getOperand(0);
3728 }
3729
3730 if (OtherAddOp) {
3731 // So at this point we know we have:
3732 // select C, (add X, Y), (sub X, ?)
3733 // We can do the transform profitably if either 'Y' = '?' or '?' is
3734 // a constant.
3735 if (SubOp->getOperand(1) == AddOp ||
3736 isa<Constant>(SubOp->getOperand(1))) {
3737 Value *NegVal;
3738 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3739 NegVal = ConstantExpr::getNeg(C);
3740 } else {
3741 NegVal = InsertNewInstBefore(
3742 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3743 }
3744
Chris Lattner51726c42005-01-14 17:35:12 +00003745 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00003746 Value *NewFalseOp = NegVal;
3747 if (AddOp != TI)
3748 std::swap(NewTrueOp, NewFalseOp);
3749 Instruction *NewSel =
3750 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
3751
3752 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00003753 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00003754 }
3755 }
3756 }
3757 }
3758
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003759 // See if we can fold the select into one of our operands.
3760 if (SI.getType()->isInteger()) {
3761 // See the comment above GetSelectFoldableOperands for a description of the
3762 // transformation we are doing here.
3763 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3764 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3765 !isa<Constant>(FalseVal))
3766 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3767 unsigned OpToFold = 0;
3768 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3769 OpToFold = 1;
3770 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3771 OpToFold = 2;
3772 }
3773
3774 if (OpToFold) {
3775 Constant *C = GetSelectFoldableConstant(TVI);
3776 std::string Name = TVI->getName(); TVI->setName("");
3777 Instruction *NewSel =
3778 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3779 Name);
3780 InsertNewInstBefore(NewSel, SI);
3781 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3782 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3783 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3784 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3785 else {
3786 assert(0 && "Unknown instruction!!");
3787 }
3788 }
3789 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003790
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003791 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3792 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3793 !isa<Constant>(TrueVal))
3794 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3795 unsigned OpToFold = 0;
3796 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3797 OpToFold = 1;
3798 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3799 OpToFold = 2;
3800 }
3801
3802 if (OpToFold) {
3803 Constant *C = GetSelectFoldableConstant(FVI);
3804 std::string Name = FVI->getName(); FVI->setName("");
3805 Instruction *NewSel =
3806 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3807 Name);
3808 InsertNewInstBefore(NewSel, SI);
3809 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3810 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3811 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3812 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3813 else {
3814 assert(0 && "Unknown instruction!!");
3815 }
3816 }
3817 }
3818 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003819 return 0;
3820}
3821
3822
Chris Lattner970c33a2003-06-19 17:00:31 +00003823// CallInst simplification
3824//
3825Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003826 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3827 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003828 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3829 bool Changed = false;
3830
3831 // memmove/cpy/set of zero bytes is a noop.
3832 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3833 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3834
3835 // FIXME: Increase alignment here.
3836
3837 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3838 if (CI->getRawValue() == 1) {
3839 // Replace the instruction with just byte operations. We would
3840 // transform other cases to loads/stores, but we don't know if
3841 // alignment is sufficient.
3842 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003843 }
3844
Chris Lattner00648e12004-10-12 04:52:52 +00003845 // If we have a memmove and the source operation is a constant global,
3846 // then the source and dest pointers can't alias, so we can change this
3847 // into a call to memcpy.
3848 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3849 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3850 if (GVSrc->isConstant()) {
3851 Module *M = CI.getParent()->getParent()->getParent();
3852 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3853 CI.getCalledFunction()->getFunctionType());
3854 CI.setOperand(0, MemCpy);
3855 Changed = true;
3856 }
3857
3858 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003859 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3860 // If this stoppoint is at the same source location as the previous
3861 // stoppoint in the chain, it is not needed.
3862 if (DbgStopPointInst *PrevSPI =
3863 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3864 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3865 SPI->getColNo() == PrevSPI->getColNo()) {
3866 SPI->replaceAllUsesWith(PrevSPI);
3867 return EraseInstFromFunction(CI);
3868 }
Chris Lattner00648e12004-10-12 04:52:52 +00003869 }
3870
Chris Lattneraec3d942003-10-07 22:32:43 +00003871 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003872}
3873
3874// InvokeInst simplification
3875//
3876Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003877 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003878}
3879
Chris Lattneraec3d942003-10-07 22:32:43 +00003880// visitCallSite - Improvements for call and invoke instructions.
3881//
3882Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003883 bool Changed = false;
3884
3885 // If the callee is a constexpr cast of a function, attempt to move the cast
3886 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003887 if (transformConstExprCastCall(CS)) return 0;
3888
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003889 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003890
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003891 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3892 // This instruction is not reachable, just remove it. We insert a store to
3893 // undef so that we know that this code is not reachable, despite the fact
3894 // that we can't modify the CFG here.
3895 new StoreInst(ConstantBool::True,
3896 UndefValue::get(PointerType::get(Type::BoolTy)),
3897 CS.getInstruction());
3898
3899 if (!CS.getInstruction()->use_empty())
3900 CS.getInstruction()->
3901 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3902
3903 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3904 // Don't break the CFG, insert a dummy cond branch.
3905 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3906 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003907 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003908 return EraseInstFromFunction(*CS.getInstruction());
3909 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003910
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003911 const PointerType *PTy = cast<PointerType>(Callee->getType());
3912 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3913 if (FTy->isVarArg()) {
3914 // See if we can optimize any arguments passed through the varargs area of
3915 // the call.
3916 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3917 E = CS.arg_end(); I != E; ++I)
3918 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3919 // If this cast does not effect the value passed through the varargs
3920 // area, we can eliminate the use of the cast.
3921 Value *Op = CI->getOperand(0);
3922 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3923 *I = Op;
3924 Changed = true;
3925 }
3926 }
3927 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003928
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003929 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003930}
3931
Chris Lattner970c33a2003-06-19 17:00:31 +00003932// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3933// attempt to move the cast to the arguments of the call/invoke.
3934//
3935bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3936 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3937 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003938 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003939 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003940 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003941 Instruction *Caller = CS.getInstruction();
3942
3943 // Okay, this is a cast from a function to a different type. Unless doing so
3944 // would cause a type conversion of one of our arguments, change this call to
3945 // be a direct call with arguments casted to the appropriate types.
3946 //
3947 const FunctionType *FT = Callee->getFunctionType();
3948 const Type *OldRetTy = Caller->getType();
3949
Chris Lattner1f7942f2004-01-14 06:06:08 +00003950 // Check to see if we are changing the return type...
3951 if (OldRetTy != FT->getReturnType()) {
3952 if (Callee->isExternal() &&
3953 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3954 !Caller->use_empty())
3955 return false; // Cannot transform this return value...
3956
3957 // If the callsite is an invoke instruction, and the return value is used by
3958 // a PHI node in a successor, we cannot change the return type of the call
3959 // because there is no place to put the cast instruction (without breaking
3960 // the critical edge). Bail out in this case.
3961 if (!Caller->use_empty())
3962 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3963 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3964 UI != E; ++UI)
3965 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3966 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003967 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003968 return false;
3969 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003970
3971 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3972 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3973
3974 CallSite::arg_iterator AI = CS.arg_begin();
3975 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3976 const Type *ParamTy = FT->getParamType(i);
3977 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3978 if (Callee->isExternal() && !isConvertible) return false;
3979 }
3980
3981 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3982 Callee->isExternal())
3983 return false; // Do not delete arguments unless we have a function body...
3984
3985 // Okay, we decided that this is a safe thing to do: go ahead and start
3986 // inserting cast instructions as necessary...
3987 std::vector<Value*> Args;
3988 Args.reserve(NumActualArgs);
3989
3990 AI = CS.arg_begin();
3991 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3992 const Type *ParamTy = FT->getParamType(i);
3993 if ((*AI)->getType() == ParamTy) {
3994 Args.push_back(*AI);
3995 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003996 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3997 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003998 }
3999 }
4000
4001 // If the function takes more arguments than the call was taking, add them
4002 // now...
4003 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4004 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4005
4006 // If we are removing arguments to the function, emit an obnoxious warning...
4007 if (FT->getNumParams() < NumActualArgs)
4008 if (!FT->isVarArg()) {
4009 std::cerr << "WARNING: While resolving call to function '"
4010 << Callee->getName() << "' arguments were dropped!\n";
4011 } else {
4012 // Add all of the arguments in their promoted form to the arg list...
4013 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4014 const Type *PTy = getPromotedType((*AI)->getType());
4015 if (PTy != (*AI)->getType()) {
4016 // Must promote to pass through va_arg area!
4017 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4018 InsertNewInstBefore(Cast, *Caller);
4019 Args.push_back(Cast);
4020 } else {
4021 Args.push_back(*AI);
4022 }
4023 }
4024 }
4025
4026 if (FT->getReturnType() == Type::VoidTy)
4027 Caller->setName(""); // Void type should not have a name...
4028
4029 Instruction *NC;
4030 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004031 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004032 Args, Caller->getName(), Caller);
4033 } else {
4034 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4035 }
4036
4037 // Insert a cast of the return type as necessary...
4038 Value *NV = NC;
4039 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4040 if (NV->getType() != Type::VoidTy) {
4041 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004042
4043 // If this is an invoke instruction, we should insert it after the first
4044 // non-phi, instruction in the normal successor block.
4045 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4046 BasicBlock::iterator I = II->getNormalDest()->begin();
4047 while (isa<PHINode>(I)) ++I;
4048 InsertNewInstBefore(NC, *I);
4049 } else {
4050 // Otherwise, it's a call, just insert cast right after the call instr
4051 InsertNewInstBefore(NC, *Caller);
4052 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004053 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004054 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004055 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004056 }
4057 }
4058
4059 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4060 Caller->replaceAllUsesWith(NV);
4061 Caller->getParent()->getInstList().erase(Caller);
4062 removeFromWorkList(Caller);
4063 return true;
4064}
4065
4066
Chris Lattner7515cab2004-11-14 19:13:23 +00004067// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4068// operator and they all are only used by the PHI, PHI together their
4069// inputs, and do the operation once, to the result of the PHI.
4070Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4071 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4072
4073 // Scan the instruction, looking for input operations that can be folded away.
4074 // If all input operands to the phi are the same instruction (e.g. a cast from
4075 // the same type or "+42") we can pull the operation through the PHI, reducing
4076 // code size and simplifying code.
4077 Constant *ConstantOp = 0;
4078 const Type *CastSrcTy = 0;
4079 if (isa<CastInst>(FirstInst)) {
4080 CastSrcTy = FirstInst->getOperand(0)->getType();
4081 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4082 // Can fold binop or shift if the RHS is a constant.
4083 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4084 if (ConstantOp == 0) return 0;
4085 } else {
4086 return 0; // Cannot fold this operation.
4087 }
4088
4089 // Check to see if all arguments are the same operation.
4090 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4091 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4092 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4093 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4094 return 0;
4095 if (CastSrcTy) {
4096 if (I->getOperand(0)->getType() != CastSrcTy)
4097 return 0; // Cast operation must match.
4098 } else if (I->getOperand(1) != ConstantOp) {
4099 return 0;
4100 }
4101 }
4102
4103 // Okay, they are all the same operation. Create a new PHI node of the
4104 // correct type, and PHI together all of the LHS's of the instructions.
4105 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4106 PN.getName()+".in");
4107 NewPN->op_reserve(PN.getNumOperands());
Chris Lattner46dd5a62004-11-14 19:29:34 +00004108
4109 Value *InVal = FirstInst->getOperand(0);
4110 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004111
4112 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004113 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4114 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4115 if (NewInVal != InVal)
4116 InVal = 0;
4117 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4118 }
4119
4120 Value *PhiVal;
4121 if (InVal) {
4122 // The new PHI unions all of the same values together. This is really
4123 // common, so we handle it intelligently here for compile-time speed.
4124 PhiVal = InVal;
4125 delete NewPN;
4126 } else {
4127 InsertNewInstBefore(NewPN, PN);
4128 PhiVal = NewPN;
4129 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004130
4131 // Insert and return the new operation.
4132 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004133 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004134 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004135 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004136 else
4137 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004138 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004139}
Chris Lattner48a44f72002-05-02 17:06:02 +00004140
Chris Lattner71536432005-01-17 05:10:15 +00004141/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4142/// that is dead.
4143static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4144 if (PN->use_empty()) return true;
4145 if (!PN->hasOneUse()) return false;
4146
4147 // Remember this node, and if we find the cycle, return.
4148 if (!PotentiallyDeadPHIs.insert(PN).second)
4149 return true;
4150
4151 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4152 return DeadPHICycle(PU, PotentiallyDeadPHIs);
4153
4154 return false;
4155}
4156
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004157// PHINode simplification
4158//
Chris Lattner113f4f42002-06-25 16:13:24 +00004159Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00004160 if (Value *V = hasConstantValue(&PN)) {
4161 // If V is an instruction, we have to be certain that it dominates PN.
4162 // However, because we don't have dom info, we can't do a perfect job.
4163 if (Instruction *I = dyn_cast<Instruction>(V)) {
4164 // We know that the instruction dominates the PHI if there are no undef
4165 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00004166 if (I->getParent() != &I->getParent()->getParent()->front() ||
4167 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00004168 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4169 if (isa<UndefValue>(PN.getIncomingValue(i))) {
4170 V = 0;
4171 break;
4172 }
Chris Lattnere29d6342004-10-17 21:22:38 +00004173 }
4174
4175 if (V)
4176 return ReplaceInstUsesWith(PN, V);
4177 }
Chris Lattner4db2d222004-02-16 05:07:08 +00004178
4179 // If the only user of this instruction is a cast instruction, and all of the
4180 // incoming values are constants, change this PHI to merge together the casted
4181 // constants.
4182 if (PN.hasOneUse())
4183 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4184 if (CI->getType() != PN.getType()) { // noop casts will be folded
4185 bool AllConstant = true;
4186 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4187 if (!isa<Constant>(PN.getIncomingValue(i))) {
4188 AllConstant = false;
4189 break;
4190 }
4191 if (AllConstant) {
4192 // Make a new PHI with all casted values.
4193 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4194 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4195 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4196 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4197 PN.getIncomingBlock(i));
4198 }
4199
4200 // Update the cast instruction.
4201 CI->setOperand(0, New);
4202 WorkList.push_back(CI); // revisit the cast instruction to fold.
4203 WorkList.push_back(New); // Make sure to revisit the new Phi
4204 return &PN; // PN is now dead!
4205 }
4206 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004207
4208 // If all PHI operands are the same operation, pull them through the PHI,
4209 // reducing code size.
4210 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4211 PN.getIncomingValue(0)->hasOneUse())
4212 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4213 return Result;
4214
Chris Lattner71536432005-01-17 05:10:15 +00004215 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4216 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4217 // PHI)... break the cycle.
4218 if (PN.hasOneUse())
4219 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4220 std::set<PHINode*> PotentiallyDeadPHIs;
4221 PotentiallyDeadPHIs.insert(&PN);
4222 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4223 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4224 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004225
Chris Lattner91daeb52003-12-19 05:58:40 +00004226 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004227}
4228
Chris Lattner69193f92004-04-05 01:30:19 +00004229static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4230 Instruction *InsertPoint,
4231 InstCombiner *IC) {
4232 unsigned PS = IC->getTargetData().getPointerSize();
4233 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004234 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4235 // We must insert a cast to ensure we sign-extend.
4236 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4237 V->getName()), *InsertPoint);
4238 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4239 *InsertPoint);
4240}
4241
Chris Lattner48a44f72002-05-02 17:06:02 +00004242
Chris Lattner113f4f42002-06-25 16:13:24 +00004243Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004244 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004245 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004246 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004247 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004248 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004249
Chris Lattner81a7a232004-10-16 18:11:37 +00004250 if (isa<UndefValue>(GEP.getOperand(0)))
4251 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4252
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004253 bool HasZeroPointerIndex = false;
4254 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4255 HasZeroPointerIndex = C->isNullValue();
4256
4257 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004258 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004259
Chris Lattner69193f92004-04-05 01:30:19 +00004260 // Eliminate unneeded casts for indices.
4261 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004262 gep_type_iterator GTI = gep_type_begin(GEP);
4263 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4264 if (isa<SequentialType>(*GTI)) {
4265 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4266 Value *Src = CI->getOperand(0);
4267 const Type *SrcTy = Src->getType();
4268 const Type *DestTy = CI->getType();
4269 if (Src->getType()->isInteger()) {
4270 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
4271 // We can always eliminate a cast from ulong or long to the other.
4272 // We can always eliminate a cast from uint to int or the other on
4273 // 32-bit pointer platforms.
4274 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
4275 MadeChange = true;
4276 GEP.setOperand(i, Src);
4277 }
4278 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4279 SrcTy->getPrimitiveSize() == 4) {
4280 // We can always eliminate a cast from int to [u]long. We can
4281 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4282 // pointer target.
4283 if (SrcTy->isSigned() ||
4284 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
4285 MadeChange = true;
4286 GEP.setOperand(i, Src);
4287 }
Chris Lattner69193f92004-04-05 01:30:19 +00004288 }
4289 }
4290 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004291 // If we are using a wider index than needed for this platform, shrink it
4292 // to what we need. If the incoming value needs a cast instruction,
4293 // insert it. This explicit cast can make subsequent optimizations more
4294 // obvious.
4295 Value *Op = GEP.getOperand(i);
4296 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004297 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004298 GEP.setOperand(i, ConstantExpr::getCast(C,
4299 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004300 MadeChange = true;
4301 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004302 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4303 Op->getName()), GEP);
4304 GEP.setOperand(i, Op);
4305 MadeChange = true;
4306 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004307
4308 // If this is a constant idx, make sure to canonicalize it to be a signed
4309 // operand, otherwise CSE and other optimizations are pessimized.
4310 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4311 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4312 CUI->getType()->getSignedVersion()));
4313 MadeChange = true;
4314 }
Chris Lattner69193f92004-04-05 01:30:19 +00004315 }
4316 if (MadeChange) return &GEP;
4317
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004318 // Combine Indices - If the source pointer to this getelementptr instruction
4319 // is a getelementptr instruction, combine the indices of the two
4320 // getelementptr instructions into a single instruction.
4321 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004322 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004323 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004324 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004325
4326 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004327 // Note that if our source is a gep chain itself that we wait for that
4328 // chain to be resolved before we perform this transformation. This
4329 // avoids us creating a TON of code in some cases.
4330 //
4331 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4332 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4333 return 0; // Wait until our source is folded to completion.
4334
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004335 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004336
4337 // Find out whether the last index in the source GEP is a sequential idx.
4338 bool EndsWithSequential = false;
4339 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4340 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004341 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00004342
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004343 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004344 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004345 // Replace: gep (gep %P, long B), long A, ...
4346 // With: T = long A+B; gep %P, T, ...
4347 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004348 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004349 if (SO1 == Constant::getNullValue(SO1->getType())) {
4350 Sum = GO1;
4351 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4352 Sum = SO1;
4353 } else {
4354 // If they aren't the same type, convert both to an integer of the
4355 // target's pointer size.
4356 if (SO1->getType() != GO1->getType()) {
4357 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4358 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4359 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4360 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4361 } else {
4362 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004363 if (SO1->getType()->getPrimitiveSize() == PS) {
4364 // Convert GO1 to SO1's type.
4365 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4366
4367 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4368 // Convert SO1 to GO1's type.
4369 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4370 } else {
4371 const Type *PT = TD->getIntPtrType();
4372 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4373 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4374 }
4375 }
4376 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004377 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4378 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4379 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004380 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4381 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004382 }
Chris Lattner69193f92004-04-05 01:30:19 +00004383 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004384
4385 // Recycle the GEP we already have if possible.
4386 if (SrcGEPOperands.size() == 2) {
4387 GEP.setOperand(0, SrcGEPOperands[0]);
4388 GEP.setOperand(1, Sum);
4389 return &GEP;
4390 } else {
4391 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4392 SrcGEPOperands.end()-1);
4393 Indices.push_back(Sum);
4394 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4395 }
Chris Lattner69193f92004-04-05 01:30:19 +00004396 } else if (isa<Constant>(*GEP.idx_begin()) &&
4397 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00004398 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004399 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004400 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4401 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004402 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4403 }
4404
4405 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004406 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004407
Chris Lattner5f667a62004-05-07 22:09:22 +00004408 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004409 // GEP of global variable. If all of the indices for this GEP are
4410 // constants, we can promote this to a constexpr instead of an instruction.
4411
4412 // Scan for nonconstants...
4413 std::vector<Constant*> Indices;
4414 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4415 for (; I != E && isa<Constant>(*I); ++I)
4416 Indices.push_back(cast<Constant>(*I));
4417
4418 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004419 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004420
4421 // Replace all uses of the GEP with the new constexpr...
4422 return ReplaceInstUsesWith(GEP, CE);
4423 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004424 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004425 if (CE->getOpcode() == Instruction::Cast) {
4426 if (HasZeroPointerIndex) {
4427 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4428 // into : GEP [10 x ubyte]* X, long 0, ...
4429 //
4430 // This occurs when the program declares an array extern like "int X[];"
4431 //
4432 Constant *X = CE->getOperand(0);
4433 const PointerType *CPTy = cast<PointerType>(CE->getType());
4434 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4435 if (const ArrayType *XATy =
4436 dyn_cast<ArrayType>(XTy->getElementType()))
4437 if (const ArrayType *CATy =
4438 dyn_cast<ArrayType>(CPTy->getElementType()))
4439 if (CATy->getElementType() == XATy->getElementType()) {
4440 // At this point, we know that the cast source type is a pointer
4441 // to an array of the same type as the destination pointer
4442 // array. Because the array type is never stepped over (there
4443 // is a leading zero) we can fold the cast into this GEP.
4444 GEP.setOperand(0, X);
4445 return &GEP;
4446 }
Chris Lattner0798af32005-01-13 20:14:25 +00004447 } else if (GEP.getNumOperands() == 2 &&
4448 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004449 // Transform things like:
4450 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4451 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4452 Constant *X = CE->getOperand(0);
4453 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4454 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4455 if (isa<ArrayType>(SrcElTy) &&
4456 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4457 TD->getTypeSize(ResElTy)) {
4458 Value *V = InsertNewInstBefore(
4459 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4460 GEP.getOperand(1), GEP.getName()), GEP);
4461 return new CastInst(V, GEP.getType());
4462 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004463 }
4464 }
Chris Lattnerca081252001-12-14 16:52:21 +00004465 }
4466
Chris Lattnerca081252001-12-14 16:52:21 +00004467 return 0;
4468}
4469
Chris Lattner1085bdf2002-11-04 16:18:53 +00004470Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4471 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4472 if (AI.isArrayAllocation()) // Check C != 1
4473 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4474 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004475 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004476
4477 // Create and insert the replacement instruction...
4478 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004479 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004480 else {
4481 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004482 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004483 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004484
4485 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00004486
4487 // Scan to the end of the allocation instructions, to skip over a block of
4488 // allocas if possible...
4489 //
4490 BasicBlock::iterator It = New;
4491 while (isa<AllocationInst>(*It)) ++It;
4492
4493 // Now that I is pointing to the first non-allocation-inst in the block,
4494 // insert our getelementptr instruction...
4495 //
Chris Lattner69193f92004-04-05 01:30:19 +00004496 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004497 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
4498
4499 // Now make everything use the getelementptr instead of the original
4500 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004501 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004502 } else if (isa<UndefValue>(AI.getArraySize())) {
4503 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004504 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004505
4506 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4507 // Note that we only do this for alloca's, because malloc should allocate and
4508 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00004509 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
4510 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004511 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4512
Chris Lattner1085bdf2002-11-04 16:18:53 +00004513 return 0;
4514}
4515
Chris Lattner8427bff2003-12-07 01:24:23 +00004516Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4517 Value *Op = FI.getOperand(0);
4518
4519 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4520 if (CastInst *CI = dyn_cast<CastInst>(Op))
4521 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4522 FI.setOperand(0, CI->getOperand(0));
4523 return &FI;
4524 }
4525
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004526 // free undef -> unreachable.
4527 if (isa<UndefValue>(Op)) {
4528 // Insert a new store to null because we cannot modify the CFG here.
4529 new StoreInst(ConstantBool::True,
4530 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4531 return EraseInstFromFunction(FI);
4532 }
4533
Chris Lattnerf3a36602004-02-28 04:57:37 +00004534 // If we have 'free null' delete the instruction. This can happen in stl code
4535 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004536 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004537 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004538
Chris Lattner8427bff2003-12-07 01:24:23 +00004539 return 0;
4540}
4541
4542
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004543/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4544/// constantexpr, return the constant value being addressed by the constant
4545/// expression, or null if something is funny.
4546///
4547static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004548 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004549 return 0; // Do not allow stepping over the value!
4550
4551 // Loop over all of the operands, tracking down which value we are
4552 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004553 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4554 for (++I; I != E; ++I)
4555 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4556 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4557 assert(CU->getValue() < STy->getNumElements() &&
4558 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004559 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00004560 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004561 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00004562 } else if (isa<ConstantAggregateZero>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004563 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00004564 } else if (isa<UndefValue>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004565 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004566 } else {
4567 return 0;
4568 }
4569 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4570 const ArrayType *ATy = cast<ArrayType>(*I);
4571 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4572 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004573 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004574 else if (isa<ConstantAggregateZero>(C))
4575 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004576 else if (isa<UndefValue>(C))
4577 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004578 else
4579 return 0;
4580 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004581 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004582 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004583 return C;
4584}
4585
Chris Lattner35e24772004-07-13 01:49:43 +00004586static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4587 User *CI = cast<User>(LI.getOperand(0));
4588
4589 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4590 if (const PointerType *SrcTy =
4591 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
4592 const Type *SrcPTy = SrcTy->getElementType();
4593 if (SrcPTy->isSized() && DestPTy->isSized() &&
4594 IC.getTargetData().getTypeSize(SrcPTy) ==
4595 IC.getTargetData().getTypeSize(DestPTy) &&
4596 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
4597 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
4598 // Okay, we are casting from one integer or pointer type to another of
4599 // the same size. Instead of casting the pointer before the load, cast
4600 // the result of the loaded value.
4601 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004602 CI->getName(),
4603 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00004604 // Now cast the result of the load.
4605 return new CastInst(NewLoad, LI.getType());
4606 }
4607 }
4608 return 0;
4609}
4610
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004611/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004612/// from this value cannot trap. If it is not obviously safe to load from the
4613/// specified pointer, we do a quick local scan of the basic block containing
4614/// ScanFrom, to determine if the address is already accessed.
4615static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4616 // If it is an alloca or global variable, it is always safe to load from.
4617 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4618
4619 // Otherwise, be a little bit agressive by scanning the local block where we
4620 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004621 // from/to. If so, the previous load or store would have already trapped,
4622 // so there is no harm doing an extra load (also, CSE will later eliminate
4623 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004624 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4625
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004626 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004627 --BBI;
4628
4629 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4630 if (LI->getOperand(0) == V) return true;
4631 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4632 if (SI->getOperand(1) == V) return true;
4633
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004634 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004635 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004636}
4637
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004638Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4639 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004640
Chris Lattner81a7a232004-10-16 18:11:37 +00004641 if (Constant *C = dyn_cast<Constant>(Op)) {
4642 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004643 !LI.isVolatile()) { // load null/undef -> undef
4644 // Insert a new store to null instruction before the load to indicate that
4645 // this code is not reachable. We do this instead of inserting an
4646 // unreachable instruction directly because we cannot modify the CFG.
4647 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004648 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004649 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004650
Chris Lattner81a7a232004-10-16 18:11:37 +00004651 // Instcombine load (constant global) into the value loaded.
4652 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4653 if (GV->isConstant() && !GV->isExternal())
4654 return ReplaceInstUsesWith(LI, GV->getInitializer());
4655
4656 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4657 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4658 if (CE->getOpcode() == Instruction::GetElementPtr) {
4659 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4660 if (GV->isConstant() && !GV->isExternal())
4661 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4662 return ReplaceInstUsesWith(LI, V);
4663 } else if (CE->getOpcode() == Instruction::Cast) {
4664 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4665 return Res;
4666 }
4667 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004668
4669 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004670 if (CastInst *CI = dyn_cast<CastInst>(Op))
4671 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4672 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004673
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004674 if (!LI.isVolatile() && Op->hasOneUse()) {
4675 // Change select and PHI nodes to select values instead of addresses: this
4676 // helps alias analysis out a lot, allows many others simplifications, and
4677 // exposes redundancy in the code.
4678 //
4679 // Note that we cannot do the transformation unless we know that the
4680 // introduced loads cannot trap! Something like this is valid as long as
4681 // the condition is always false: load (select bool %C, int* null, int* %G),
4682 // but it would not be valid if we transformed it to load from null
4683 // unconditionally.
4684 //
4685 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4686 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004687 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4688 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004689 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004690 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004691 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004692 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004693 return new SelectInst(SI->getCondition(), V1, V2);
4694 }
4695
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004696 // load (select (cond, null, P)) -> load P
4697 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4698 if (C->isNullValue()) {
4699 LI.setOperand(0, SI->getOperand(2));
4700 return &LI;
4701 }
4702
4703 // load (select (cond, P, null)) -> load P
4704 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4705 if (C->isNullValue()) {
4706 LI.setOperand(0, SI->getOperand(1));
4707 return &LI;
4708 }
4709
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004710 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4711 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004712 bool Safe = PN->getParent() == LI.getParent();
4713
4714 // Scan all of the instructions between the PHI and the load to make
4715 // sure there are no instructions that might possibly alter the value
4716 // loaded from the PHI.
4717 if (Safe) {
4718 BasicBlock::iterator I = &LI;
4719 for (--I; !isa<PHINode>(I); --I)
4720 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4721 Safe = false;
4722 break;
4723 }
4724 }
4725
4726 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004727 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004728 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004729 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004730
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004731 if (Safe) {
4732 // Create the PHI.
4733 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4734 InsertNewInstBefore(NewPN, *PN);
4735 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4736
4737 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4738 BasicBlock *BB = PN->getIncomingBlock(i);
4739 Value *&TheLoad = LoadMap[BB];
4740 if (TheLoad == 0) {
4741 Value *InVal = PN->getIncomingValue(i);
4742 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4743 InVal->getName()+".val"),
4744 *BB->getTerminator());
4745 }
4746 NewPN->addIncoming(TheLoad, BB);
4747 }
4748 return ReplaceInstUsesWith(LI, NewPN);
4749 }
4750 }
4751 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004752 return 0;
4753}
4754
Chris Lattner9eef8a72003-06-04 04:46:00 +00004755Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4756 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004757 Value *X;
4758 BasicBlock *TrueDest;
4759 BasicBlock *FalseDest;
4760 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4761 !isa<Constant>(X)) {
4762 // Swap Destinations and condition...
4763 BI.setCondition(X);
4764 BI.setSuccessor(0, FalseDest);
4765 BI.setSuccessor(1, TrueDest);
4766 return &BI;
4767 }
4768
4769 // Cannonicalize setne -> seteq
4770 Instruction::BinaryOps Op; Value *Y;
4771 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4772 TrueDest, FalseDest)))
4773 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4774 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4775 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4776 std::string Name = I->getName(); I->setName("");
4777 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4778 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004779 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004780 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004781 BI.setSuccessor(0, FalseDest);
4782 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004783 removeFromWorkList(I);
4784 I->getParent()->getInstList().erase(I);
4785 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004786 return &BI;
4787 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004788
Chris Lattner9eef8a72003-06-04 04:46:00 +00004789 return 0;
4790}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004791
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004792Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4793 Value *Cond = SI.getCondition();
4794 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4795 if (I->getOpcode() == Instruction::Add)
4796 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4797 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4798 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004799 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004800 AddRHS));
4801 SI.setOperand(0, I->getOperand(0));
4802 WorkList.push_back(I);
4803 return &SI;
4804 }
4805 }
4806 return 0;
4807}
4808
Chris Lattnerca081252001-12-14 16:52:21 +00004809
Chris Lattner99f48c62002-09-02 04:59:56 +00004810void InstCombiner::removeFromWorkList(Instruction *I) {
4811 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4812 WorkList.end());
4813}
4814
Chris Lattner39c98bb2004-12-08 23:43:58 +00004815
4816/// TryToSinkInstruction - Try to move the specified instruction from its
4817/// current block into the beginning of DestBlock, which can only happen if it's
4818/// safe to move the instruction past all of the instructions between it and the
4819/// end of its block.
4820static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
4821 assert(I->hasOneUse() && "Invariants didn't hold!");
4822
4823 // Cannot move control-flow-involving instructions.
4824 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
4825
4826 // Do not sink alloca instructions out of the entry block.
4827 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
4828 return false;
4829
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004830 // We can only sink load instructions if there is nothing between the load and
4831 // the end of block that could change the value.
4832 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4833 if (LI->isVolatile()) return false; // Don't sink volatile loads.
4834
4835 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
4836 Scan != E; ++Scan)
4837 if (Scan->mayWriteToMemory())
4838 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004839 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00004840
4841 BasicBlock::iterator InsertPos = DestBlock->begin();
4842 while (isa<PHINode>(InsertPos)) ++InsertPos;
4843
4844 BasicBlock *SrcBlock = I->getParent();
4845 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
4846 ++NumSunkInst;
4847 return true;
4848}
4849
Chris Lattner113f4f42002-06-25 16:13:24 +00004850bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004851 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004852 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004853
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004854 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4855 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004856
Chris Lattnerca081252001-12-14 16:52:21 +00004857
4858 while (!WorkList.empty()) {
4859 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4860 WorkList.pop_back();
4861
Misha Brukman632df282002-10-29 23:06:16 +00004862 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004863 // Check to see if we can DIE the instruction...
4864 if (isInstructionTriviallyDead(I)) {
4865 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004866 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004867 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004868 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004869
4870 I->getParent()->getInstList().erase(I);
4871 removeFromWorkList(I);
4872 continue;
4873 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004874
Misha Brukman632df282002-10-29 23:06:16 +00004875 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004876 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004877 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00004878 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004879 cast<Constant>(Ptr)->isNullValue() &&
4880 !isa<ConstantPointerNull>(C) &&
4881 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00004882 // If this is a constant expr gep that is effectively computing an
4883 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4884 bool isFoldableGEP = true;
4885 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4886 if (!isa<ConstantInt>(I->getOperand(i)))
4887 isFoldableGEP = false;
4888 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004889 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00004890 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4891 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004892 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004893 C = ConstantExpr::getCast(C, I->getType());
4894 }
4895 }
4896
Chris Lattner99f48c62002-09-02 04:59:56 +00004897 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004898 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004899 ReplaceInstUsesWith(*I, C);
4900
Chris Lattner99f48c62002-09-02 04:59:56 +00004901 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004902 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004903 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004904 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004905 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004906
Chris Lattner39c98bb2004-12-08 23:43:58 +00004907 // See if we can trivially sink this instruction to a successor basic block.
4908 if (I->hasOneUse()) {
4909 BasicBlock *BB = I->getParent();
4910 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
4911 if (UserParent != BB) {
4912 bool UserIsSuccessor = false;
4913 // See if the user is one of our successors.
4914 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
4915 if (*SI == UserParent) {
4916 UserIsSuccessor = true;
4917 break;
4918 }
4919
4920 // If the user is one of our immediate successors, and if that successor
4921 // only has us as a predecessors (we'd have to split the critical edge
4922 // otherwise), we can keep going.
4923 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
4924 next(pred_begin(UserParent)) == pred_end(UserParent))
4925 // Okay, the CFG is simple enough, try to sink this instruction.
4926 Changed |= TryToSinkInstruction(I, UserParent);
4927 }
4928 }
4929
Chris Lattnerca081252001-12-14 16:52:21 +00004930 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004931 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004932 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004933 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004934 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004935 DEBUG(std::cerr << "IC: Old = " << *I
4936 << " New = " << *Result);
4937
Chris Lattner396dbfe2004-06-09 05:08:07 +00004938 // Everything uses the new instruction now.
4939 I->replaceAllUsesWith(Result);
4940
4941 // Push the new instruction and any users onto the worklist.
4942 WorkList.push_back(Result);
4943 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004944
4945 // Move the name to the new instruction first...
4946 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004947 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004948
4949 // Insert the new instruction into the basic block...
4950 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00004951 BasicBlock::iterator InsertPos = I;
4952
4953 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4954 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4955 ++InsertPos;
4956
4957 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004958
Chris Lattner63d75af2004-05-01 23:27:23 +00004959 // Make sure that we reprocess all operands now that we reduced their
4960 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004961 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4962 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4963 WorkList.push_back(OpI);
4964
Chris Lattner396dbfe2004-06-09 05:08:07 +00004965 // Instructions can end up on the worklist more than once. Make sure
4966 // we do not process an instruction that has been deleted.
4967 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004968
4969 // Erase the old instruction.
4970 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004971 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004972 DEBUG(std::cerr << "IC: MOD = " << *I);
4973
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004974 // If the instruction was modified, it's possible that it is now dead.
4975 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004976 if (isInstructionTriviallyDead(I)) {
4977 // Make sure we process all operands now that we are reducing their
4978 // use counts.
4979 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4980 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4981 WorkList.push_back(OpI);
4982
4983 // Instructions may end up in the worklist more than once. Erase all
4984 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004985 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004986 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004987 } else {
4988 WorkList.push_back(Result);
4989 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004990 }
Chris Lattner053c0932002-05-14 15:24:07 +00004991 }
Chris Lattner260ab202002-04-18 17:39:14 +00004992 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004993 }
4994 }
4995
Chris Lattner260ab202002-04-18 17:39:14 +00004996 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004997}
4998
Brian Gaeke38b79e82004-07-27 17:43:21 +00004999FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005000 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005001}
Brian Gaeke960707c2003-11-11 22:41:34 +00005002