blob: f663ae6137f3a2063e2c7180a0a0bd77a3b8ba54 [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 Lattnerbfb1d032003-07-23 21:41:57 +000032// N. This list is incomplete
33//
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 Lattner471bd762003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner51ea1272004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
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);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000116 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000117 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000118 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000123 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000124 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000125 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000126 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000127 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000128
129 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000131
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000133 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000134 bool transformConstExprCastCall(CallSite CS);
135
Chris Lattner69193f92004-04-05 01:30:19 +0000136 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
139 //
Chris Lattner623826c2004-09-28 21:48:02 +0000140 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000146 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000147 }
148
Chris Lattner7e794272004-09-24 15:21:34 +0000149 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150 /// This also adds the cast to the worklist. Finally, this returns the
151 /// cast.
152 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153 if (V->getType() == Ty) return V;
154
155 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156 WorkList.push_back(C);
157 return C;
158 }
159
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 // ReplaceInstUsesWith - This method is to be used when an instruction is
161 // found to be dead, replacable with another preexisting expression. Here
162 // we add all uses of I to the worklist, replace all uses of I with the new
163 // value, then return I, so that the inst combiner will know that I was
164 // modified.
165 //
166 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000167 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000168 if (&I != V) {
169 I.replaceAllUsesWith(V);
170 return &I;
171 } else {
172 // If we are replacing the instruction with itself, this must be in a
173 // segment of unreachable code, so just clobber the instruction.
174 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
175 return &I;
176 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000178
179 // EraseInstFromFunction - When dealing with an instruction that has side
180 // effects or produces a void value, we can't rely on DCE to delete the
181 // instruction. Instead, visit methods should return the value returned by
182 // this function.
183 Instruction *EraseInstFromFunction(Instruction &I) {
184 assert(I.use_empty() && "Cannot erase instruction that is used!");
185 AddUsesToWorkList(I);
186 removeFromWorkList(&I);
187 I.getParent()->getInstList().erase(&I);
188 return 0; // Don't do anything with FI
189 }
190
191
Chris Lattner3ac7c262003-08-13 20:16:26 +0000192 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000193 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194 /// InsertBefore instruction. This is specialized a bit to avoid inserting
195 /// casts that are known to not do anything...
196 ///
197 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198 Instruction *InsertBefore);
199
Chris Lattner7fb29e12003-03-11 00:12:48 +0000200 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000201 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000202 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000203
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000204
205 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
206 // PHI node as operand #0, see if we can fold the instruction into the PHI
207 // (which is only possible if all operands to the PHI are constants).
208 Instruction *FoldOpIntoPhi(Instruction &I);
209
Chris Lattnerba1cb382003-09-19 17:17:26 +0000210 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
211 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000212
213 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
214 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000215 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000216
Chris Lattnerc8b70922002-07-26 21:12:46 +0000217 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000218}
219
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000220// getComplexity: Assign a complexity or rank value to LLVM Values...
221// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
222static unsigned getComplexity(Value *V) {
223 if (isa<Instruction>(V)) {
224 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
225 return 2;
226 return 3;
227 }
228 if (isa<Argument>(V)) return 2;
229 return isa<Constant>(V) ? 0 : 1;
230}
Chris Lattner260ab202002-04-18 17:39:14 +0000231
Chris Lattner7fb29e12003-03-11 00:12:48 +0000232// isOnlyUse - Return true if this instruction will be deleted if we stop using
233// it.
234static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000235 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000236}
237
Chris Lattnere79e8542004-02-23 06:38:22 +0000238// getPromotedType - Return the specified type promoted as it would be to pass
239// though a va_arg area...
240static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000241 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000242 case Type::SByteTyID:
243 case Type::ShortTyID: return Type::IntTy;
244 case Type::UByteTyID:
245 case Type::UShortTyID: return Type::UIntTy;
246 case Type::FloatTyID: return Type::DoubleTy;
247 default: return Ty;
248 }
249}
250
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000251// SimplifyCommutative - This performs a few simplifications for commutative
252// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000253//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000254// 1. Order operands such that they are listed from right (least complex) to
255// left (most complex). This puts constants before unary operators before
256// binary operators.
257//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000258// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
259// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000260//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000261bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000262 bool Changed = false;
263 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
264 Changed = !I.swapOperands();
265
266 if (!I.isAssociative()) return Changed;
267 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000268 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
269 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
270 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000271 Constant *Folded = ConstantExpr::get(I.getOpcode(),
272 cast<Constant>(I.getOperand(1)),
273 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000274 I.setOperand(0, Op->getOperand(0));
275 I.setOperand(1, Folded);
276 return true;
277 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
278 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
279 isOnlyUse(Op) && isOnlyUse(Op1)) {
280 Constant *C1 = cast<Constant>(Op->getOperand(1));
281 Constant *C2 = cast<Constant>(Op1->getOperand(1));
282
283 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000284 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000285 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
286 Op1->getOperand(0),
287 Op1->getName(), &I);
288 WorkList.push_back(New);
289 I.setOperand(0, New);
290 I.setOperand(1, Folded);
291 return true;
292 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000293 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000294 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000295}
Chris Lattnerca081252001-12-14 16:52:21 +0000296
Chris Lattnerbb74e222003-03-10 23:06:50 +0000297// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
298// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000299//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000300static inline Value *dyn_castNegVal(Value *V) {
301 if (BinaryOperator::isNeg(V))
302 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
303
Chris Lattner9244df62003-04-30 22:19:10 +0000304 // Constants can be considered to be negated values if they can be folded...
305 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000306 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000307 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000308}
309
Chris Lattnerbb74e222003-03-10 23:06:50 +0000310static inline Value *dyn_castNotVal(Value *V) {
311 if (BinaryOperator::isNot(V))
312 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
313
314 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000315 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000316 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000317 return 0;
318}
319
Chris Lattner7fb29e12003-03-11 00:12:48 +0000320// dyn_castFoldableMul - If this value is a multiply that can be folded into
321// other computations (because it has a constant operand), return the
322// non-constant operand of the multiply.
323//
324static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000325 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000326 if (Instruction *I = dyn_cast<Instruction>(V))
327 if (I->getOpcode() == Instruction::Mul)
328 if (isa<Constant>(I->getOperand(1)))
329 return I->getOperand(0);
330 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000331}
Chris Lattner31ae8632002-08-14 17:51:49 +0000332
Chris Lattner3082c5a2003-02-18 19:28:33 +0000333// Log2 - Calculate the log base 2 for the specified value if it is exactly a
334// power of 2.
335static unsigned Log2(uint64_t Val) {
336 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
337 unsigned Count = 0;
338 while (Val != 1) {
339 if (Val & 1) return 0; // Multiple bits set?
340 Val >>= 1;
341 ++Count;
342 }
343 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000344}
345
Chris Lattner623826c2004-09-28 21:48:02 +0000346// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000347static ConstantInt *AddOne(ConstantInt *C) {
348 return cast<ConstantInt>(ConstantExpr::getAdd(C,
349 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000350}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000351static ConstantInt *SubOne(ConstantInt *C) {
352 return cast<ConstantInt>(ConstantExpr::getSub(C,
353 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000354}
355
356// isTrueWhenEqual - Return true if the specified setcondinst instruction is
357// true when both operands are equal...
358//
359static bool isTrueWhenEqual(Instruction &I) {
360 return I.getOpcode() == Instruction::SetEQ ||
361 I.getOpcode() == Instruction::SetGE ||
362 I.getOpcode() == Instruction::SetLE;
363}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000364
365/// AssociativeOpt - Perform an optimization on an associative operator. This
366/// function is designed to check a chain of associative operators for a
367/// potential to apply a certain optimization. Since the optimization may be
368/// applicable if the expression was reassociated, this checks the chain, then
369/// reassociates the expression as necessary to expose the optimization
370/// opportunity. This makes use of a special Functor, which must define
371/// 'shouldApply' and 'apply' methods.
372///
373template<typename Functor>
374Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
375 unsigned Opcode = Root.getOpcode();
376 Value *LHS = Root.getOperand(0);
377
378 // Quick check, see if the immediate LHS matches...
379 if (F.shouldApply(LHS))
380 return F.apply(Root);
381
382 // Otherwise, if the LHS is not of the same opcode as the root, return.
383 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000384 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000385 // Should we apply this transform to the RHS?
386 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
387
388 // If not to the RHS, check to see if we should apply to the LHS...
389 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
390 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
391 ShouldApply = true;
392 }
393
394 // If the functor wants to apply the optimization to the RHS of LHSI,
395 // reassociate the expression from ((? op A) op B) to (? op (A op B))
396 if (ShouldApply) {
397 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000398
399 // Now all of the instructions are in the current basic block, go ahead
400 // and perform the reassociation.
401 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
402
403 // First move the selected RHS to the LHS of the root...
404 Root.setOperand(0, LHSI->getOperand(1));
405
406 // Make what used to be the LHS of the root be the user of the root...
407 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000408 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000409 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
410 return 0;
411 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000412 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000413 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000414 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
415 BasicBlock::iterator ARI = &Root; ++ARI;
416 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
417 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000418
419 // Now propagate the ExtraOperand down the chain of instructions until we
420 // get to LHSI.
421 while (TmpLHSI != LHSI) {
422 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000423 // Move the instruction to immediately before the chain we are
424 // constructing to avoid breaking dominance properties.
425 NextLHSI->getParent()->getInstList().remove(NextLHSI);
426 BB->getInstList().insert(ARI, NextLHSI);
427 ARI = NextLHSI;
428
Chris Lattnerb8b97502003-08-13 19:01:45 +0000429 Value *NextOp = NextLHSI->getOperand(1);
430 NextLHSI->setOperand(1, ExtraOperand);
431 TmpLHSI = NextLHSI;
432 ExtraOperand = NextOp;
433 }
434
435 // Now that the instructions are reassociated, have the functor perform
436 // the transformation...
437 return F.apply(Root);
438 }
439
440 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
441 }
442 return 0;
443}
444
445
446// AddRHS - Implements: X + X --> X << 1
447struct AddRHS {
448 Value *RHS;
449 AddRHS(Value *rhs) : RHS(rhs) {}
450 bool shouldApply(Value *LHS) const { return LHS == RHS; }
451 Instruction *apply(BinaryOperator &Add) const {
452 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
453 ConstantInt::get(Type::UByteTy, 1));
454 }
455};
456
457// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
458// iff C1&C2 == 0
459struct AddMaskingAnd {
460 Constant *C2;
461 AddMaskingAnd(Constant *c) : C2(c) {}
462 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000463 ConstantInt *C1;
464 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
465 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000466 }
467 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000468 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000469 }
470};
471
Chris Lattner183b3362004-04-09 19:05:30 +0000472static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
473 InstCombiner *IC) {
474 // Figure out if the constant is the left or the right argument.
475 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
476 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000477
Chris Lattner183b3362004-04-09 19:05:30 +0000478 if (Constant *SOC = dyn_cast<Constant>(SO)) {
479 if (ConstIsRHS)
480 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
481 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
482 }
483
484 Value *Op0 = SO, *Op1 = ConstOperand;
485 if (!ConstIsRHS)
486 std::swap(Op0, Op1);
487 Instruction *New;
488 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
489 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
490 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
491 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000492 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000493 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000494 abort();
495 }
Chris Lattner183b3362004-04-09 19:05:30 +0000496 return IC->InsertNewInstBefore(New, BI);
497}
498
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000499
500/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
501/// node as operand #0, see if we can fold the instruction into the PHI (which
502/// is only possible if all operands to the PHI are constants).
503Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
504 PHINode *PN = cast<PHINode>(I.getOperand(0));
505 if (!PN->hasOneUse()) return 0;
506
507 // Check to see if all of the operands of the PHI are constants. If not, we
508 // cannot do the transformation.
509 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
510 if (!isa<Constant>(PN->getIncomingValue(i)))
511 return 0;
512
513 // Okay, we can do the transformation: create the new PHI node.
514 PHINode *NewPN = new PHINode(I.getType(), I.getName());
515 I.setName("");
516 NewPN->op_reserve(PN->getNumOperands());
517 InsertNewInstBefore(NewPN, *PN);
518
519 // Next, add all of the operands to the PHI.
520 if (I.getNumOperands() == 2) {
521 Constant *C = cast<Constant>(I.getOperand(1));
522 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
523 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
524 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
525 PN->getIncomingBlock(i));
526 }
527 } else {
528 assert(isa<CastInst>(I) && "Unary op should be a cast!");
529 const Type *RetTy = I.getType();
530 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
531 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
532 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
533 PN->getIncomingBlock(i));
534 }
535 }
536 return ReplaceInstUsesWith(I, NewPN);
537}
538
Chris Lattner183b3362004-04-09 19:05:30 +0000539// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
540// constant as the other operand, try to fold the binary operator into the
541// select arguments.
542static Instruction *FoldBinOpIntoSelect(Instruction &BI, 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(BI, TV, IC);
551 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
552
553 return new SelectInst(SI->getCondition(), SelectTrueVal,
554 SelectFalseVal);
555 }
556 return 0;
557}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000558
Chris Lattner113f4f42002-06-25 16:13:24 +0000559Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000560 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000561 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000562
Chris Lattnercf4a9962004-04-10 22:01:55 +0000563 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
564 // X + 0 --> X
565 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
566 RHSC->isNullValue())
567 return ReplaceInstUsesWith(I, LHS);
568
569 // X + (signbit) --> X ^ signbit
570 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
571 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
572 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
573 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000574 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000575 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000576
577 if (isa<PHINode>(LHS))
578 if (Instruction *NV = FoldOpIntoPhi(I))
579 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000580 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000581
Chris Lattnerb8b97502003-08-13 19:01:45 +0000582 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000583 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000584 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000585 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000586
Chris Lattner147e9752002-05-08 22:46:53 +0000587 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000588 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000589 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000590
591 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000592 if (!isa<Constant>(RHS))
593 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000594 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000595
Chris Lattner57c8d992003-02-18 19:57:07 +0000596 // X*C + X --> X * (C+1)
597 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000598 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000599 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000600 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
601 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000602 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000603 }
604
605 // X + X*C --> X * (C+1)
606 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000607 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000608 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000609 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
610 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000611 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000612 }
613
Chris Lattnerb8b97502003-08-13 19:01:45 +0000614 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000615 ConstantInt *C2;
616 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000617 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000618
Chris Lattnerb9cde762003-10-02 15:11:26 +0000619 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000620 Value *X;
621 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
622 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
623 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000624 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000625
Chris Lattnerbff91d92004-10-08 05:07:56 +0000626 // (X & FF00) + xx00 -> (X+xx00) & FF00
627 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
628 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
629 if (Anded == CRHS) {
630 // See if all bits from the first bit set in the Add RHS up are included
631 // in the mask. First, get the rightmost bit.
632 uint64_t AddRHSV = CRHS->getRawValue();
633
634 // Form a mask of all bits from the lowest bit added through the top.
635 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
636 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
637
638 // See if the and mask includes all of these bits.
639 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
640
641 if (AddRHSHighBits == AddRHSHighBitsAnd) {
642 // Okay, the xform is safe. Insert the new add pronto.
643 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
644 LHS->getName()), I);
645 return BinaryOperator::createAnd(NewAdd, C2);
646 }
647 }
648 }
649
650
Chris Lattnerd4252a72004-07-30 07:50:03 +0000651 // Try to fold constant add into select arguments.
652 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
653 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
654 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000655 }
656
Chris Lattner113f4f42002-06-25 16:13:24 +0000657 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000658}
659
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000660// isSignBit - Return true if the value represented by the constant only has the
661// highest order bit set.
662static bool isSignBit(ConstantInt *CI) {
663 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
664 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
665}
666
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000667static unsigned getTypeSizeInBits(const Type *Ty) {
668 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
669}
670
Chris Lattner022167f2004-03-13 00:11:49 +0000671/// RemoveNoopCast - Strip off nonconverting casts from the value.
672///
673static Value *RemoveNoopCast(Value *V) {
674 if (CastInst *CI = dyn_cast<CastInst>(V)) {
675 const Type *CTy = CI->getType();
676 const Type *OpTy = CI->getOperand(0)->getType();
677 if (CTy->isInteger() && OpTy->isInteger()) {
678 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
679 return RemoveNoopCast(CI->getOperand(0));
680 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
681 return RemoveNoopCast(CI->getOperand(0));
682 }
683 return V;
684}
685
Chris Lattner113f4f42002-06-25 16:13:24 +0000686Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000687 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000688
Chris Lattnere6794492002-08-12 21:17:25 +0000689 if (Op0 == Op1) // sub X, X -> 0
690 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000691
Chris Lattnere6794492002-08-12 21:17:25 +0000692 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000693 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000694 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000695
Chris Lattner8f2f5982003-11-05 01:06:05 +0000696 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
697 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000698 if (C->isAllOnesValue())
699 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000700
Chris Lattner8f2f5982003-11-05 01:06:05 +0000701 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000702 Value *X;
703 if (match(Op1, m_Not(m_Value(X))))
704 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000705 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000706 // -((uint)X >> 31) -> ((int)X >> 31)
707 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000708 if (C->isNullValue()) {
709 Value *NoopCastedRHS = RemoveNoopCast(Op1);
710 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000711 if (SI->getOpcode() == Instruction::Shr)
712 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
713 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000714 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000715 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000716 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000717 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000718 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000719 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000720 // Ok, the transformation is safe. Insert a cast of the incoming
721 // value, then the new shift, then the new cast.
722 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
723 SI->getOperand(0)->getName());
724 Value *InV = InsertNewInstBefore(FirstCast, I);
725 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
726 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000727 if (NewShift->getType() == I.getType())
728 return NewShift;
729 else {
730 InV = InsertNewInstBefore(NewShift, I);
731 return new CastInst(NewShift, I.getType());
732 }
Chris Lattner92295c52004-03-12 23:53:13 +0000733 }
734 }
Chris Lattner022167f2004-03-13 00:11:49 +0000735 }
Chris Lattner183b3362004-04-09 19:05:30 +0000736
737 // Try to fold constant sub into select arguments.
738 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
739 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
740 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000741
742 if (isa<PHINode>(Op0))
743 if (Instruction *NV = FoldOpIntoPhi(I))
744 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000745 }
746
Chris Lattner3082c5a2003-02-18 19:28:33 +0000747 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000748 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000749 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
750 // is not used by anyone else...
751 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000752 if (Op1I->getOpcode() == Instruction::Sub &&
753 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000754 // Swap the two operands of the subexpr...
755 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
756 Op1I->setOperand(0, IIOp1);
757 Op1I->setOperand(1, IIOp0);
758
759 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000760 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000761 }
762
763 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
764 //
765 if (Op1I->getOpcode() == Instruction::And &&
766 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
767 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
768
Chris Lattner396dbfe2004-06-09 05:08:07 +0000769 Value *NewNot =
770 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000771 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000772 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000773
Chris Lattner0aee4b72004-10-06 15:08:25 +0000774 // -(X sdiv C) -> (X sdiv -C)
775 if (Op1I->getOpcode() == Instruction::Div)
776 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
777 if (CSI->getValue() == 0)
778 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
779 return BinaryOperator::createDiv(Op1I->getOperand(0),
780 ConstantExpr::getNeg(DivRHS));
781
Chris Lattner57c8d992003-02-18 19:57:07 +0000782 // X - X*C --> X * (1-C)
783 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000784 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000785 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000786 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000787 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000788 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000789 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000790 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000791
Chris Lattner57c8d992003-02-18 19:57:07 +0000792 // X*C - X --> X * (C-1)
793 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000794 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000795 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000796 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000797 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000798 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000799 }
800
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000801 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000802}
803
Chris Lattnere79e8542004-02-23 06:38:22 +0000804/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
805/// really just returns true if the most significant (sign) bit is set.
806static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
807 if (RHS->getType()->isSigned()) {
808 // True if source is LHS < 0 or LHS <= -1
809 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
810 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
811 } else {
812 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
813 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
814 // the size of the integer type.
815 if (Opcode == Instruction::SetGE)
816 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
817 if (Opcode == Instruction::SetGT)
818 return RHSC->getValue() ==
819 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
820 }
821 return false;
822}
823
Chris Lattner113f4f42002-06-25 16:13:24 +0000824Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000825 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000826 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000827
Chris Lattnere6794492002-08-12 21:17:25 +0000828 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000829 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
830 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000831
832 // ((X << C1)*C2) == (X * (C2 << C1))
833 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
834 if (SI->getOpcode() == Instruction::Shl)
835 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000836 return BinaryOperator::createMul(SI->getOperand(0),
837 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000838
Chris Lattnercce81be2003-09-11 22:24:54 +0000839 if (CI->isNullValue())
840 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
841 if (CI->equalsInt(1)) // X * 1 == X
842 return ReplaceInstUsesWith(I, Op0);
843 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000844 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000845
Chris Lattnercce81be2003-09-11 22:24:54 +0000846 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000847 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
848 return new ShiftInst(Instruction::Shl, Op0,
849 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000850 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000851 if (Op1F->isNullValue())
852 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000853
Chris Lattner3082c5a2003-02-18 19:28:33 +0000854 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
855 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
856 if (Op1F->getValue() == 1.0)
857 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
858 }
Chris Lattner183b3362004-04-09 19:05:30 +0000859
860 // Try to fold constant mul into select arguments.
861 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
862 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
863 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000864
865 if (isa<PHINode>(Op0))
866 if (Instruction *NV = FoldOpIntoPhi(I))
867 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000868 }
869
Chris Lattner934a64cf2003-03-10 23:23:04 +0000870 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
871 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000872 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000873
Chris Lattner2635b522004-02-23 05:39:21 +0000874 // If one of the operands of the multiply is a cast from a boolean value, then
875 // we know the bool is either zero or one, so this is a 'masking' multiply.
876 // See if we can simplify things based on how the boolean was originally
877 // formed.
878 CastInst *BoolCast = 0;
879 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
880 if (CI->getOperand(0)->getType() == Type::BoolTy)
881 BoolCast = CI;
882 if (!BoolCast)
883 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
884 if (CI->getOperand(0)->getType() == Type::BoolTy)
885 BoolCast = CI;
886 if (BoolCast) {
887 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
888 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
889 const Type *SCOpTy = SCIOp0->getType();
890
Chris Lattnere79e8542004-02-23 06:38:22 +0000891 // If the setcc is true iff the sign bit of X is set, then convert this
892 // multiply into a shift/and combination.
893 if (isa<ConstantInt>(SCIOp1) &&
894 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000895 // Shift the X value right to turn it into "all signbits".
896 Constant *Amt = ConstantUInt::get(Type::UByteTy,
897 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000898 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000899 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000900 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
901 SCIOp0->getName()), I);
902 }
903
904 Value *V =
905 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
906 BoolCast->getOperand(0)->getName()+
907 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000908
909 // If the multiply type is not the same as the source type, sign extend
910 // or truncate to the multiply type.
911 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000912 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000913
914 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000915 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000916 }
917 }
918 }
919
Chris Lattner113f4f42002-06-25 16:13:24 +0000920 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000921}
922
Chris Lattner113f4f42002-06-25 16:13:24 +0000923Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000924 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000925 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000926 if (RHS->equalsInt(1))
927 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000928
Chris Lattnere20c3342004-04-26 14:01:59 +0000929 // div X, -1 == -X
930 if (RHS->isAllOnesValue())
931 return BinaryOperator::createNeg(I.getOperand(0));
932
Chris Lattner272d5ca2004-09-28 18:22:15 +0000933 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
934 if (LHS->getOpcode() == Instruction::Div)
935 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000936 // (X / C1) / C2 -> X / (C1*C2)
937 return BinaryOperator::createDiv(LHS->getOperand(0),
938 ConstantExpr::getMul(RHS, LHSRHS));
939 }
940
Chris Lattner3082c5a2003-02-18 19:28:33 +0000941 // Check to see if this is an unsigned division with an exact power of 2,
942 // if so, convert to a right shift.
943 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
944 if (uint64_t Val = C->getValue()) // Don't break X / 0
945 if (uint64_t C = Log2(Val))
946 return new ShiftInst(Instruction::Shr, I.getOperand(0),
947 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000948
Chris Lattner4ad08352004-10-09 02:50:40 +0000949 // -X/C -> X/-C
950 if (RHS->getType()->isSigned())
951 if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
952 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
953
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000954 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
955 if (Instruction *NV = FoldOpIntoPhi(I))
956 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000957 }
958
959 // 0 / X == 0, we don't need to preserve faults!
960 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
961 if (LHS->equalsInt(0))
962 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
963
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000964 return 0;
965}
966
967
Chris Lattner113f4f42002-06-25 16:13:24 +0000968Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000969 if (I.getType()->isSigned())
970 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000971 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000972 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000973 // X % -Y -> X % Y
974 AddUsesToWorkList(I);
975 I.setOperand(1, RHSNeg);
976 return &I;
977 }
978
Chris Lattner3082c5a2003-02-18 19:28:33 +0000979 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
980 if (RHS->equalsInt(1)) // X % 1 == 0
981 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
982
983 // Check to see if this is an unsigned remainder with an exact power of 2,
984 // if so, convert to a bitwise and.
985 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
986 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000987 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000988 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000989 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000990 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
991 if (Instruction *NV = FoldOpIntoPhi(I))
992 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000993 }
994
995 // 0 % X == 0, we don't need to preserve faults!
996 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
997 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000998 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
999
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001000 return 0;
1001}
1002
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001003// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001004static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001005 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1006 // Calculate -1 casted to the right type...
1007 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1008 uint64_t Val = ~0ULL; // All ones
1009 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1010 return CU->getValue() == Val-1;
1011 }
1012
1013 const ConstantSInt *CS = cast<ConstantSInt>(C);
1014
1015 // Calculate 0111111111..11111
1016 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1017 int64_t Val = INT64_MAX; // All ones
1018 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1019 return CS->getValue() == Val-1;
1020}
1021
1022// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001023static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001024 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1025 return CU->getValue() == 1;
1026
1027 const ConstantSInt *CS = cast<ConstantSInt>(C);
1028
1029 // Calculate 1111111111000000000000
1030 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1031 int64_t Val = -1; // All ones
1032 Val <<= TypeBits-1; // Shift over to the right spot
1033 return CS->getValue() == Val+1;
1034}
1035
Chris Lattner35167c32004-06-09 07:59:58 +00001036// isOneBitSet - Return true if there is exactly one bit set in the specified
1037// constant.
1038static bool isOneBitSet(const ConstantInt *CI) {
1039 uint64_t V = CI->getRawValue();
1040 return V && (V & (V-1)) == 0;
1041}
1042
Chris Lattner8fc5af42004-09-23 21:46:38 +00001043#if 0 // Currently unused
1044// isLowOnes - Return true if the constant is of the form 0+1+.
1045static bool isLowOnes(const ConstantInt *CI) {
1046 uint64_t V = CI->getRawValue();
1047
1048 // There won't be bits set in parts that the type doesn't contain.
1049 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1050
1051 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1052 return U && V && (U & V) == 0;
1053}
1054#endif
1055
1056// isHighOnes - Return true if the constant is of the form 1+0+.
1057// This is the same as lowones(~X).
1058static bool isHighOnes(const ConstantInt *CI) {
1059 uint64_t V = ~CI->getRawValue();
1060
1061 // There won't be bits set in parts that the type doesn't contain.
1062 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1063
1064 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1065 return U && V && (U & V) == 0;
1066}
1067
1068
Chris Lattner3ac7c262003-08-13 20:16:26 +00001069/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1070/// are carefully arranged to allow folding of expressions such as:
1071///
1072/// (A < B) | (A > B) --> (A != B)
1073///
1074/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1075/// represents that the comparison is true if A == B, and bit value '1' is true
1076/// if A < B.
1077///
1078static unsigned getSetCondCode(const SetCondInst *SCI) {
1079 switch (SCI->getOpcode()) {
1080 // False -> 0
1081 case Instruction::SetGT: return 1;
1082 case Instruction::SetEQ: return 2;
1083 case Instruction::SetGE: return 3;
1084 case Instruction::SetLT: return 4;
1085 case Instruction::SetNE: return 5;
1086 case Instruction::SetLE: return 6;
1087 // True -> 7
1088 default:
1089 assert(0 && "Invalid SetCC opcode!");
1090 return 0;
1091 }
1092}
1093
1094/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1095/// opcode and two operands into either a constant true or false, or a brand new
1096/// SetCC instruction.
1097static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1098 switch (Opcode) {
1099 case 0: return ConstantBool::False;
1100 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1101 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1102 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1103 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1104 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1105 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1106 case 7: return ConstantBool::True;
1107 default: assert(0 && "Illegal SetCCCode!"); return 0;
1108 }
1109}
1110
1111// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1112struct FoldSetCCLogical {
1113 InstCombiner &IC;
1114 Value *LHS, *RHS;
1115 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1116 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1117 bool shouldApply(Value *V) const {
1118 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1119 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1120 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1121 return false;
1122 }
1123 Instruction *apply(BinaryOperator &Log) const {
1124 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1125 if (SCI->getOperand(0) != LHS) {
1126 assert(SCI->getOperand(1) == LHS);
1127 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1128 }
1129
1130 unsigned LHSCode = getSetCondCode(SCI);
1131 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1132 unsigned Code;
1133 switch (Log.getOpcode()) {
1134 case Instruction::And: Code = LHSCode & RHSCode; break;
1135 case Instruction::Or: Code = LHSCode | RHSCode; break;
1136 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001137 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001138 }
1139
1140 Value *RV = getSetCCValue(Code, LHS, RHS);
1141 if (Instruction *I = dyn_cast<Instruction>(RV))
1142 return I;
1143 // Otherwise, it's a constant boolean value...
1144 return IC.ReplaceInstUsesWith(Log, RV);
1145 }
1146};
1147
1148
Chris Lattnerba1cb382003-09-19 17:17:26 +00001149// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1150// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1151// guaranteed to be either a shift instruction or a binary operator.
1152Instruction *InstCombiner::OptAndOp(Instruction *Op,
1153 ConstantIntegral *OpRHS,
1154 ConstantIntegral *AndRHS,
1155 BinaryOperator &TheAnd) {
1156 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001157 Constant *Together = 0;
1158 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001159 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001160
Chris Lattnerba1cb382003-09-19 17:17:26 +00001161 switch (Op->getOpcode()) {
1162 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001163 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001164 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001165 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001166 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001167 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1168 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001169 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001170 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001171 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001172 }
1173 break;
1174 case Instruction::Or:
1175 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001176 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001177 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001178 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001179 if (Together == AndRHS) // (X | C) & C --> C
1180 return ReplaceInstUsesWith(TheAnd, AndRHS);
1181
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001182 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001183 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1184 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001185 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001186 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001187 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001188 }
1189 }
1190 break;
1191 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001192 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001193 // Adding a one to a single bit bit-field should be turned into an XOR
1194 // of the bit. First thing to check is to see if this AND is with a
1195 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001196 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001197
1198 // Clear bits that are not part of the constant.
1199 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1200
1201 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001202 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001203 // Ok, at this point, we know that we are masking the result of the
1204 // ADD down to exactly one bit. If the constant we are adding has
1205 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001206 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001207
1208 // Check to see if any bits below the one bit set in AndRHSV are set.
1209 if ((AddRHS & (AndRHSV-1)) == 0) {
1210 // If not, the only thing that can effect the output of the AND is
1211 // the bit specified by AndRHSV. If that bit is set, the effect of
1212 // the XOR is to toggle the bit. If it is clear, then the ADD has
1213 // no effect.
1214 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1215 TheAnd.setOperand(0, X);
1216 return &TheAnd;
1217 } else {
1218 std::string Name = Op->getName(); Op->setName("");
1219 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001220 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001221 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001222 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001223 }
1224 }
1225 }
1226 }
1227 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001228
1229 case Instruction::Shl: {
1230 // We know that the AND will not produce any of the bits shifted in, so if
1231 // the anded constant includes them, clear them now!
1232 //
1233 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001234 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1235 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1236
1237 if (CI == ShlMask) { // Masking out bits that the shift already masks
1238 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1239 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001240 TheAnd.setOperand(1, CI);
1241 return &TheAnd;
1242 }
1243 break;
1244 }
1245 case Instruction::Shr:
1246 // We know that the AND will not produce any of the bits shifted in, so if
1247 // the anded constant includes them, clear them now! This only applies to
1248 // unsigned shifts, because a signed shr may bring in set bits!
1249 //
1250 if (AndRHS->getType()->isUnsigned()) {
1251 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001252 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1253 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1254
1255 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1256 return ReplaceInstUsesWith(TheAnd, Op);
1257 } else if (CI != AndRHS) {
1258 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001259 return &TheAnd;
1260 }
Chris Lattner7e794272004-09-24 15:21:34 +00001261 } else { // Signed shr.
1262 // See if this is shifting in some sign extension, then masking it out
1263 // with an and.
1264 if (Op->hasOneUse()) {
1265 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1266 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1267 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1268 if (CI == ShrMask) { // Masking out bits shifted in.
1269 // Make the argument unsigned.
1270 Value *ShVal = Op->getOperand(0);
1271 ShVal = InsertCastBefore(ShVal,
1272 ShVal->getType()->getUnsignedVersion(),
1273 TheAnd);
1274 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1275 OpRHS, Op->getName()),
1276 TheAnd);
1277 return new CastInst(ShVal, Op->getType());
1278 }
1279 }
Chris Lattner2da29172003-09-19 19:05:02 +00001280 }
1281 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001282 }
1283 return 0;
1284}
1285
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001286
Chris Lattner6862fbd2004-09-29 17:40:11 +00001287/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1288/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1289/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1290/// insert new instructions.
1291Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1292 bool Inside, Instruction &IB) {
1293 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1294 "Lo is not <= Hi in range emission code!");
1295 if (Inside) {
1296 if (Lo == Hi) // Trivially false.
1297 return new SetCondInst(Instruction::SetNE, V, V);
1298 if (cast<ConstantIntegral>(Lo)->isMinValue())
1299 return new SetCondInst(Instruction::SetLT, V, Hi);
1300
1301 Constant *AddCST = ConstantExpr::getNeg(Lo);
1302 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1303 InsertNewInstBefore(Add, IB);
1304 // Convert to unsigned for the comparison.
1305 const Type *UnsType = Add->getType()->getUnsignedVersion();
1306 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1307 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1308 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1309 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1310 }
1311
1312 if (Lo == Hi) // Trivially true.
1313 return new SetCondInst(Instruction::SetEQ, V, V);
1314
1315 Hi = SubOne(cast<ConstantInt>(Hi));
1316 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1317 return new SetCondInst(Instruction::SetGT, V, Hi);
1318
1319 // Emit X-Lo > Hi-Lo-1
1320 Constant *AddCST = ConstantExpr::getNeg(Lo);
1321 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1322 InsertNewInstBefore(Add, IB);
1323 // Convert to unsigned for the comparison.
1324 const Type *UnsType = Add->getType()->getUnsignedVersion();
1325 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1326 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1327 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1328 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1329}
1330
1331
Chris Lattner113f4f42002-06-25 16:13:24 +00001332Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001333 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001334 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001335
1336 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001337 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1338 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001339
1340 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001341 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001342 if (RHS->isAllOnesValue())
1343 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001344
Chris Lattnerba1cb382003-09-19 17:17:26 +00001345 // Optimize a variety of ((val OP C1) & C2) combinations...
1346 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1347 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001348 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001349 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001350 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1351 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001352 }
Chris Lattner183b3362004-04-09 19:05:30 +00001353
1354 // Try to fold constant and into select arguments.
1355 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1356 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1357 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001358 if (isa<PHINode>(Op0))
1359 if (Instruction *NV = FoldOpIntoPhi(I))
1360 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001361 }
1362
Chris Lattnerbb74e222003-03-10 23:06:50 +00001363 Value *Op0NotVal = dyn_castNotVal(Op0);
1364 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001365
Chris Lattner023a4832004-06-18 06:07:51 +00001366 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1367 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1368
Misha Brukman9c003d82004-07-30 12:50:08 +00001369 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001370 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001371 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1372 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001373 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001374 return BinaryOperator::createNot(Or);
1375 }
1376
Chris Lattner623826c2004-09-28 21:48:02 +00001377 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1378 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001379 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1380 return R;
1381
Chris Lattner623826c2004-09-28 21:48:02 +00001382 Value *LHSVal, *RHSVal;
1383 ConstantInt *LHSCst, *RHSCst;
1384 Instruction::BinaryOps LHSCC, RHSCC;
1385 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1386 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1387 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1388 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1389 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1390 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1391 // Ensure that the larger constant is on the RHS.
1392 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1393 SetCondInst *LHS = cast<SetCondInst>(Op0);
1394 if (cast<ConstantBool>(Cmp)->getValue()) {
1395 std::swap(LHS, RHS);
1396 std::swap(LHSCst, RHSCst);
1397 std::swap(LHSCC, RHSCC);
1398 }
1399
1400 // At this point, we know we have have two setcc instructions
1401 // comparing a value against two constants and and'ing the result
1402 // together. Because of the above check, we know that we only have
1403 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1404 // FoldSetCCLogical check above), that the two constants are not
1405 // equal.
1406 assert(LHSCst != RHSCst && "Compares not folded above?");
1407
1408 switch (LHSCC) {
1409 default: assert(0 && "Unknown integer condition code!");
1410 case Instruction::SetEQ:
1411 switch (RHSCC) {
1412 default: assert(0 && "Unknown integer condition code!");
1413 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1414 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1415 return ReplaceInstUsesWith(I, ConstantBool::False);
1416 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1417 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1418 return ReplaceInstUsesWith(I, LHS);
1419 }
1420 case Instruction::SetNE:
1421 switch (RHSCC) {
1422 default: assert(0 && "Unknown integer condition code!");
1423 case Instruction::SetLT:
1424 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1425 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1426 break; // (X != 13 & X < 15) -> no change
1427 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1428 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1429 return ReplaceInstUsesWith(I, RHS);
1430 case Instruction::SetNE:
1431 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1432 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1433 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1434 LHSVal->getName()+".off");
1435 InsertNewInstBefore(Add, I);
1436 const Type *UnsType = Add->getType()->getUnsignedVersion();
1437 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1438 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1439 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1440 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1441 }
1442 break; // (X != 13 & X != 15) -> no change
1443 }
1444 break;
1445 case Instruction::SetLT:
1446 switch (RHSCC) {
1447 default: assert(0 && "Unknown integer condition code!");
1448 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1449 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1450 return ReplaceInstUsesWith(I, ConstantBool::False);
1451 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1452 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1453 return ReplaceInstUsesWith(I, LHS);
1454 }
1455 case Instruction::SetGT:
1456 switch (RHSCC) {
1457 default: assert(0 && "Unknown integer condition code!");
1458 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1459 return ReplaceInstUsesWith(I, LHS);
1460 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1461 return ReplaceInstUsesWith(I, RHS);
1462 case Instruction::SetNE:
1463 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1464 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1465 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001466 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1467 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001468 }
1469 }
1470 }
1471 }
1472
Chris Lattner113f4f42002-06-25 16:13:24 +00001473 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001474}
1475
Chris Lattner113f4f42002-06-25 16:13:24 +00001476Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001477 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001478 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001479
1480 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001481 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1482 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001483
1484 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001485 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001486 if (RHS->isAllOnesValue())
1487 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001488
Chris Lattnerd4252a72004-07-30 07:50:03 +00001489 ConstantInt *C1; Value *X;
1490 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1491 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1492 std::string Op0Name = Op0->getName(); Op0->setName("");
1493 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1494 InsertNewInstBefore(Or, I);
1495 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1496 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001497
Chris Lattnerd4252a72004-07-30 07:50:03 +00001498 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1499 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1500 std::string Op0Name = Op0->getName(); Op0->setName("");
1501 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1502 InsertNewInstBefore(Or, I);
1503 return BinaryOperator::createXor(Or,
1504 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001505 }
Chris Lattner183b3362004-04-09 19:05:30 +00001506
1507 // Try to fold constant and into select arguments.
1508 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1509 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1510 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001511 if (isa<PHINode>(Op0))
1512 if (Instruction *NV = FoldOpIntoPhi(I))
1513 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001514 }
1515
Chris Lattner812aab72003-08-12 19:11:07 +00001516 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001517 Value *A, *B; ConstantInt *C1, *C2;
1518 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1519 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1520 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001521
Chris Lattnerd4252a72004-07-30 07:50:03 +00001522 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1523 if (A == Op1) // ~A | A == -1
1524 return ReplaceInstUsesWith(I,
1525 ConstantIntegral::getAllOnesValue(I.getType()));
1526 } else {
1527 A = 0;
1528 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001529
Chris Lattnerd4252a72004-07-30 07:50:03 +00001530 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1531 if (Op0 == B)
1532 return ReplaceInstUsesWith(I,
1533 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001534
Misha Brukman9c003d82004-07-30 12:50:08 +00001535 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001536 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1537 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1538 I.getName()+".demorgan"), I);
1539 return BinaryOperator::createNot(And);
1540 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001541 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001542
Chris Lattner3ac7c262003-08-13 20:16:26 +00001543 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001544 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001545 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1546 return R;
1547
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001548 Value *LHSVal, *RHSVal;
1549 ConstantInt *LHSCst, *RHSCst;
1550 Instruction::BinaryOps LHSCC, RHSCC;
1551 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1552 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1553 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1554 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1555 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1556 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1557 // Ensure that the larger constant is on the RHS.
1558 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1559 SetCondInst *LHS = cast<SetCondInst>(Op0);
1560 if (cast<ConstantBool>(Cmp)->getValue()) {
1561 std::swap(LHS, RHS);
1562 std::swap(LHSCst, RHSCst);
1563 std::swap(LHSCC, RHSCC);
1564 }
1565
1566 // At this point, we know we have have two setcc instructions
1567 // comparing a value against two constants and or'ing the result
1568 // together. Because of the above check, we know that we only have
1569 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1570 // FoldSetCCLogical check above), that the two constants are not
1571 // equal.
1572 assert(LHSCst != RHSCst && "Compares not folded above?");
1573
1574 switch (LHSCC) {
1575 default: assert(0 && "Unknown integer condition code!");
1576 case Instruction::SetEQ:
1577 switch (RHSCC) {
1578 default: assert(0 && "Unknown integer condition code!");
1579 case Instruction::SetEQ:
1580 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1581 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1582 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1583 LHSVal->getName()+".off");
1584 InsertNewInstBefore(Add, I);
1585 const Type *UnsType = Add->getType()->getUnsignedVersion();
1586 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1587 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1588 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1589 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1590 }
1591 break; // (X == 13 | X == 15) -> no change
1592
1593 case Instruction::SetGT:
1594 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1595 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1596 break; // (X == 13 | X > 15) -> no change
1597 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1598 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1599 return ReplaceInstUsesWith(I, RHS);
1600 }
1601 break;
1602 case Instruction::SetNE:
1603 switch (RHSCC) {
1604 default: assert(0 && "Unknown integer condition code!");
1605 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1606 return ReplaceInstUsesWith(I, RHS);
1607 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1608 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1609 return ReplaceInstUsesWith(I, LHS);
1610 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1611 return ReplaceInstUsesWith(I, ConstantBool::True);
1612 }
1613 break;
1614 case Instruction::SetLT:
1615 switch (RHSCC) {
1616 default: assert(0 && "Unknown integer condition code!");
1617 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1618 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001619 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1620 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001621 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1622 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1623 return ReplaceInstUsesWith(I, RHS);
1624 }
1625 break;
1626 case Instruction::SetGT:
1627 switch (RHSCC) {
1628 default: assert(0 && "Unknown integer condition code!");
1629 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1630 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1631 return ReplaceInstUsesWith(I, LHS);
1632 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1633 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1634 return ReplaceInstUsesWith(I, ConstantBool::True);
1635 }
1636 }
1637 }
1638 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001639 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001640}
1641
Chris Lattnerc2076352004-02-16 01:20:27 +00001642// XorSelf - Implements: X ^ X --> 0
1643struct XorSelf {
1644 Value *RHS;
1645 XorSelf(Value *rhs) : RHS(rhs) {}
1646 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1647 Instruction *apply(BinaryOperator &Xor) const {
1648 return &Xor;
1649 }
1650};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001651
1652
Chris Lattner113f4f42002-06-25 16:13:24 +00001653Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001654 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001655 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001656
Chris Lattnerc2076352004-02-16 01:20:27 +00001657 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1658 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1659 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001660 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001661 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001662
Chris Lattner97638592003-07-23 21:37:07 +00001663 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001664 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001665 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001666 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001667
Chris Lattner97638592003-07-23 21:37:07 +00001668 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001669 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001670 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001671 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001672 return new SetCondInst(SCI->getInverseCondition(),
1673 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001674
Chris Lattner8f2f5982003-11-05 01:06:05 +00001675 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001676 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1677 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001678 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1679 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001680 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001681 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001682 }
Chris Lattner023a4832004-06-18 06:07:51 +00001683
1684 // ~(~X & Y) --> (X | ~Y)
1685 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1686 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1687 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1688 Instruction *NotY =
1689 BinaryOperator::createNot(Op0I->getOperand(1),
1690 Op0I->getOperand(1)->getName()+".not");
1691 InsertNewInstBefore(NotY, I);
1692 return BinaryOperator::createOr(Op0NotVal, NotY);
1693 }
1694 }
Chris Lattner97638592003-07-23 21:37:07 +00001695
1696 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001697 switch (Op0I->getOpcode()) {
1698 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001699 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001700 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001701 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1702 return BinaryOperator::createSub(
1703 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001704 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001705 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001706 }
Chris Lattnere5806662003-11-04 23:50:51 +00001707 break;
1708 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001709 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001710 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1711 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001712 break;
1713 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001714 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001715 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001716 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001717 break;
1718 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001719 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001720 }
Chris Lattner183b3362004-04-09 19:05:30 +00001721
1722 // Try to fold constant and into select arguments.
1723 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1724 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1725 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001726 if (isa<PHINode>(Op0))
1727 if (Instruction *NV = FoldOpIntoPhi(I))
1728 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001729 }
1730
Chris Lattnerbb74e222003-03-10 23:06:50 +00001731 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001732 if (X == Op1)
1733 return ReplaceInstUsesWith(I,
1734 ConstantIntegral::getAllOnesValue(I.getType()));
1735
Chris Lattnerbb74e222003-03-10 23:06:50 +00001736 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001737 if (X == Op0)
1738 return ReplaceInstUsesWith(I,
1739 ConstantIntegral::getAllOnesValue(I.getType()));
1740
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001741 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001742 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001743 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1744 cast<BinaryOperator>(Op1I)->swapOperands();
1745 I.swapOperands();
1746 std::swap(Op0, Op1);
1747 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1748 I.swapOperands();
1749 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001750 }
1751 } else if (Op1I->getOpcode() == Instruction::Xor) {
1752 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1753 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1754 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1755 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1756 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001757
1758 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001759 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001760 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1761 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001762 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001763 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1764 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001765 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001766 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001767 } else if (Op0I->getOpcode() == Instruction::Xor) {
1768 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1769 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1770 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1771 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001772 }
1773
Chris Lattner7aa2d472004-08-01 19:42:59 +00001774 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001775 Value *A, *B; ConstantInt *C1, *C2;
1776 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1777 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001778 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001779 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001780
Chris Lattner3ac7c262003-08-13 20:16:26 +00001781 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1782 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1783 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1784 return R;
1785
Chris Lattner113f4f42002-06-25 16:13:24 +00001786 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001787}
1788
Chris Lattner6862fbd2004-09-29 17:40:11 +00001789/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1790/// overflowed for this type.
1791static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1792 ConstantInt *In2) {
1793 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1794 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1795}
1796
1797static bool isPositive(ConstantInt *C) {
1798 return cast<ConstantSInt>(C)->getValue() >= 0;
1799}
1800
1801/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1802/// overflowed for this type.
1803static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1804 ConstantInt *In2) {
1805 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1806
1807 if (In1->getType()->isUnsigned())
1808 return cast<ConstantUInt>(Result)->getValue() <
1809 cast<ConstantUInt>(In1)->getValue();
1810 if (isPositive(In1) != isPositive(In2))
1811 return false;
1812 if (isPositive(In1))
1813 return cast<ConstantSInt>(Result)->getValue() <
1814 cast<ConstantSInt>(In1)->getValue();
1815 return cast<ConstantSInt>(Result)->getValue() >
1816 cast<ConstantSInt>(In1)->getValue();
1817}
1818
Chris Lattner113f4f42002-06-25 16:13:24 +00001819Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001820 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001821 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1822 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001823
1824 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001825 if (Op0 == Op1)
1826 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001827
Chris Lattnerd07283a2003-08-13 05:38:46 +00001828 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1829 if (isa<ConstantPointerNull>(Op1) &&
1830 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001831 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1832
Chris Lattnerd07283a2003-08-13 05:38:46 +00001833
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001834 // setcc's with boolean values can always be turned into bitwise operations
1835 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001836 switch (I.getOpcode()) {
1837 default: assert(0 && "Invalid setcc instruction!");
1838 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001839 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001840 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001841 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001842 }
Chris Lattner4456da62004-08-11 00:50:51 +00001843 case Instruction::SetNE:
1844 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001845
Chris Lattner4456da62004-08-11 00:50:51 +00001846 case Instruction::SetGT:
1847 std::swap(Op0, Op1); // Change setgt -> setlt
1848 // FALL THROUGH
1849 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1850 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1851 InsertNewInstBefore(Not, I);
1852 return BinaryOperator::createAnd(Not, Op1);
1853 }
1854 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001855 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001856 // FALL THROUGH
1857 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1858 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1859 InsertNewInstBefore(Not, I);
1860 return BinaryOperator::createOr(Not, Op1);
1861 }
1862 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001863 }
1864
Chris Lattner2dd01742004-06-09 04:24:29 +00001865 // See if we are doing a comparison between a constant and an instruction that
1866 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001867 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001868 // Check to see if we are comparing against the minimum or maximum value...
1869 if (CI->isMinValue()) {
1870 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1871 return ReplaceInstUsesWith(I, ConstantBool::False);
1872 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1873 return ReplaceInstUsesWith(I, ConstantBool::True);
1874 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1875 return BinaryOperator::createSetEQ(Op0, Op1);
1876 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1877 return BinaryOperator::createSetNE(Op0, Op1);
1878
1879 } else if (CI->isMaxValue()) {
1880 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1881 return ReplaceInstUsesWith(I, ConstantBool::False);
1882 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1883 return ReplaceInstUsesWith(I, ConstantBool::True);
1884 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1885 return BinaryOperator::createSetEQ(Op0, Op1);
1886 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1887 return BinaryOperator::createSetNE(Op0, Op1);
1888
1889 // Comparing against a value really close to min or max?
1890 } else if (isMinValuePlusOne(CI)) {
1891 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1892 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1893 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1894 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1895
1896 } else if (isMaxValueMinusOne(CI)) {
1897 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1898 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1899 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1900 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1901 }
1902
1903 // If we still have a setle or setge instruction, turn it into the
1904 // appropriate setlt or setgt instruction. Since the border cases have
1905 // already been handled above, this requires little checking.
1906 //
1907 if (I.getOpcode() == Instruction::SetLE)
1908 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1909 if (I.getOpcode() == Instruction::SetGE)
1910 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1911
Chris Lattnere1e10e12004-05-25 06:32:08 +00001912 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001913 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001914 case Instruction::PHI:
1915 if (Instruction *NV = FoldOpIntoPhi(I))
1916 return NV;
1917 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001918 case Instruction::And:
1919 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1920 LHSI->getOperand(0)->hasOneUse()) {
1921 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1922 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1923 // happens a LOT in code produced by the C front-end, for bitfield
1924 // access.
1925 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1926 ConstantUInt *ShAmt;
1927 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1928 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1929 const Type *Ty = LHSI->getType();
1930
1931 // We can fold this as long as we can't shift unknown bits
1932 // into the mask. This can only happen with signed shift
1933 // rights, as they sign-extend.
1934 if (ShAmt) {
1935 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001936 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001937 if (!CanFold) {
1938 // To test for the bad case of the signed shr, see if any
1939 // of the bits shifted in could be tested after the mask.
1940 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001941 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001942 Constant *ShVal =
1943 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1944 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1945 CanFold = true;
1946 }
1947
1948 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001949 Constant *NewCst;
1950 if (Shift->getOpcode() == Instruction::Shl)
1951 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1952 else
1953 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001954
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001955 // Check to see if we are shifting out any of the bits being
1956 // compared.
1957 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1958 // If we shifted bits out, the fold is not going to work out.
1959 // As a special case, check to see if this means that the
1960 // result is always true or false now.
1961 if (I.getOpcode() == Instruction::SetEQ)
1962 return ReplaceInstUsesWith(I, ConstantBool::False);
1963 if (I.getOpcode() == Instruction::SetNE)
1964 return ReplaceInstUsesWith(I, ConstantBool::True);
1965 } else {
1966 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00001967 Constant *NewAndCST;
1968 if (Shift->getOpcode() == Instruction::Shl)
1969 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
1970 else
1971 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1972 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001973 LHSI->setOperand(0, Shift->getOperand(0));
1974 WorkList.push_back(Shift); // Shift is dead.
1975 AddUsesToWorkList(I);
1976 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00001977 }
1978 }
Chris Lattner35167c32004-06-09 07:59:58 +00001979 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001980 }
1981 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001982
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001983 case Instruction::Cast: { // (setcc (cast X to larger), CI)
1984 const Type *SrcTy = LHSI->getOperand(0)->getType();
1985 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00001986 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001987 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00001988 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001989 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
1990 if (SrcBits < DestBits) {
1991 // Check to see if the comparison is always true or false.
1992 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
1993 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
1994 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
1995 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
1996 Min = ConstantExpr::getCast(Min, LHSI->getType());
1997 Max = ConstantExpr::getCast(Max, LHSI->getType());
1998 switch (I.getOpcode()) {
1999 default: assert(0 && "unknown integer comparison");
2000 case Instruction::SetEQ:
2001 return ReplaceInstUsesWith(I, ConstantBool::False);
2002 case Instruction::SetNE:
2003 return ReplaceInstUsesWith(I, ConstantBool::True);
2004 case Instruction::SetLT:
2005 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002006 case Instruction::SetGT:
2007 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002008 }
2009 }
2010
2011 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2012 ConstantExpr::getCast(CI, SrcTy));
2013 }
2014 }
2015 break;
2016 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00002017 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2018 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2019 switch (I.getOpcode()) {
2020 default: break;
2021 case Instruction::SetEQ:
2022 case Instruction::SetNE: {
2023 // If we are comparing against bits always shifted out, the
2024 // comparison cannot succeed.
2025 Constant *Comp =
2026 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2027 if (Comp != CI) {// Comparing against a bit that we know is zero.
2028 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2029 Constant *Cst = ConstantBool::get(IsSetNE);
2030 return ReplaceInstUsesWith(I, Cst);
2031 }
2032
2033 if (LHSI->hasOneUse()) {
2034 // Otherwise strength reduce the shift into an and.
2035 unsigned ShAmtVal = ShAmt->getValue();
2036 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2037 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2038
2039 Constant *Mask;
2040 if (CI->getType()->isUnsigned()) {
2041 Mask = ConstantUInt::get(CI->getType(), Val);
2042 } else if (ShAmtVal != 0) {
2043 Mask = ConstantSInt::get(CI->getType(), Val);
2044 } else {
2045 Mask = ConstantInt::getAllOnesValue(CI->getType());
2046 }
2047
2048 Instruction *AndI =
2049 BinaryOperator::createAnd(LHSI->getOperand(0),
2050 Mask, LHSI->getName()+".mask");
2051 Value *And = InsertNewInstBefore(AndI, I);
2052 return new SetCondInst(I.getOpcode(), And,
2053 ConstantExpr::getUShr(CI, ShAmt));
2054 }
2055 }
2056 }
2057 }
2058 break;
2059
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002060 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002061 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002062 switch (I.getOpcode()) {
2063 default: break;
2064 case Instruction::SetEQ:
2065 case Instruction::SetNE: {
2066 // If we are comparing against bits always shifted out, the
2067 // comparison cannot succeed.
2068 Constant *Comp =
2069 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2070
2071 if (Comp != CI) {// Comparing against a bit that we know is zero.
2072 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2073 Constant *Cst = ConstantBool::get(IsSetNE);
2074 return ReplaceInstUsesWith(I, Cst);
2075 }
2076
2077 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002078 unsigned ShAmtVal = ShAmt->getValue();
2079
Chris Lattner1023b872004-09-27 16:18:50 +00002080 // Otherwise strength reduce the shift into an and.
2081 uint64_t Val = ~0ULL; // All ones.
2082 Val <<= ShAmtVal; // Shift over to the right spot.
2083
2084 Constant *Mask;
2085 if (CI->getType()->isUnsigned()) {
2086 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2087 Val &= (1ULL << TypeBits)-1;
2088 Mask = ConstantUInt::get(CI->getType(), Val);
2089 } else {
2090 Mask = ConstantSInt::get(CI->getType(), Val);
2091 }
2092
2093 Instruction *AndI =
2094 BinaryOperator::createAnd(LHSI->getOperand(0),
2095 Mask, LHSI->getName()+".mask");
2096 Value *And = InsertNewInstBefore(AndI, I);
2097 return new SetCondInst(I.getOpcode(), And,
2098 ConstantExpr::getShl(CI, ShAmt));
2099 }
2100 break;
2101 }
2102 }
2103 }
2104 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002105
Chris Lattner6862fbd2004-09-29 17:40:11 +00002106 case Instruction::Div:
2107 // Fold: (div X, C1) op C2 -> range check
2108 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2109 // Fold this div into the comparison, producing a range check.
2110 // Determine, based on the divide type, what the range is being
2111 // checked. If there is an overflow on the low or high side, remember
2112 // it, otherwise compute the range [low, hi) bounding the new value.
2113 bool LoOverflow = false, HiOverflow = 0;
2114 ConstantInt *LoBound = 0, *HiBound = 0;
2115
2116 ConstantInt *Prod;
2117 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2118
2119 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2120 } else if (LHSI->getType()->isUnsigned()) { // udiv
2121 LoBound = Prod;
2122 LoOverflow = ProdOV;
2123 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2124 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2125 if (CI->isNullValue()) { // (X / pos) op 0
2126 // Can't overflow.
2127 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2128 HiBound = DivRHS;
2129 } else if (isPositive(CI)) { // (X / pos) op pos
2130 LoBound = Prod;
2131 LoOverflow = ProdOV;
2132 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2133 } else { // (X / pos) op neg
2134 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2135 LoOverflow = AddWithOverflow(LoBound, Prod,
2136 cast<ConstantInt>(DivRHSH));
2137 HiBound = Prod;
2138 HiOverflow = ProdOV;
2139 }
2140 } else { // Divisor is < 0.
2141 if (CI->isNullValue()) { // (X / neg) op 0
2142 LoBound = AddOne(DivRHS);
2143 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2144 } else if (isPositive(CI)) { // (X / neg) op pos
2145 HiOverflow = LoOverflow = ProdOV;
2146 if (!LoOverflow)
2147 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2148 HiBound = AddOne(Prod);
2149 } else { // (X / neg) op neg
2150 LoBound = Prod;
2151 LoOverflow = HiOverflow = ProdOV;
2152 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2153 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002154
2155 /// FIXME: This code is disabled, because we do not compile the
2156 /// divisor case < 0 correctly. For example, this code is incorrect
2157 /// in the case of "X/-10 < 1".
2158 LoBound = 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002159 }
2160
2161 if (LoBound) {
2162 Value *X = LHSI->getOperand(0);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002163 switch (I.getOpcode()) {
2164 default: assert(0 && "Unhandled setcc opcode!");
2165 case Instruction::SetEQ:
2166 if (LoOverflow && HiOverflow)
2167 return ReplaceInstUsesWith(I, ConstantBool::False);
2168 else if (HiOverflow)
2169 return new SetCondInst(Instruction::SetGE, X, LoBound);
2170 else if (LoOverflow)
2171 return new SetCondInst(Instruction::SetLT, X, HiBound);
2172 else
2173 return InsertRangeTest(X, LoBound, HiBound, true, I);
2174 case Instruction::SetNE:
2175 if (LoOverflow && HiOverflow)
2176 return ReplaceInstUsesWith(I, ConstantBool::True);
2177 else if (HiOverflow)
2178 return new SetCondInst(Instruction::SetLT, X, LoBound);
2179 else if (LoOverflow)
2180 return new SetCondInst(Instruction::SetGE, X, HiBound);
2181 else
2182 return InsertRangeTest(X, LoBound, HiBound, false, I);
2183 case Instruction::SetLT:
2184 if (LoOverflow)
2185 return ReplaceInstUsesWith(I, ConstantBool::False);
2186 return new SetCondInst(Instruction::SetLT, X, LoBound);
2187 case Instruction::SetGT:
2188 if (HiOverflow)
2189 return ReplaceInstUsesWith(I, ConstantBool::False);
2190 return new SetCondInst(Instruction::SetGE, X, HiBound);
2191 }
2192 }
2193 }
2194 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002195 case Instruction::Select:
2196 // If either operand of the select is a constant, we can fold the
2197 // comparison into the select arms, which will cause one to be
2198 // constant folded and the select turned into a bitwise or.
2199 Value *Op1 = 0, *Op2 = 0;
2200 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002201 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002202 // Fold the known value into the constant operand.
2203 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2204 // Insert a new SetCC of the other select operand.
2205 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002206 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002207 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002208 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002209 // Fold the known value into the constant operand.
2210 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2211 // Insert a new SetCC of the other select operand.
2212 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002213 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002214 I.getName()), I);
2215 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002216 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002217
2218 if (Op1)
2219 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2220 break;
2221 }
2222
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002223 // Simplify seteq and setne instructions...
2224 if (I.getOpcode() == Instruction::SetEQ ||
2225 I.getOpcode() == Instruction::SetNE) {
2226 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2227
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002228 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002229 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2231 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002232 case Instruction::Rem:
2233 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2234 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2235 BO->hasOneUse() &&
2236 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2237 if (unsigned L2 =
2238 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2239 const Type *UTy = BO->getType()->getUnsignedVersion();
2240 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2241 UTy, "tmp"), I);
2242 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2243 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2244 RHSCst, BO->getName()), I);
2245 return BinaryOperator::create(I.getOpcode(), NewRem,
2246 Constant::getNullValue(UTy));
2247 }
2248 break;
2249
Chris Lattnerc992add2003-08-13 05:33:12 +00002250 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002251 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2252 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002253 if (BO->hasOneUse())
2254 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2255 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002256 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002257 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2258 // efficiently invertible, or if the add has just this one use.
2259 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002260
Chris Lattnerc992add2003-08-13 05:33:12 +00002261 if (Value *NegVal = dyn_castNegVal(BOp1))
2262 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2263 else if (Value *NegVal = dyn_castNegVal(BOp0))
2264 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002265 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002266 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2267 BO->setName("");
2268 InsertNewInstBefore(Neg, I);
2269 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2270 }
2271 }
2272 break;
2273 case Instruction::Xor:
2274 // For the xor case, we can xor two constants together, eliminating
2275 // the explicit xor.
2276 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2277 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002278 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002279
2280 // FALLTHROUGH
2281 case Instruction::Sub:
2282 // Replace (([sub|xor] A, B) != 0) with (A != B)
2283 if (CI->isNullValue())
2284 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2285 BO->getOperand(1));
2286 break;
2287
2288 case Instruction::Or:
2289 // If bits are being or'd in that are not present in the constant we
2290 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002291 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002292 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002293 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002294 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002295 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002296 break;
2297
2298 case Instruction::And:
2299 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002300 // If bits are being compared against that are and'd out, then the
2301 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002302 if (!ConstantExpr::getAnd(CI,
2303 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002304 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002305
Chris Lattner35167c32004-06-09 07:59:58 +00002306 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002307 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002308 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2309 Instruction::SetNE, Op0,
2310 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002311
Chris Lattnerc992add2003-08-13 05:33:12 +00002312 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2313 // to be a signed value as appropriate.
2314 if (isSignBit(BOC)) {
2315 Value *X = BO->getOperand(0);
2316 // If 'X' is not signed, insert a cast now...
2317 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002318 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002319 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002320 }
2321 return new SetCondInst(isSetNE ? Instruction::SetLT :
2322 Instruction::SetGE, X,
2323 Constant::getNullValue(X->getType()));
2324 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002325
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002326 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002327 if (CI->isNullValue() && isHighOnes(BOC)) {
2328 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002329 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002330
2331 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002332 if (NegX->getType()->isSigned()) {
2333 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2334 X = InsertCastBefore(X, DestTy, I);
2335 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002336 }
2337
2338 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002339 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002340 }
2341
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002342 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002343 default: break;
2344 }
2345 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002346 } else { // Not a SetEQ/SetNE
2347 // If the LHS is a cast from an integral value of the same size,
2348 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2349 Value *CastOp = Cast->getOperand(0);
2350 const Type *SrcTy = CastOp->getType();
2351 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2352 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2353 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2354 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2355 "Source and destination signednesses should differ!");
2356 if (Cast->getType()->isSigned()) {
2357 // If this is a signed comparison, check for comparisons in the
2358 // vicinity of zero.
2359 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2360 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002361 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002362 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2363 else if (I.getOpcode() == Instruction::SetGT &&
2364 cast<ConstantSInt>(CI)->getValue() == -1)
2365 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002366 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002367 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2368 } else {
2369 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2370 if (I.getOpcode() == Instruction::SetLT &&
2371 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2372 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002373 return BinaryOperator::createSetGT(CastOp,
2374 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002375 else if (I.getOpcode() == Instruction::SetGT &&
2376 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2377 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002378 return BinaryOperator::createSetLT(CastOp,
2379 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002380 }
2381 }
2382 }
Chris Lattnere967b342003-06-04 05:10:11 +00002383 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002384 }
2385
Chris Lattner16930792003-11-03 04:25:02 +00002386 // Test to see if the operands of the setcc are casted versions of other
2387 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002388 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2389 Value *CastOp0 = CI->getOperand(0);
2390 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002391 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002392 (I.getOpcode() == Instruction::SetEQ ||
2393 I.getOpcode() == Instruction::SetNE)) {
2394 // We keep moving the cast from the left operand over to the right
2395 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002396 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002397
2398 // If operand #1 is a cast instruction, see if we can eliminate it as
2399 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002400 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2401 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002402 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002403 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002404
2405 // If Op1 is a constant, we can fold the cast into the constant.
2406 if (Op1->getType() != Op0->getType())
2407 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2408 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2409 } else {
2410 // Otherwise, cast the RHS right before the setcc
2411 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2412 InsertNewInstBefore(cast<Instruction>(Op1), I);
2413 }
2414 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2415 }
2416
Chris Lattner6444c372003-11-03 05:17:03 +00002417 // Handle the special case of: setcc (cast bool to X), <cst>
2418 // This comes up when you have code like
2419 // int X = A < B;
2420 // if (X) ...
2421 // For generality, we handle any zero-extension of any operand comparison
2422 // with a constant.
2423 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2424 const Type *SrcTy = CastOp0->getType();
2425 const Type *DestTy = Op0->getType();
2426 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2427 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2428 // Ok, we have an expansion of operand 0 into a new type. Get the
2429 // constant value, masink off bits which are not set in the RHS. These
2430 // could be set if the destination value is signed.
2431 uint64_t ConstVal = ConstantRHS->getRawValue();
2432 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2433
2434 // If the constant we are comparing it with has high bits set, which
2435 // don't exist in the original value, the values could never be equal,
2436 // because the source would be zero extended.
2437 unsigned SrcBits =
2438 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002439 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2440 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002441 switch (I.getOpcode()) {
2442 default: assert(0 && "Unknown comparison type!");
2443 case Instruction::SetEQ:
2444 return ReplaceInstUsesWith(I, ConstantBool::False);
2445 case Instruction::SetNE:
2446 return ReplaceInstUsesWith(I, ConstantBool::True);
2447 case Instruction::SetLT:
2448 case Instruction::SetLE:
2449 if (DestTy->isSigned() && HasSignBit)
2450 return ReplaceInstUsesWith(I, ConstantBool::False);
2451 return ReplaceInstUsesWith(I, ConstantBool::True);
2452 case Instruction::SetGT:
2453 case Instruction::SetGE:
2454 if (DestTy->isSigned() && HasSignBit)
2455 return ReplaceInstUsesWith(I, ConstantBool::True);
2456 return ReplaceInstUsesWith(I, ConstantBool::False);
2457 }
2458 }
2459
2460 // Otherwise, we can replace the setcc with a setcc of the smaller
2461 // operand value.
2462 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2463 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2464 }
2465 }
2466 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002467 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002468}
2469
2470
2471
Chris Lattnere8d6c602003-03-10 19:16:08 +00002472Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002473 assert(I.getOperand(1)->getType() == Type::UByteTy);
2474 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002475 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002476
2477 // shl X, 0 == X and shr X, 0 == X
2478 // shl 0, X == 0 and shr 0, X == 0
2479 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002480 Op0 == Constant::getNullValue(Op0->getType()))
2481 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002482
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002483 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2484 if (!isLeftShift)
2485 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2486 if (CSI->isAllOnesValue())
2487 return ReplaceInstUsesWith(I, CSI);
2488
Chris Lattner183b3362004-04-09 19:05:30 +00002489 // Try to fold constant and into select arguments.
2490 if (isa<Constant>(Op0))
2491 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2492 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2493 return R;
2494
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002495 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002496 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2497 // of a signed value.
2498 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002499 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002500 if (CUI->getValue() >= TypeBits) {
2501 if (!Op0->getType()->isSigned() || isLeftShift)
2502 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2503 else {
2504 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2505 return &I;
2506 }
2507 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002508
Chris Lattnerede3fe02003-08-13 04:18:28 +00002509 // ((X*C1) << C2) == (X * (C1 << C2))
2510 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2511 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2512 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002513 return BinaryOperator::createMul(BO->getOperand(0),
2514 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002515
Chris Lattner183b3362004-04-09 19:05:30 +00002516 // Try to fold constant and into select arguments.
2517 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2518 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2519 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002520 if (isa<PHINode>(Op0))
2521 if (Instruction *NV = FoldOpIntoPhi(I))
2522 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002523
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002524 // If the operand is an bitwise operator with a constant RHS, and the
2525 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002526 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002527 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2528 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2529 bool isValid = true; // Valid only for And, Or, Xor
2530 bool highBitSet = false; // Transform if high bit of constant set?
2531
2532 switch (Op0BO->getOpcode()) {
2533 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002534 case Instruction::Add:
2535 isValid = isLeftShift;
2536 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002537 case Instruction::Or:
2538 case Instruction::Xor:
2539 highBitSet = false;
2540 break;
2541 case Instruction::And:
2542 highBitSet = true;
2543 break;
2544 }
2545
2546 // If this is a signed shift right, and the high bit is modified
2547 // by the logical operation, do not perform the transformation.
2548 // The highBitSet boolean indicates the value of the high bit of
2549 // the constant which would cause it to be modified for this
2550 // operation.
2551 //
2552 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2553 uint64_t Val = Op0C->getRawValue();
2554 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2555 }
2556
2557 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002558 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002559
2560 Instruction *NewShift =
2561 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2562 Op0BO->getName());
2563 Op0BO->setName("");
2564 InsertNewInstBefore(NewShift, I);
2565
2566 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2567 NewRHS);
2568 }
2569 }
2570
Chris Lattner3204d4e2003-07-24 17:52:58 +00002571 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002572 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002573 if (ConstantUInt *ShiftAmt1C =
2574 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002575 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2576 unsigned ShiftAmt2 = CUI->getValue();
2577
2578 // Check for (A << c1) << c2 and (A >> c1) >> c2
2579 if (I.getOpcode() == Op0SI->getOpcode()) {
2580 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002581 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2582 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002583 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2584 ConstantUInt::get(Type::UByteTy, Amt));
2585 }
2586
Chris Lattnerab780df2003-07-24 18:38:56 +00002587 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2588 // signed types, we can only support the (A >> c1) << c2 configuration,
2589 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002590 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002591 // Calculate bitmask for what gets shifted off the edge...
2592 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002593 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002594 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002595 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002596 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002597
2598 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002599 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2600 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002601 InsertNewInstBefore(Mask, I);
2602
2603 // Figure out what flavor of shift we should use...
2604 if (ShiftAmt1 == ShiftAmt2)
2605 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2606 else if (ShiftAmt1 < ShiftAmt2) {
2607 return new ShiftInst(I.getOpcode(), Mask,
2608 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2609 } else {
2610 return new ShiftInst(Op0SI->getOpcode(), Mask,
2611 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2612 }
2613 }
2614 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002615 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002616
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002617 return 0;
2618}
2619
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002620enum CastType {
2621 Noop = 0,
2622 Truncate = 1,
2623 Signext = 2,
2624 Zeroext = 3
2625};
2626
2627/// getCastType - In the future, we will split the cast instruction into these
2628/// various types. Until then, we have to do the analysis here.
2629static CastType getCastType(const Type *Src, const Type *Dest) {
2630 assert(Src->isIntegral() && Dest->isIntegral() &&
2631 "Only works on integral types!");
2632 unsigned SrcSize = Src->getPrimitiveSize()*8;
2633 if (Src == Type::BoolTy) SrcSize = 1;
2634 unsigned DestSize = Dest->getPrimitiveSize()*8;
2635 if (Dest == Type::BoolTy) DestSize = 1;
2636
2637 if (SrcSize == DestSize) return Noop;
2638 if (SrcSize > DestSize) return Truncate;
2639 if (Src->isSigned()) return Signext;
2640 return Zeroext;
2641}
2642
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002643
Chris Lattner48a44f72002-05-02 17:06:02 +00002644// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2645// instruction.
2646//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002647static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002648 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002649
Chris Lattner650b6da2002-08-02 20:00:25 +00002650 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2651 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002652 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002653 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002654 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002655
Chris Lattner4fbad962004-07-21 04:27:24 +00002656 // If we are casting between pointer and integer types, treat pointers as
2657 // integers of the appropriate size for the code below.
2658 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2659 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2660 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002661
Chris Lattner48a44f72002-05-02 17:06:02 +00002662 // Allow free casting and conversion of sizes as long as the sign doesn't
2663 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002664 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002665 CastType FirstCast = getCastType(SrcTy, MidTy);
2666 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002667
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002668 // Capture the effect of these two casts. If the result is a legal cast,
2669 // the CastType is stored here, otherwise a special code is used.
2670 static const unsigned CastResult[] = {
2671 // First cast is noop
2672 0, 1, 2, 3,
2673 // First cast is a truncate
2674 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2675 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002676 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002677 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002678 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002679 };
2680
2681 unsigned Result = CastResult[FirstCast*4+SecondCast];
2682 switch (Result) {
2683 default: assert(0 && "Illegal table value!");
2684 case 0:
2685 case 1:
2686 case 2:
2687 case 3:
2688 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2689 // truncates, we could eliminate more casts.
2690 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2691 case 4:
2692 return false; // Not possible to eliminate this here.
2693 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002694 // Sign or zero extend followed by truncate is always ok if the result
2695 // is a truncate or noop.
2696 CastType ResultCast = getCastType(SrcTy, DstTy);
2697 if (ResultCast == Noop || ResultCast == Truncate)
2698 return true;
2699 // Otherwise we are still growing the value, we are only safe if the
2700 // result will match the sign/zeroextendness of the result.
2701 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002702 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002703 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002704 return false;
2705}
2706
Chris Lattner11ffd592004-07-20 05:21:00 +00002707static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002708 if (V->getType() == Ty || isa<Constant>(V)) return false;
2709 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002710 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2711 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002712 return false;
2713 return true;
2714}
2715
2716/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2717/// InsertBefore instruction. This is specialized a bit to avoid inserting
2718/// casts that are known to not do anything...
2719///
2720Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2721 Instruction *InsertBefore) {
2722 if (V->getType() == DestTy) return V;
2723 if (Constant *C = dyn_cast<Constant>(V))
2724 return ConstantExpr::getCast(C, DestTy);
2725
2726 CastInst *CI = new CastInst(V, DestTy, V->getName());
2727 InsertNewInstBefore(CI, *InsertBefore);
2728 return CI;
2729}
Chris Lattner48a44f72002-05-02 17:06:02 +00002730
2731// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002732//
Chris Lattner113f4f42002-06-25 16:13:24 +00002733Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002734 Value *Src = CI.getOperand(0);
2735
Chris Lattner48a44f72002-05-02 17:06:02 +00002736 // If the user is casting a value to the same type, eliminate this cast
2737 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002738 if (CI.getType() == Src->getType())
2739 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002740
Chris Lattner48a44f72002-05-02 17:06:02 +00002741 // If casting the result of another cast instruction, try to eliminate this
2742 // one!
2743 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002744 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002745 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002746 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002747 // This instruction now refers directly to the cast's src operand. This
2748 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002749 CI.setOperand(0, CSrc->getOperand(0));
2750 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002751 }
2752
Chris Lattner650b6da2002-08-02 20:00:25 +00002753 // If this is an A->B->A cast, and we are dealing with integral types, try
2754 // to convert this into a logical 'and' instruction.
2755 //
2756 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002757 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002758 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2759 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2760 assert(CSrc->getType() != Type::ULongTy &&
2761 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002762 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002763 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002764 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002765 }
2766 }
2767
Chris Lattner03841652004-05-25 04:29:21 +00002768 // If this is a cast to bool, turn it into the appropriate setne instruction.
2769 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002770 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002771 Constant::getNullValue(CI.getOperand(0)->getType()));
2772
Chris Lattnerd0d51602003-06-21 23:12:02 +00002773 // If casting the result of a getelementptr instruction with no offset, turn
2774 // this into a cast of the original pointer!
2775 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002776 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002777 bool AllZeroOperands = true;
2778 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2779 if (!isa<Constant>(GEP->getOperand(i)) ||
2780 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2781 AllZeroOperands = false;
2782 break;
2783 }
2784 if (AllZeroOperands) {
2785 CI.setOperand(0, GEP->getOperand(0));
2786 return &CI;
2787 }
2788 }
2789
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002790 // If we are casting a malloc or alloca to a pointer to a type of the same
2791 // size, rewrite the allocation instruction to allocate the "right" type.
2792 //
2793 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002794 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002795 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2796 // Get the type really allocated and the type casted to...
2797 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002798 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002799 if (AllocElTy->isSized() && CastElTy->isSized()) {
2800 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2801 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002802
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002803 // If the allocation is for an even multiple of the cast type size
2804 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2805 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002806 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002807 std::string Name = AI->getName(); AI->setName("");
2808 AllocationInst *New;
2809 if (isa<MallocInst>(AI))
2810 New = new MallocInst(CastElTy, Amt, Name);
2811 else
2812 New = new AllocaInst(CastElTy, Amt, Name);
2813 InsertNewInstBefore(New, *AI);
2814 return ReplaceInstUsesWith(CI, New);
2815 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002816 }
2817 }
2818
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002819 if (isa<PHINode>(Src))
2820 if (Instruction *NV = FoldOpIntoPhi(CI))
2821 return NV;
2822
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002823 // If the source value is an instruction with only this use, we can attempt to
2824 // propagate the cast into the instruction. Also, only handle integral types
2825 // for now.
2826 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002827 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002828 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2829 const Type *DestTy = CI.getType();
2830 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2831 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2832
2833 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2834 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2835
2836 switch (SrcI->getOpcode()) {
2837 case Instruction::Add:
2838 case Instruction::Mul:
2839 case Instruction::And:
2840 case Instruction::Or:
2841 case Instruction::Xor:
2842 // If we are discarding information, or just changing the sign, rewrite.
2843 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2844 // Don't insert two casts if they cannot be eliminated. We allow two
2845 // casts to be inserted if the sizes are the same. This could only be
2846 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002847 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2848 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002849 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2850 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2851 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2852 ->getOpcode(), Op0c, Op1c);
2853 }
2854 }
2855 break;
2856 case Instruction::Shl:
2857 // Allow changing the sign of the source operand. Do not allow changing
2858 // the size of the shift, UNLESS the shift amount is a constant. We
2859 // mush not change variable sized shifts to a smaller size, because it
2860 // is undefined to shift more bits out than exist in the value.
2861 if (DestBitSize == SrcBitSize ||
2862 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2863 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2864 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2865 }
2866 break;
2867 }
2868 }
2869
Chris Lattner260ab202002-04-18 17:39:14 +00002870 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002871}
2872
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002873/// GetSelectFoldableOperands - We want to turn code that looks like this:
2874/// %C = or %A, %B
2875/// %D = select %cond, %C, %A
2876/// into:
2877/// %C = select %cond, %B, 0
2878/// %D = or %A, %C
2879///
2880/// Assuming that the specified instruction is an operand to the select, return
2881/// a bitmask indicating which operands of this instruction are foldable if they
2882/// equal the other incoming value of the select.
2883///
2884static unsigned GetSelectFoldableOperands(Instruction *I) {
2885 switch (I->getOpcode()) {
2886 case Instruction::Add:
2887 case Instruction::Mul:
2888 case Instruction::And:
2889 case Instruction::Or:
2890 case Instruction::Xor:
2891 return 3; // Can fold through either operand.
2892 case Instruction::Sub: // Can only fold on the amount subtracted.
2893 case Instruction::Shl: // Can only fold on the shift amount.
2894 case Instruction::Shr:
2895 return 1;
2896 default:
2897 return 0; // Cannot fold
2898 }
2899}
2900
2901/// GetSelectFoldableConstant - For the same transformation as the previous
2902/// function, return the identity constant that goes into the select.
2903static Constant *GetSelectFoldableConstant(Instruction *I) {
2904 switch (I->getOpcode()) {
2905 default: assert(0 && "This cannot happen!"); abort();
2906 case Instruction::Add:
2907 case Instruction::Sub:
2908 case Instruction::Or:
2909 case Instruction::Xor:
2910 return Constant::getNullValue(I->getType());
2911 case Instruction::Shl:
2912 case Instruction::Shr:
2913 return Constant::getNullValue(Type::UByteTy);
2914 case Instruction::And:
2915 return ConstantInt::getAllOnesValue(I->getType());
2916 case Instruction::Mul:
2917 return ConstantInt::get(I->getType(), 1);
2918 }
2919}
2920
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002921Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002922 Value *CondVal = SI.getCondition();
2923 Value *TrueVal = SI.getTrueValue();
2924 Value *FalseVal = SI.getFalseValue();
2925
2926 // select true, X, Y -> X
2927 // select false, X, Y -> Y
2928 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002929 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002930 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002931 else {
2932 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002933 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002934 }
Chris Lattner533bc492004-03-30 19:37:13 +00002935
2936 // select C, X, X -> X
2937 if (TrueVal == FalseVal)
2938 return ReplaceInstUsesWith(SI, TrueVal);
2939
Chris Lattner1c631e82004-04-08 04:43:23 +00002940 if (SI.getType() == Type::BoolTy)
2941 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2942 if (C == ConstantBool::True) {
2943 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002944 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002945 } else {
2946 // Change: A = select B, false, C --> A = and !B, C
2947 Value *NotCond =
2948 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2949 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002950 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002951 }
2952 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2953 if (C == ConstantBool::False) {
2954 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002955 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002956 } else {
2957 // Change: A = select B, C, true --> A = or !B, C
2958 Value *NotCond =
2959 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2960 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002961 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002962 }
2963 }
2964
Chris Lattner183b3362004-04-09 19:05:30 +00002965 // Selecting between two integer constants?
2966 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2967 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2968 // select C, 1, 0 -> cast C to int
2969 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2970 return new CastInst(CondVal, SI.getType());
2971 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2972 // select C, 0, 1 -> cast !C to int
2973 Value *NotCond =
2974 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002975 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002976 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002977 }
Chris Lattner35167c32004-06-09 07:59:58 +00002978
2979 // If one of the constants is zero (we know they can't both be) and we
2980 // have a setcc instruction with zero, and we have an 'and' with the
2981 // non-constant value, eliminate this whole mess. This corresponds to
2982 // cases like this: ((X & 27) ? 27 : 0)
2983 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2984 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2985 if ((IC->getOpcode() == Instruction::SetEQ ||
2986 IC->getOpcode() == Instruction::SetNE) &&
2987 isa<ConstantInt>(IC->getOperand(1)) &&
2988 cast<Constant>(IC->getOperand(1))->isNullValue())
2989 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2990 if (ICA->getOpcode() == Instruction::And &&
2991 isa<ConstantInt>(ICA->getOperand(1)) &&
2992 (ICA->getOperand(1) == TrueValC ||
2993 ICA->getOperand(1) == FalseValC) &&
2994 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2995 // Okay, now we know that everything is set up, we just don't
2996 // know whether we have a setne or seteq and whether the true or
2997 // false val is the zero.
2998 bool ShouldNotVal = !TrueValC->isNullValue();
2999 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3000 Value *V = ICA;
3001 if (ShouldNotVal)
3002 V = InsertNewInstBefore(BinaryOperator::create(
3003 Instruction::Xor, V, ICA->getOperand(1)), SI);
3004 return ReplaceInstUsesWith(SI, V);
3005 }
Chris Lattner533bc492004-03-30 19:37:13 +00003006 }
Chris Lattner623fba12004-04-10 22:21:27 +00003007
3008 // See if we are selecting two values based on a comparison of the two values.
3009 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3010 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3011 // Transform (X == Y) ? X : Y -> Y
3012 if (SCI->getOpcode() == Instruction::SetEQ)
3013 return ReplaceInstUsesWith(SI, FalseVal);
3014 // Transform (X != Y) ? X : Y -> X
3015 if (SCI->getOpcode() == Instruction::SetNE)
3016 return ReplaceInstUsesWith(SI, TrueVal);
3017 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3018
3019 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3020 // Transform (X == Y) ? Y : X -> X
3021 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003022 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003023 // Transform (X != Y) ? Y : X -> Y
3024 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003025 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003026 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3027 }
3028 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003029
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003030 // See if we can fold the select into one of our operands.
3031 if (SI.getType()->isInteger()) {
3032 // See the comment above GetSelectFoldableOperands for a description of the
3033 // transformation we are doing here.
3034 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3035 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3036 !isa<Constant>(FalseVal))
3037 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3038 unsigned OpToFold = 0;
3039 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3040 OpToFold = 1;
3041 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3042 OpToFold = 2;
3043 }
3044
3045 if (OpToFold) {
3046 Constant *C = GetSelectFoldableConstant(TVI);
3047 std::string Name = TVI->getName(); TVI->setName("");
3048 Instruction *NewSel =
3049 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3050 Name);
3051 InsertNewInstBefore(NewSel, SI);
3052 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3053 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3054 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3055 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3056 else {
3057 assert(0 && "Unknown instruction!!");
3058 }
3059 }
3060 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003061
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003062 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3063 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3064 !isa<Constant>(TrueVal))
3065 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3066 unsigned OpToFold = 0;
3067 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3068 OpToFold = 1;
3069 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3070 OpToFold = 2;
3071 }
3072
3073 if (OpToFold) {
3074 Constant *C = GetSelectFoldableConstant(FVI);
3075 std::string Name = FVI->getName(); FVI->setName("");
3076 Instruction *NewSel =
3077 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3078 Name);
3079 InsertNewInstBefore(NewSel, SI);
3080 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3081 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3082 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3083 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3084 else {
3085 assert(0 && "Unknown instruction!!");
3086 }
3087 }
3088 }
3089 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003090 return 0;
3091}
3092
3093
Chris Lattner970c33a2003-06-19 17:00:31 +00003094// CallInst simplification
3095//
3096Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003097 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3098 // visitCallSite.
3099 if (Function *F = CI.getCalledFunction())
3100 switch (F->getIntrinsicID()) {
3101 case Intrinsic::memmove:
3102 case Intrinsic::memcpy:
3103 case Intrinsic::memset:
3104 // memmove/cpy/set of zero bytes is a noop.
3105 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
3106 if (NumBytes->isNullValue())
3107 return EraseInstFromFunction(CI);
3108 }
3109 break;
3110 default:
3111 break;
3112 }
3113
Chris Lattneraec3d942003-10-07 22:32:43 +00003114 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003115}
3116
3117// InvokeInst simplification
3118//
3119Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003120 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003121}
3122
Chris Lattneraec3d942003-10-07 22:32:43 +00003123// visitCallSite - Improvements for call and invoke instructions.
3124//
3125Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003126 bool Changed = false;
3127
3128 // If the callee is a constexpr cast of a function, attempt to move the cast
3129 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003130 if (transformConstExprCastCall(CS)) return 0;
3131
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003132 Value *Callee = CS.getCalledValue();
3133 const PointerType *PTy = cast<PointerType>(Callee->getType());
3134 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3135 if (FTy->isVarArg()) {
3136 // See if we can optimize any arguments passed through the varargs area of
3137 // the call.
3138 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3139 E = CS.arg_end(); I != E; ++I)
3140 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3141 // If this cast does not effect the value passed through the varargs
3142 // area, we can eliminate the use of the cast.
3143 Value *Op = CI->getOperand(0);
3144 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3145 *I = Op;
3146 Changed = true;
3147 }
3148 }
3149 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003150
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003151 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003152}
3153
Chris Lattner970c33a2003-06-19 17:00:31 +00003154// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3155// attempt to move the cast to the arguments of the call/invoke.
3156//
3157bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3158 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3159 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003160 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003161 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003162 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003163 Instruction *Caller = CS.getInstruction();
3164
3165 // Okay, this is a cast from a function to a different type. Unless doing so
3166 // would cause a type conversion of one of our arguments, change this call to
3167 // be a direct call with arguments casted to the appropriate types.
3168 //
3169 const FunctionType *FT = Callee->getFunctionType();
3170 const Type *OldRetTy = Caller->getType();
3171
Chris Lattner1f7942f2004-01-14 06:06:08 +00003172 // Check to see if we are changing the return type...
3173 if (OldRetTy != FT->getReturnType()) {
3174 if (Callee->isExternal() &&
3175 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3176 !Caller->use_empty())
3177 return false; // Cannot transform this return value...
3178
3179 // If the callsite is an invoke instruction, and the return value is used by
3180 // a PHI node in a successor, we cannot change the return type of the call
3181 // because there is no place to put the cast instruction (without breaking
3182 // the critical edge). Bail out in this case.
3183 if (!Caller->use_empty())
3184 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3185 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3186 UI != E; ++UI)
3187 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3188 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003189 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003190 return false;
3191 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003192
3193 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3194 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3195
3196 CallSite::arg_iterator AI = CS.arg_begin();
3197 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3198 const Type *ParamTy = FT->getParamType(i);
3199 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3200 if (Callee->isExternal() && !isConvertible) return false;
3201 }
3202
3203 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3204 Callee->isExternal())
3205 return false; // Do not delete arguments unless we have a function body...
3206
3207 // Okay, we decided that this is a safe thing to do: go ahead and start
3208 // inserting cast instructions as necessary...
3209 std::vector<Value*> Args;
3210 Args.reserve(NumActualArgs);
3211
3212 AI = CS.arg_begin();
3213 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3214 const Type *ParamTy = FT->getParamType(i);
3215 if ((*AI)->getType() == ParamTy) {
3216 Args.push_back(*AI);
3217 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003218 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3219 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003220 }
3221 }
3222
3223 // If the function takes more arguments than the call was taking, add them
3224 // now...
3225 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3226 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3227
3228 // If we are removing arguments to the function, emit an obnoxious warning...
3229 if (FT->getNumParams() < NumActualArgs)
3230 if (!FT->isVarArg()) {
3231 std::cerr << "WARNING: While resolving call to function '"
3232 << Callee->getName() << "' arguments were dropped!\n";
3233 } else {
3234 // Add all of the arguments in their promoted form to the arg list...
3235 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3236 const Type *PTy = getPromotedType((*AI)->getType());
3237 if (PTy != (*AI)->getType()) {
3238 // Must promote to pass through va_arg area!
3239 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3240 InsertNewInstBefore(Cast, *Caller);
3241 Args.push_back(Cast);
3242 } else {
3243 Args.push_back(*AI);
3244 }
3245 }
3246 }
3247
3248 if (FT->getReturnType() == Type::VoidTy)
3249 Caller->setName(""); // Void type should not have a name...
3250
3251 Instruction *NC;
3252 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003253 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003254 Args, Caller->getName(), Caller);
3255 } else {
3256 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3257 }
3258
3259 // Insert a cast of the return type as necessary...
3260 Value *NV = NC;
3261 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3262 if (NV->getType() != Type::VoidTy) {
3263 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003264
3265 // If this is an invoke instruction, we should insert it after the first
3266 // non-phi, instruction in the normal successor block.
3267 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3268 BasicBlock::iterator I = II->getNormalDest()->begin();
3269 while (isa<PHINode>(I)) ++I;
3270 InsertNewInstBefore(NC, *I);
3271 } else {
3272 // Otherwise, it's a call, just insert cast right after the call instr
3273 InsertNewInstBefore(NC, *Caller);
3274 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003275 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003276 } else {
3277 NV = Constant::getNullValue(Caller->getType());
3278 }
3279 }
3280
3281 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3282 Caller->replaceAllUsesWith(NV);
3283 Caller->getParent()->getInstList().erase(Caller);
3284 removeFromWorkList(Caller);
3285 return true;
3286}
3287
3288
Chris Lattner48a44f72002-05-02 17:06:02 +00003289
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003290// PHINode simplification
3291//
Chris Lattner113f4f42002-06-25 16:13:24 +00003292Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00003293 if (Value *V = hasConstantValue(&PN))
3294 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00003295
3296 // If the only user of this instruction is a cast instruction, and all of the
3297 // incoming values are constants, change this PHI to merge together the casted
3298 // constants.
3299 if (PN.hasOneUse())
3300 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3301 if (CI->getType() != PN.getType()) { // noop casts will be folded
3302 bool AllConstant = true;
3303 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3304 if (!isa<Constant>(PN.getIncomingValue(i))) {
3305 AllConstant = false;
3306 break;
3307 }
3308 if (AllConstant) {
3309 // Make a new PHI with all casted values.
3310 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3311 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3312 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3313 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3314 PN.getIncomingBlock(i));
3315 }
3316
3317 // Update the cast instruction.
3318 CI->setOperand(0, New);
3319 WorkList.push_back(CI); // revisit the cast instruction to fold.
3320 WorkList.push_back(New); // Make sure to revisit the new Phi
3321 return &PN; // PN is now dead!
3322 }
3323 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003324 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003325}
3326
Chris Lattner69193f92004-04-05 01:30:19 +00003327static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3328 Instruction *InsertPoint,
3329 InstCombiner *IC) {
3330 unsigned PS = IC->getTargetData().getPointerSize();
3331 const Type *VTy = V->getType();
3332 Instruction *Cast;
3333 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3334 // We must insert a cast to ensure we sign-extend.
3335 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3336 V->getName()), *InsertPoint);
3337 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3338 *InsertPoint);
3339}
3340
Chris Lattner48a44f72002-05-02 17:06:02 +00003341
Chris Lattner113f4f42002-06-25 16:13:24 +00003342Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003343 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003344 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003345 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003346 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003347 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003348
3349 bool HasZeroPointerIndex = false;
3350 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3351 HasZeroPointerIndex = C->isNullValue();
3352
3353 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003354 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003355
Chris Lattner69193f92004-04-05 01:30:19 +00003356 // Eliminate unneeded casts for indices.
3357 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003358 gep_type_iterator GTI = gep_type_begin(GEP);
3359 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3360 if (isa<SequentialType>(*GTI)) {
3361 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3362 Value *Src = CI->getOperand(0);
3363 const Type *SrcTy = Src->getType();
3364 const Type *DestTy = CI->getType();
3365 if (Src->getType()->isInteger()) {
3366 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3367 // We can always eliminate a cast from ulong or long to the other.
3368 // We can always eliminate a cast from uint to int or the other on
3369 // 32-bit pointer platforms.
3370 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3371 MadeChange = true;
3372 GEP.setOperand(i, Src);
3373 }
3374 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3375 SrcTy->getPrimitiveSize() == 4) {
3376 // We can always eliminate a cast from int to [u]long. We can
3377 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3378 // pointer target.
3379 if (SrcTy->isSigned() ||
3380 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3381 MadeChange = true;
3382 GEP.setOperand(i, Src);
3383 }
Chris Lattner69193f92004-04-05 01:30:19 +00003384 }
3385 }
3386 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003387 // If we are using a wider index than needed for this platform, shrink it
3388 // to what we need. If the incoming value needs a cast instruction,
3389 // insert it. This explicit cast can make subsequent optimizations more
3390 // obvious.
3391 Value *Op = GEP.getOperand(i);
3392 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003393 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003394 GEP.setOperand(i, ConstantExpr::getCast(C,
3395 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003396 MadeChange = true;
3397 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003398 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3399 Op->getName()), GEP);
3400 GEP.setOperand(i, Op);
3401 MadeChange = true;
3402 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003403
3404 // If this is a constant idx, make sure to canonicalize it to be a signed
3405 // operand, otherwise CSE and other optimizations are pessimized.
3406 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3407 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3408 CUI->getType()->getSignedVersion()));
3409 MadeChange = true;
3410 }
Chris Lattner69193f92004-04-05 01:30:19 +00003411 }
3412 if (MadeChange) return &GEP;
3413
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003414 // Combine Indices - If the source pointer to this getelementptr instruction
3415 // is a getelementptr instruction, combine the indices of the two
3416 // getelementptr instructions into a single instruction.
3417 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003418 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003419 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003420 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003421 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003422 if (CE->getOpcode() == Instruction::GetElementPtr)
3423 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3424 }
3425
3426 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003427 // Note that if our source is a gep chain itself that we wait for that
3428 // chain to be resolved before we perform this transformation. This
3429 // avoids us creating a TON of code in some cases.
3430 //
3431 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3432 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3433 return 0; // Wait until our source is folded to completion.
3434
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003435 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003436
3437 // Find out whether the last index in the source GEP is a sequential idx.
3438 bool EndsWithSequential = false;
3439 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3440 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003441 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003442
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003443 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003444 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003445 // Replace: gep (gep %P, long B), long A, ...
3446 // With: T = long A+B; gep %P, T, ...
3447 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003448 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003449 if (SO1 == Constant::getNullValue(SO1->getType())) {
3450 Sum = GO1;
3451 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3452 Sum = SO1;
3453 } else {
3454 // If they aren't the same type, convert both to an integer of the
3455 // target's pointer size.
3456 if (SO1->getType() != GO1->getType()) {
3457 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3458 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3459 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3460 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3461 } else {
3462 unsigned PS = TD->getPointerSize();
3463 Instruction *Cast;
3464 if (SO1->getType()->getPrimitiveSize() == PS) {
3465 // Convert GO1 to SO1's type.
3466 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3467
3468 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3469 // Convert SO1 to GO1's type.
3470 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3471 } else {
3472 const Type *PT = TD->getIntPtrType();
3473 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3474 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3475 }
3476 }
3477 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003478 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3479 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3480 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003481 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3482 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003483 }
Chris Lattner69193f92004-04-05 01:30:19 +00003484 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003485
3486 // Recycle the GEP we already have if possible.
3487 if (SrcGEPOperands.size() == 2) {
3488 GEP.setOperand(0, SrcGEPOperands[0]);
3489 GEP.setOperand(1, Sum);
3490 return &GEP;
3491 } else {
3492 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3493 SrcGEPOperands.end()-1);
3494 Indices.push_back(Sum);
3495 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3496 }
Chris Lattner69193f92004-04-05 01:30:19 +00003497 } else if (isa<Constant>(*GEP.idx_begin()) &&
3498 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003499 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003500 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003501 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3502 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003503 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3504 }
3505
3506 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003507 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003508
Chris Lattner5f667a62004-05-07 22:09:22 +00003509 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003510 // GEP of global variable. If all of the indices for this GEP are
3511 // constants, we can promote this to a constexpr instead of an instruction.
3512
3513 // Scan for nonconstants...
3514 std::vector<Constant*> Indices;
3515 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3516 for (; I != E && isa<Constant>(*I); ++I)
3517 Indices.push_back(cast<Constant>(*I));
3518
3519 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003520 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003521
3522 // Replace all uses of the GEP with the new constexpr...
3523 return ReplaceInstUsesWith(GEP, CE);
3524 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003525 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003526 if (CE->getOpcode() == Instruction::Cast) {
3527 if (HasZeroPointerIndex) {
3528 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3529 // into : GEP [10 x ubyte]* X, long 0, ...
3530 //
3531 // This occurs when the program declares an array extern like "int X[];"
3532 //
3533 Constant *X = CE->getOperand(0);
3534 const PointerType *CPTy = cast<PointerType>(CE->getType());
3535 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3536 if (const ArrayType *XATy =
3537 dyn_cast<ArrayType>(XTy->getElementType()))
3538 if (const ArrayType *CATy =
3539 dyn_cast<ArrayType>(CPTy->getElementType()))
3540 if (CATy->getElementType() == XATy->getElementType()) {
3541 // At this point, we know that the cast source type is a pointer
3542 // to an array of the same type as the destination pointer
3543 // array. Because the array type is never stepped over (there
3544 // is a leading zero) we can fold the cast into this GEP.
3545 GEP.setOperand(0, X);
3546 return &GEP;
3547 }
3548 }
3549 }
Chris Lattnerca081252001-12-14 16:52:21 +00003550 }
3551
Chris Lattnerca081252001-12-14 16:52:21 +00003552 return 0;
3553}
3554
Chris Lattner1085bdf2002-11-04 16:18:53 +00003555Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3556 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3557 if (AI.isArrayAllocation()) // Check C != 1
3558 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3559 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003560 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003561
3562 // Create and insert the replacement instruction...
3563 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003564 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003565 else {
3566 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003567 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003568 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003569
3570 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003571
3572 // Scan to the end of the allocation instructions, to skip over a block of
3573 // allocas if possible...
3574 //
3575 BasicBlock::iterator It = New;
3576 while (isa<AllocationInst>(*It)) ++It;
3577
3578 // Now that I is pointing to the first non-allocation-inst in the block,
3579 // insert our getelementptr instruction...
3580 //
Chris Lattner69193f92004-04-05 01:30:19 +00003581 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003582 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3583
3584 // Now make everything use the getelementptr instead of the original
3585 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003586 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003587 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003588
3589 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3590 // Note that we only do this for alloca's, because malloc should allocate and
3591 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003592 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3593 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003594 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3595
Chris Lattner1085bdf2002-11-04 16:18:53 +00003596 return 0;
3597}
3598
Chris Lattner8427bff2003-12-07 01:24:23 +00003599Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3600 Value *Op = FI.getOperand(0);
3601
3602 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3603 if (CastInst *CI = dyn_cast<CastInst>(Op))
3604 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3605 FI.setOperand(0, CI->getOperand(0));
3606 return &FI;
3607 }
3608
Chris Lattnerf3a36602004-02-28 04:57:37 +00003609 // If we have 'free null' delete the instruction. This can happen in stl code
3610 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00003611 if (isa<ConstantPointerNull>(Op))
3612 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003613
Chris Lattner8427bff2003-12-07 01:24:23 +00003614 return 0;
3615}
3616
3617
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003618/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3619/// constantexpr, return the constant value being addressed by the constant
3620/// expression, or null if something is funny.
3621///
3622static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003623 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003624 return 0; // Do not allow stepping over the value!
3625
3626 // Loop over all of the operands, tracking down which value we are
3627 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003628 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3629 for (++I; I != E; ++I)
3630 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3631 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3632 assert(CU->getValue() < STy->getNumElements() &&
3633 "Struct index out of range!");
3634 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003635 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003636 } else if (isa<ConstantAggregateZero>(C)) {
3637 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3638 } else {
3639 return 0;
3640 }
3641 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3642 const ArrayType *ATy = cast<ArrayType>(*I);
3643 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3644 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003645 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003646 else if (isa<ConstantAggregateZero>(C))
3647 C = Constant::getNullValue(ATy->getElementType());
3648 else
3649 return 0;
3650 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003651 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003652 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003653 return C;
3654}
3655
Chris Lattner35e24772004-07-13 01:49:43 +00003656static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3657 User *CI = cast<User>(LI.getOperand(0));
3658
3659 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3660 if (const PointerType *SrcTy =
3661 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3662 const Type *SrcPTy = SrcTy->getElementType();
3663 if (SrcPTy->isSized() && DestPTy->isSized() &&
3664 IC.getTargetData().getTypeSize(SrcPTy) ==
3665 IC.getTargetData().getTypeSize(DestPTy) &&
3666 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3667 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3668 // Okay, we are casting from one integer or pointer type to another of
3669 // the same size. Instead of casting the pointer before the load, cast
3670 // the result of the loaded value.
3671 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003672 CI->getName(),
3673 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003674 // Now cast the result of the load.
3675 return new CastInst(NewLoad, LI.getType());
3676 }
3677 }
3678 return 0;
3679}
3680
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003681/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003682/// from this value cannot trap. If it is not obviously safe to load from the
3683/// specified pointer, we do a quick local scan of the basic block containing
3684/// ScanFrom, to determine if the address is already accessed.
3685static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3686 // If it is an alloca or global variable, it is always safe to load from.
3687 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3688
3689 // Otherwise, be a little bit agressive by scanning the local block where we
3690 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003691 // from/to. If so, the previous load or store would have already trapped,
3692 // so there is no harm doing an extra load (also, CSE will later eliminate
3693 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003694 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3695
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003696 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003697 --BBI;
3698
3699 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3700 if (LI->getOperand(0) == V) return true;
3701 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3702 if (SI->getOperand(1) == V) return true;
3703
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003704 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003705 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003706}
3707
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003708Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3709 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003710
Chris Lattner6679e462004-04-14 03:28:36 +00003711 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003712 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattner6679e462004-04-14 03:28:36 +00003713 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003714
3715 // Instcombine load (constant global) into the value loaded...
3716 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00003717 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003718 return ReplaceInstUsesWith(LI, GV->getInitializer());
3719
3720 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3721 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattner35e24772004-07-13 01:49:43 +00003722 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer87436872004-07-18 00:38:32 +00003723 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3724 if (GV->isConstant() && !GV->isExternal())
3725 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3726 return ReplaceInstUsesWith(LI, V);
Chris Lattner35e24772004-07-13 01:49:43 +00003727 } else if (CE->getOpcode() == Instruction::Cast) {
3728 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3729 return Res;
3730 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003731
3732 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003733 if (CastInst *CI = dyn_cast<CastInst>(Op))
3734 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3735 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003736
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003737 if (!LI.isVolatile() && Op->hasOneUse()) {
3738 // Change select and PHI nodes to select values instead of addresses: this
3739 // helps alias analysis out a lot, allows many others simplifications, and
3740 // exposes redundancy in the code.
3741 //
3742 // Note that we cannot do the transformation unless we know that the
3743 // introduced loads cannot trap! Something like this is valid as long as
3744 // the condition is always false: load (select bool %C, int* null, int* %G),
3745 // but it would not be valid if we transformed it to load from null
3746 // unconditionally.
3747 //
3748 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3749 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003750 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3751 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003752 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003753 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003754 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003755 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003756 return new SelectInst(SI->getCondition(), V1, V2);
3757 }
3758
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003759 // load (select (cond, null, P)) -> load P
3760 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3761 if (C->isNullValue()) {
3762 LI.setOperand(0, SI->getOperand(2));
3763 return &LI;
3764 }
3765
3766 // load (select (cond, P, null)) -> load P
3767 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3768 if (C->isNullValue()) {
3769 LI.setOperand(0, SI->getOperand(1));
3770 return &LI;
3771 }
3772
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003773 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3774 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003775 bool Safe = PN->getParent() == LI.getParent();
3776
3777 // Scan all of the instructions between the PHI and the load to make
3778 // sure there are no instructions that might possibly alter the value
3779 // loaded from the PHI.
3780 if (Safe) {
3781 BasicBlock::iterator I = &LI;
3782 for (--I; !isa<PHINode>(I); --I)
3783 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3784 Safe = false;
3785 break;
3786 }
3787 }
3788
3789 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003790 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003791 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003792 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003793
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003794 if (Safe) {
3795 // Create the PHI.
3796 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3797 InsertNewInstBefore(NewPN, *PN);
3798 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3799
3800 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3801 BasicBlock *BB = PN->getIncomingBlock(i);
3802 Value *&TheLoad = LoadMap[BB];
3803 if (TheLoad == 0) {
3804 Value *InVal = PN->getIncomingValue(i);
3805 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3806 InVal->getName()+".val"),
3807 *BB->getTerminator());
3808 }
3809 NewPN->addIncoming(TheLoad, BB);
3810 }
3811 return ReplaceInstUsesWith(LI, NewPN);
3812 }
3813 }
3814 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003815 return 0;
3816}
3817
3818
Chris Lattner9eef8a72003-06-04 04:46:00 +00003819Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3820 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003821 Value *X;
3822 BasicBlock *TrueDest;
3823 BasicBlock *FalseDest;
3824 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3825 !isa<Constant>(X)) {
3826 // Swap Destinations and condition...
3827 BI.setCondition(X);
3828 BI.setSuccessor(0, FalseDest);
3829 BI.setSuccessor(1, TrueDest);
3830 return &BI;
3831 }
3832
3833 // Cannonicalize setne -> seteq
3834 Instruction::BinaryOps Op; Value *Y;
3835 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3836 TrueDest, FalseDest)))
3837 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3838 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3839 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3840 std::string Name = I->getName(); I->setName("");
3841 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3842 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003843 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003844 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003845 BI.setSuccessor(0, FalseDest);
3846 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003847 removeFromWorkList(I);
3848 I->getParent()->getInstList().erase(I);
3849 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003850 return &BI;
3851 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003852
Chris Lattner9eef8a72003-06-04 04:46:00 +00003853 return 0;
3854}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003855
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003856Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3857 Value *Cond = SI.getCondition();
3858 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3859 if (I->getOpcode() == Instruction::Add)
3860 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3861 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3862 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3863 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3864 AddRHS));
3865 SI.setOperand(0, I->getOperand(0));
3866 WorkList.push_back(I);
3867 return &SI;
3868 }
3869 }
3870 return 0;
3871}
3872
Chris Lattnerca081252001-12-14 16:52:21 +00003873
Chris Lattner99f48c62002-09-02 04:59:56 +00003874void InstCombiner::removeFromWorkList(Instruction *I) {
3875 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3876 WorkList.end());
3877}
3878
Chris Lattner113f4f42002-06-25 16:13:24 +00003879bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003880 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003881 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003882
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003883 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3884 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003885
Chris Lattnerca081252001-12-14 16:52:21 +00003886
3887 while (!WorkList.empty()) {
3888 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3889 WorkList.pop_back();
3890
Misha Brukman632df282002-10-29 23:06:16 +00003891 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003892 // Check to see if we can DIE the instruction...
3893 if (isInstructionTriviallyDead(I)) {
3894 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003895 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003896 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003897 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003898
3899 I->getParent()->getInstList().erase(I);
3900 removeFromWorkList(I);
3901 continue;
3902 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003903
Misha Brukman632df282002-10-29 23:06:16 +00003904 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003905 if (Constant *C = ConstantFoldInstruction(I)) {
3906 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003907 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003908 ReplaceInstUsesWith(*I, C);
3909
Chris Lattner99f48c62002-09-02 04:59:56 +00003910 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003911 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003912 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003913 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003914 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003915
Chris Lattnerca081252001-12-14 16:52:21 +00003916 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003917 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003918 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003919 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003920 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003921 DEBUG(std::cerr << "IC: Old = " << *I
3922 << " New = " << *Result);
3923
Chris Lattner396dbfe2004-06-09 05:08:07 +00003924 // Everything uses the new instruction now.
3925 I->replaceAllUsesWith(Result);
3926
3927 // Push the new instruction and any users onto the worklist.
3928 WorkList.push_back(Result);
3929 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003930
3931 // Move the name to the new instruction first...
3932 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003933 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003934
3935 // Insert the new instruction into the basic block...
3936 BasicBlock *InstParent = I->getParent();
3937 InstParent->getInstList().insert(I, Result);
3938
Chris Lattner63d75af2004-05-01 23:27:23 +00003939 // Make sure that we reprocess all operands now that we reduced their
3940 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003941 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3942 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3943 WorkList.push_back(OpI);
3944
Chris Lattner396dbfe2004-06-09 05:08:07 +00003945 // Instructions can end up on the worklist more than once. Make sure
3946 // we do not process an instruction that has been deleted.
3947 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003948
3949 // Erase the old instruction.
3950 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003951 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003952 DEBUG(std::cerr << "IC: MOD = " << *I);
3953
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003954 // If the instruction was modified, it's possible that it is now dead.
3955 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003956 if (isInstructionTriviallyDead(I)) {
3957 // Make sure we process all operands now that we are reducing their
3958 // use counts.
3959 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3960 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3961 WorkList.push_back(OpI);
3962
3963 // Instructions may end up in the worklist more than once. Erase all
3964 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003965 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003966 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003967 } else {
3968 WorkList.push_back(Result);
3969 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003970 }
Chris Lattner053c0932002-05-14 15:24:07 +00003971 }
Chris Lattner260ab202002-04-18 17:39:14 +00003972 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003973 }
3974 }
3975
Chris Lattner260ab202002-04-18 17:39:14 +00003976 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003977}
3978
Brian Gaeke38b79e82004-07-27 17:43:21 +00003979FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003980 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003981}
Brian Gaeke960707c2003-11-11 22:41:34 +00003982