blob: 5b477b3a409753f54477002f81fa830c95f16527 [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
949 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
950 if (Instruction *NV = FoldOpIntoPhi(I))
951 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000952 }
953
954 // 0 / X == 0, we don't need to preserve faults!
955 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
956 if (LHS->equalsInt(0))
957 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
958
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000959 return 0;
960}
961
962
Chris Lattner113f4f42002-06-25 16:13:24 +0000963Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000964 if (I.getType()->isSigned())
965 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000966 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000967 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000968 // X % -Y -> X % Y
969 AddUsesToWorkList(I);
970 I.setOperand(1, RHSNeg);
971 return &I;
972 }
973
Chris Lattner3082c5a2003-02-18 19:28:33 +0000974 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
975 if (RHS->equalsInt(1)) // X % 1 == 0
976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
977
978 // Check to see if this is an unsigned remainder with an exact power of 2,
979 // if so, convert to a bitwise and.
980 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
981 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000982 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000983 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000984 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000985 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
986 if (Instruction *NV = FoldOpIntoPhi(I))
987 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000988 }
989
990 // 0 % X == 0, we don't need to preserve faults!
991 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
992 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000993 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
994
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000995 return 0;
996}
997
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000998// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000999static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001000 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1001 // Calculate -1 casted to the right type...
1002 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1003 uint64_t Val = ~0ULL; // All ones
1004 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1005 return CU->getValue() == Val-1;
1006 }
1007
1008 const ConstantSInt *CS = cast<ConstantSInt>(C);
1009
1010 // Calculate 0111111111..11111
1011 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1012 int64_t Val = INT64_MAX; // All ones
1013 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1014 return CS->getValue() == Val-1;
1015}
1016
1017// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001018static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001019 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1020 return CU->getValue() == 1;
1021
1022 const ConstantSInt *CS = cast<ConstantSInt>(C);
1023
1024 // Calculate 1111111111000000000000
1025 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1026 int64_t Val = -1; // All ones
1027 Val <<= TypeBits-1; // Shift over to the right spot
1028 return CS->getValue() == Val+1;
1029}
1030
Chris Lattner35167c32004-06-09 07:59:58 +00001031// isOneBitSet - Return true if there is exactly one bit set in the specified
1032// constant.
1033static bool isOneBitSet(const ConstantInt *CI) {
1034 uint64_t V = CI->getRawValue();
1035 return V && (V & (V-1)) == 0;
1036}
1037
Chris Lattner8fc5af42004-09-23 21:46:38 +00001038#if 0 // Currently unused
1039// isLowOnes - Return true if the constant is of the form 0+1+.
1040static bool isLowOnes(const ConstantInt *CI) {
1041 uint64_t V = CI->getRawValue();
1042
1043 // There won't be bits set in parts that the type doesn't contain.
1044 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1045
1046 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1047 return U && V && (U & V) == 0;
1048}
1049#endif
1050
1051// isHighOnes - Return true if the constant is of the form 1+0+.
1052// This is the same as lowones(~X).
1053static bool isHighOnes(const ConstantInt *CI) {
1054 uint64_t V = ~CI->getRawValue();
1055
1056 // There won't be bits set in parts that the type doesn't contain.
1057 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1058
1059 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1060 return U && V && (U & V) == 0;
1061}
1062
1063
Chris Lattner3ac7c262003-08-13 20:16:26 +00001064/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1065/// are carefully arranged to allow folding of expressions such as:
1066///
1067/// (A < B) | (A > B) --> (A != B)
1068///
1069/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1070/// represents that the comparison is true if A == B, and bit value '1' is true
1071/// if A < B.
1072///
1073static unsigned getSetCondCode(const SetCondInst *SCI) {
1074 switch (SCI->getOpcode()) {
1075 // False -> 0
1076 case Instruction::SetGT: return 1;
1077 case Instruction::SetEQ: return 2;
1078 case Instruction::SetGE: return 3;
1079 case Instruction::SetLT: return 4;
1080 case Instruction::SetNE: return 5;
1081 case Instruction::SetLE: return 6;
1082 // True -> 7
1083 default:
1084 assert(0 && "Invalid SetCC opcode!");
1085 return 0;
1086 }
1087}
1088
1089/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1090/// opcode and two operands into either a constant true or false, or a brand new
1091/// SetCC instruction.
1092static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1093 switch (Opcode) {
1094 case 0: return ConstantBool::False;
1095 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1096 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1097 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1098 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1099 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1100 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1101 case 7: return ConstantBool::True;
1102 default: assert(0 && "Illegal SetCCCode!"); return 0;
1103 }
1104}
1105
1106// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1107struct FoldSetCCLogical {
1108 InstCombiner &IC;
1109 Value *LHS, *RHS;
1110 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1111 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1112 bool shouldApply(Value *V) const {
1113 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1114 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1115 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1116 return false;
1117 }
1118 Instruction *apply(BinaryOperator &Log) const {
1119 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1120 if (SCI->getOperand(0) != LHS) {
1121 assert(SCI->getOperand(1) == LHS);
1122 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1123 }
1124
1125 unsigned LHSCode = getSetCondCode(SCI);
1126 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1127 unsigned Code;
1128 switch (Log.getOpcode()) {
1129 case Instruction::And: Code = LHSCode & RHSCode; break;
1130 case Instruction::Or: Code = LHSCode | RHSCode; break;
1131 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001132 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001133 }
1134
1135 Value *RV = getSetCCValue(Code, LHS, RHS);
1136 if (Instruction *I = dyn_cast<Instruction>(RV))
1137 return I;
1138 // Otherwise, it's a constant boolean value...
1139 return IC.ReplaceInstUsesWith(Log, RV);
1140 }
1141};
1142
1143
Chris Lattnerba1cb382003-09-19 17:17:26 +00001144// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1145// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1146// guaranteed to be either a shift instruction or a binary operator.
1147Instruction *InstCombiner::OptAndOp(Instruction *Op,
1148 ConstantIntegral *OpRHS,
1149 ConstantIntegral *AndRHS,
1150 BinaryOperator &TheAnd) {
1151 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001152 Constant *Together = 0;
1153 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001154 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001155
Chris Lattnerba1cb382003-09-19 17:17:26 +00001156 switch (Op->getOpcode()) {
1157 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001158 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001159 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001160 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001161 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001162 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1163 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001164 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001165 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001166 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001167 }
1168 break;
1169 case Instruction::Or:
1170 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001171 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001172 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001173 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001174 if (Together == AndRHS) // (X | C) & C --> C
1175 return ReplaceInstUsesWith(TheAnd, AndRHS);
1176
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001177 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001178 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1179 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001180 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001181 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001182 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001183 }
1184 }
1185 break;
1186 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001187 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001188 // Adding a one to a single bit bit-field should be turned into an XOR
1189 // of the bit. First thing to check is to see if this AND is with a
1190 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001191 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001192
1193 // Clear bits that are not part of the constant.
1194 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1195
1196 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001197 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001198 // Ok, at this point, we know that we are masking the result of the
1199 // ADD down to exactly one bit. If the constant we are adding has
1200 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001201 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001202
1203 // Check to see if any bits below the one bit set in AndRHSV are set.
1204 if ((AddRHS & (AndRHSV-1)) == 0) {
1205 // If not, the only thing that can effect the output of the AND is
1206 // the bit specified by AndRHSV. If that bit is set, the effect of
1207 // the XOR is to toggle the bit. If it is clear, then the ADD has
1208 // no effect.
1209 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1210 TheAnd.setOperand(0, X);
1211 return &TheAnd;
1212 } else {
1213 std::string Name = Op->getName(); Op->setName("");
1214 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001215 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001216 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001217 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001218 }
1219 }
1220 }
1221 }
1222 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001223
1224 case Instruction::Shl: {
1225 // We know that the AND will not produce any of the bits shifted in, so if
1226 // the anded constant includes them, clear them now!
1227 //
1228 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001229 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1230 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1231
1232 if (CI == ShlMask) { // Masking out bits that the shift already masks
1233 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1234 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001235 TheAnd.setOperand(1, CI);
1236 return &TheAnd;
1237 }
1238 break;
1239 }
1240 case Instruction::Shr:
1241 // We know that the AND will not produce any of the bits shifted in, so if
1242 // the anded constant includes them, clear them now! This only applies to
1243 // unsigned shifts, because a signed shr may bring in set bits!
1244 //
1245 if (AndRHS->getType()->isUnsigned()) {
1246 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001247 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1248 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1249
1250 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1251 return ReplaceInstUsesWith(TheAnd, Op);
1252 } else if (CI != AndRHS) {
1253 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001254 return &TheAnd;
1255 }
Chris Lattner7e794272004-09-24 15:21:34 +00001256 } else { // Signed shr.
1257 // See if this is shifting in some sign extension, then masking it out
1258 // with an and.
1259 if (Op->hasOneUse()) {
1260 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1261 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1262 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1263 if (CI == ShrMask) { // Masking out bits shifted in.
1264 // Make the argument unsigned.
1265 Value *ShVal = Op->getOperand(0);
1266 ShVal = InsertCastBefore(ShVal,
1267 ShVal->getType()->getUnsignedVersion(),
1268 TheAnd);
1269 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1270 OpRHS, Op->getName()),
1271 TheAnd);
1272 return new CastInst(ShVal, Op->getType());
1273 }
1274 }
Chris Lattner2da29172003-09-19 19:05:02 +00001275 }
1276 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001277 }
1278 return 0;
1279}
1280
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001281
Chris Lattner6862fbd2004-09-29 17:40:11 +00001282/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1283/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1284/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1285/// insert new instructions.
1286Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1287 bool Inside, Instruction &IB) {
1288 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1289 "Lo is not <= Hi in range emission code!");
1290 if (Inside) {
1291 if (Lo == Hi) // Trivially false.
1292 return new SetCondInst(Instruction::SetNE, V, V);
1293 if (cast<ConstantIntegral>(Lo)->isMinValue())
1294 return new SetCondInst(Instruction::SetLT, V, Hi);
1295
1296 Constant *AddCST = ConstantExpr::getNeg(Lo);
1297 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1298 InsertNewInstBefore(Add, IB);
1299 // Convert to unsigned for the comparison.
1300 const Type *UnsType = Add->getType()->getUnsignedVersion();
1301 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1302 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1303 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1304 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1305 }
1306
1307 if (Lo == Hi) // Trivially true.
1308 return new SetCondInst(Instruction::SetEQ, V, V);
1309
1310 Hi = SubOne(cast<ConstantInt>(Hi));
1311 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1312 return new SetCondInst(Instruction::SetGT, V, Hi);
1313
1314 // Emit X-Lo > Hi-Lo-1
1315 Constant *AddCST = ConstantExpr::getNeg(Lo);
1316 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1317 InsertNewInstBefore(Add, IB);
1318 // Convert to unsigned for the comparison.
1319 const Type *UnsType = Add->getType()->getUnsignedVersion();
1320 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1321 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1322 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1323 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1324}
1325
1326
Chris Lattner113f4f42002-06-25 16:13:24 +00001327Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001328 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001329 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001330
1331 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001332 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1333 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001334
1335 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001336 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001337 if (RHS->isAllOnesValue())
1338 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001339
Chris Lattnerba1cb382003-09-19 17:17:26 +00001340 // Optimize a variety of ((val OP C1) & C2) combinations...
1341 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1342 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001343 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001344 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001345 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1346 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001347 }
Chris Lattner183b3362004-04-09 19:05:30 +00001348
1349 // Try to fold constant and into select arguments.
1350 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1351 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1352 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001353 if (isa<PHINode>(Op0))
1354 if (Instruction *NV = FoldOpIntoPhi(I))
1355 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001356 }
1357
Chris Lattnerbb74e222003-03-10 23:06:50 +00001358 Value *Op0NotVal = dyn_castNotVal(Op0);
1359 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001360
Chris Lattner023a4832004-06-18 06:07:51 +00001361 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1362 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1363
Misha Brukman9c003d82004-07-30 12:50:08 +00001364 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001365 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001366 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1367 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001368 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001369 return BinaryOperator::createNot(Or);
1370 }
1371
Chris Lattner623826c2004-09-28 21:48:02 +00001372 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1373 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001374 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1375 return R;
1376
Chris Lattner623826c2004-09-28 21:48:02 +00001377 Value *LHSVal, *RHSVal;
1378 ConstantInt *LHSCst, *RHSCst;
1379 Instruction::BinaryOps LHSCC, RHSCC;
1380 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1381 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1382 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1383 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1384 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1385 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1386 // Ensure that the larger constant is on the RHS.
1387 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1388 SetCondInst *LHS = cast<SetCondInst>(Op0);
1389 if (cast<ConstantBool>(Cmp)->getValue()) {
1390 std::swap(LHS, RHS);
1391 std::swap(LHSCst, RHSCst);
1392 std::swap(LHSCC, RHSCC);
1393 }
1394
1395 // At this point, we know we have have two setcc instructions
1396 // comparing a value against two constants and and'ing the result
1397 // together. Because of the above check, we know that we only have
1398 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1399 // FoldSetCCLogical check above), that the two constants are not
1400 // equal.
1401 assert(LHSCst != RHSCst && "Compares not folded above?");
1402
1403 switch (LHSCC) {
1404 default: assert(0 && "Unknown integer condition code!");
1405 case Instruction::SetEQ:
1406 switch (RHSCC) {
1407 default: assert(0 && "Unknown integer condition code!");
1408 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1409 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1410 return ReplaceInstUsesWith(I, ConstantBool::False);
1411 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1412 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1413 return ReplaceInstUsesWith(I, LHS);
1414 }
1415 case Instruction::SetNE:
1416 switch (RHSCC) {
1417 default: assert(0 && "Unknown integer condition code!");
1418 case Instruction::SetLT:
1419 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1420 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1421 break; // (X != 13 & X < 15) -> no change
1422 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1423 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1424 return ReplaceInstUsesWith(I, RHS);
1425 case Instruction::SetNE:
1426 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1427 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1428 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1429 LHSVal->getName()+".off");
1430 InsertNewInstBefore(Add, I);
1431 const Type *UnsType = Add->getType()->getUnsignedVersion();
1432 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1433 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1434 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1435 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1436 }
1437 break; // (X != 13 & X != 15) -> no change
1438 }
1439 break;
1440 case Instruction::SetLT:
1441 switch (RHSCC) {
1442 default: assert(0 && "Unknown integer condition code!");
1443 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1444 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1445 return ReplaceInstUsesWith(I, ConstantBool::False);
1446 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1447 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1448 return ReplaceInstUsesWith(I, LHS);
1449 }
1450 case Instruction::SetGT:
1451 switch (RHSCC) {
1452 default: assert(0 && "Unknown integer condition code!");
1453 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1454 return ReplaceInstUsesWith(I, LHS);
1455 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1456 return ReplaceInstUsesWith(I, RHS);
1457 case Instruction::SetNE:
1458 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1459 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1460 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001461 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1462 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001463 }
1464 }
1465 }
1466 }
1467
Chris Lattner113f4f42002-06-25 16:13:24 +00001468 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001469}
1470
Chris Lattner113f4f42002-06-25 16:13:24 +00001471Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001472 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001473 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001474
1475 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001476 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1477 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001478
1479 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001480 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001481 if (RHS->isAllOnesValue())
1482 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001483
Chris Lattnerd4252a72004-07-30 07:50:03 +00001484 ConstantInt *C1; Value *X;
1485 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1486 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1487 std::string Op0Name = Op0->getName(); Op0->setName("");
1488 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1489 InsertNewInstBefore(Or, I);
1490 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1491 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001492
Chris Lattnerd4252a72004-07-30 07:50:03 +00001493 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1494 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1495 std::string Op0Name = Op0->getName(); Op0->setName("");
1496 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1497 InsertNewInstBefore(Or, I);
1498 return BinaryOperator::createXor(Or,
1499 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001500 }
Chris Lattner183b3362004-04-09 19:05:30 +00001501
1502 // Try to fold constant and into select arguments.
1503 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1504 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1505 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001506 if (isa<PHINode>(Op0))
1507 if (Instruction *NV = FoldOpIntoPhi(I))
1508 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001509 }
1510
Chris Lattner812aab72003-08-12 19:11:07 +00001511 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001512 Value *A, *B; ConstantInt *C1, *C2;
1513 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1514 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1515 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001516
Chris Lattnerd4252a72004-07-30 07:50:03 +00001517 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1518 if (A == Op1) // ~A | A == -1
1519 return ReplaceInstUsesWith(I,
1520 ConstantIntegral::getAllOnesValue(I.getType()));
1521 } else {
1522 A = 0;
1523 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001524
Chris Lattnerd4252a72004-07-30 07:50:03 +00001525 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1526 if (Op0 == B)
1527 return ReplaceInstUsesWith(I,
1528 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001529
Misha Brukman9c003d82004-07-30 12:50:08 +00001530 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001531 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1532 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1533 I.getName()+".demorgan"), I);
1534 return BinaryOperator::createNot(And);
1535 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001536 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001537
Chris Lattner3ac7c262003-08-13 20:16:26 +00001538 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001539 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001540 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1541 return R;
1542
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001543 Value *LHSVal, *RHSVal;
1544 ConstantInt *LHSCst, *RHSCst;
1545 Instruction::BinaryOps LHSCC, RHSCC;
1546 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1547 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1548 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1549 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1550 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1551 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1552 // Ensure that the larger constant is on the RHS.
1553 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1554 SetCondInst *LHS = cast<SetCondInst>(Op0);
1555 if (cast<ConstantBool>(Cmp)->getValue()) {
1556 std::swap(LHS, RHS);
1557 std::swap(LHSCst, RHSCst);
1558 std::swap(LHSCC, RHSCC);
1559 }
1560
1561 // At this point, we know we have have two setcc instructions
1562 // comparing a value against two constants and or'ing the result
1563 // together. Because of the above check, we know that we only have
1564 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1565 // FoldSetCCLogical check above), that the two constants are not
1566 // equal.
1567 assert(LHSCst != RHSCst && "Compares not folded above?");
1568
1569 switch (LHSCC) {
1570 default: assert(0 && "Unknown integer condition code!");
1571 case Instruction::SetEQ:
1572 switch (RHSCC) {
1573 default: assert(0 && "Unknown integer condition code!");
1574 case Instruction::SetEQ:
1575 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1576 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1577 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1578 LHSVal->getName()+".off");
1579 InsertNewInstBefore(Add, I);
1580 const Type *UnsType = Add->getType()->getUnsignedVersion();
1581 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1582 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1583 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1584 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1585 }
1586 break; // (X == 13 | X == 15) -> no change
1587
1588 case Instruction::SetGT:
1589 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1590 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1591 break; // (X == 13 | X > 15) -> no change
1592 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1593 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1594 return ReplaceInstUsesWith(I, RHS);
1595 }
1596 break;
1597 case Instruction::SetNE:
1598 switch (RHSCC) {
1599 default: assert(0 && "Unknown integer condition code!");
1600 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1601 return ReplaceInstUsesWith(I, RHS);
1602 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1603 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1604 return ReplaceInstUsesWith(I, LHS);
1605 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1606 return ReplaceInstUsesWith(I, ConstantBool::True);
1607 }
1608 break;
1609 case Instruction::SetLT:
1610 switch (RHSCC) {
1611 default: assert(0 && "Unknown integer condition code!");
1612 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1613 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001614 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1615 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001616 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1617 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1618 return ReplaceInstUsesWith(I, RHS);
1619 }
1620 break;
1621 case Instruction::SetGT:
1622 switch (RHSCC) {
1623 default: assert(0 && "Unknown integer condition code!");
1624 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1625 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1626 return ReplaceInstUsesWith(I, LHS);
1627 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1628 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1629 return ReplaceInstUsesWith(I, ConstantBool::True);
1630 }
1631 }
1632 }
1633 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001634 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001635}
1636
Chris Lattnerc2076352004-02-16 01:20:27 +00001637// XorSelf - Implements: X ^ X --> 0
1638struct XorSelf {
1639 Value *RHS;
1640 XorSelf(Value *rhs) : RHS(rhs) {}
1641 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1642 Instruction *apply(BinaryOperator &Xor) const {
1643 return &Xor;
1644 }
1645};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001646
1647
Chris Lattner113f4f42002-06-25 16:13:24 +00001648Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001649 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001650 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001651
Chris Lattnerc2076352004-02-16 01:20:27 +00001652 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1653 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1654 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001655 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001656 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001657
Chris Lattner97638592003-07-23 21:37:07 +00001658 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001659 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001660 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001661 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001662
Chris Lattner97638592003-07-23 21:37:07 +00001663 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001664 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001665 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001666 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001667 return new SetCondInst(SCI->getInverseCondition(),
1668 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001669
Chris Lattner8f2f5982003-11-05 01:06:05 +00001670 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001671 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1672 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001673 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1674 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001675 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001676 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001677 }
Chris Lattner023a4832004-06-18 06:07:51 +00001678
1679 // ~(~X & Y) --> (X | ~Y)
1680 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1681 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1682 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1683 Instruction *NotY =
1684 BinaryOperator::createNot(Op0I->getOperand(1),
1685 Op0I->getOperand(1)->getName()+".not");
1686 InsertNewInstBefore(NotY, I);
1687 return BinaryOperator::createOr(Op0NotVal, NotY);
1688 }
1689 }
Chris Lattner97638592003-07-23 21:37:07 +00001690
1691 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001692 switch (Op0I->getOpcode()) {
1693 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001694 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001695 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001696 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1697 return BinaryOperator::createSub(
1698 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001699 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001700 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001701 }
Chris Lattnere5806662003-11-04 23:50:51 +00001702 break;
1703 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001704 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001705 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1706 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001707 break;
1708 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001709 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001710 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001711 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001712 break;
1713 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001714 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001715 }
Chris Lattner183b3362004-04-09 19:05:30 +00001716
1717 // Try to fold constant and into select arguments.
1718 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1719 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1720 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001721 if (isa<PHINode>(Op0))
1722 if (Instruction *NV = FoldOpIntoPhi(I))
1723 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001724 }
1725
Chris Lattnerbb74e222003-03-10 23:06:50 +00001726 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001727 if (X == Op1)
1728 return ReplaceInstUsesWith(I,
1729 ConstantIntegral::getAllOnesValue(I.getType()));
1730
Chris Lattnerbb74e222003-03-10 23:06:50 +00001731 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001732 if (X == Op0)
1733 return ReplaceInstUsesWith(I,
1734 ConstantIntegral::getAllOnesValue(I.getType()));
1735
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001736 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001737 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001738 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1739 cast<BinaryOperator>(Op1I)->swapOperands();
1740 I.swapOperands();
1741 std::swap(Op0, Op1);
1742 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1743 I.swapOperands();
1744 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001745 }
1746 } else if (Op1I->getOpcode() == Instruction::Xor) {
1747 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1748 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1749 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1750 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1751 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001752
1753 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001754 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001755 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1756 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001757 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001758 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1759 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001760 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001761 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001762 } else if (Op0I->getOpcode() == Instruction::Xor) {
1763 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1764 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1765 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1766 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001767 }
1768
Chris Lattner7aa2d472004-08-01 19:42:59 +00001769 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001770 Value *A, *B; ConstantInt *C1, *C2;
1771 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1772 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001773 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001774 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001775
Chris Lattner3ac7c262003-08-13 20:16:26 +00001776 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1777 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1778 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1779 return R;
1780
Chris Lattner113f4f42002-06-25 16:13:24 +00001781 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001782}
1783
Chris Lattner6862fbd2004-09-29 17:40:11 +00001784/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1785/// overflowed for this type.
1786static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1787 ConstantInt *In2) {
1788 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1789 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1790}
1791
1792static bool isPositive(ConstantInt *C) {
1793 return cast<ConstantSInt>(C)->getValue() >= 0;
1794}
1795
1796/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1797/// overflowed for this type.
1798static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1799 ConstantInt *In2) {
1800 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1801
1802 if (In1->getType()->isUnsigned())
1803 return cast<ConstantUInt>(Result)->getValue() <
1804 cast<ConstantUInt>(In1)->getValue();
1805 if (isPositive(In1) != isPositive(In2))
1806 return false;
1807 if (isPositive(In1))
1808 return cast<ConstantSInt>(Result)->getValue() <
1809 cast<ConstantSInt>(In1)->getValue();
1810 return cast<ConstantSInt>(Result)->getValue() >
1811 cast<ConstantSInt>(In1)->getValue();
1812}
1813
Chris Lattner113f4f42002-06-25 16:13:24 +00001814Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001815 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001816 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1817 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001818
1819 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001820 if (Op0 == Op1)
1821 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001822
Chris Lattnerd07283a2003-08-13 05:38:46 +00001823 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1824 if (isa<ConstantPointerNull>(Op1) &&
1825 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001826 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1827
Chris Lattnerd07283a2003-08-13 05:38:46 +00001828
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001829 // setcc's with boolean values can always be turned into bitwise operations
1830 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001831 switch (I.getOpcode()) {
1832 default: assert(0 && "Invalid setcc instruction!");
1833 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001834 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001835 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001836 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001837 }
Chris Lattner4456da62004-08-11 00:50:51 +00001838 case Instruction::SetNE:
1839 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001840
Chris Lattner4456da62004-08-11 00:50:51 +00001841 case Instruction::SetGT:
1842 std::swap(Op0, Op1); // Change setgt -> setlt
1843 // FALL THROUGH
1844 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1845 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1846 InsertNewInstBefore(Not, I);
1847 return BinaryOperator::createAnd(Not, Op1);
1848 }
1849 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001850 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001851 // FALL THROUGH
1852 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1853 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1854 InsertNewInstBefore(Not, I);
1855 return BinaryOperator::createOr(Not, Op1);
1856 }
1857 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001858 }
1859
Chris Lattner2dd01742004-06-09 04:24:29 +00001860 // See if we are doing a comparison between a constant and an instruction that
1861 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001862 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001863 // Check to see if we are comparing against the minimum or maximum value...
1864 if (CI->isMinValue()) {
1865 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1866 return ReplaceInstUsesWith(I, ConstantBool::False);
1867 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1868 return ReplaceInstUsesWith(I, ConstantBool::True);
1869 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1870 return BinaryOperator::createSetEQ(Op0, Op1);
1871 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1872 return BinaryOperator::createSetNE(Op0, Op1);
1873
1874 } else if (CI->isMaxValue()) {
1875 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1876 return ReplaceInstUsesWith(I, ConstantBool::False);
1877 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1878 return ReplaceInstUsesWith(I, ConstantBool::True);
1879 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1880 return BinaryOperator::createSetEQ(Op0, Op1);
1881 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1882 return BinaryOperator::createSetNE(Op0, Op1);
1883
1884 // Comparing against a value really close to min or max?
1885 } else if (isMinValuePlusOne(CI)) {
1886 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1887 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1888 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1889 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1890
1891 } else if (isMaxValueMinusOne(CI)) {
1892 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1893 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1894 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1895 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1896 }
1897
1898 // If we still have a setle or setge instruction, turn it into the
1899 // appropriate setlt or setgt instruction. Since the border cases have
1900 // already been handled above, this requires little checking.
1901 //
1902 if (I.getOpcode() == Instruction::SetLE)
1903 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1904 if (I.getOpcode() == Instruction::SetGE)
1905 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1906
Chris Lattnere1e10e12004-05-25 06:32:08 +00001907 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001908 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001909 case Instruction::PHI:
1910 if (Instruction *NV = FoldOpIntoPhi(I))
1911 return NV;
1912 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001913 case Instruction::And:
1914 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1915 LHSI->getOperand(0)->hasOneUse()) {
1916 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1917 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1918 // happens a LOT in code produced by the C front-end, for bitfield
1919 // access.
1920 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1921 ConstantUInt *ShAmt;
1922 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1923 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1924 const Type *Ty = LHSI->getType();
1925
1926 // We can fold this as long as we can't shift unknown bits
1927 // into the mask. This can only happen with signed shift
1928 // rights, as they sign-extend.
1929 if (ShAmt) {
1930 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001931 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001932 if (!CanFold) {
1933 // To test for the bad case of the signed shr, see if any
1934 // of the bits shifted in could be tested after the mask.
1935 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001936 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001937 Constant *ShVal =
1938 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1939 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1940 CanFold = true;
1941 }
1942
1943 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001944 Constant *NewCst;
1945 if (Shift->getOpcode() == Instruction::Shl)
1946 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1947 else
1948 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001949
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001950 // Check to see if we are shifting out any of the bits being
1951 // compared.
1952 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1953 // If we shifted bits out, the fold is not going to work out.
1954 // As a special case, check to see if this means that the
1955 // result is always true or false now.
1956 if (I.getOpcode() == Instruction::SetEQ)
1957 return ReplaceInstUsesWith(I, ConstantBool::False);
1958 if (I.getOpcode() == Instruction::SetNE)
1959 return ReplaceInstUsesWith(I, ConstantBool::True);
1960 } else {
1961 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00001962 Constant *NewAndCST;
1963 if (Shift->getOpcode() == Instruction::Shl)
1964 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
1965 else
1966 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1967 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001968 LHSI->setOperand(0, Shift->getOperand(0));
1969 WorkList.push_back(Shift); // Shift is dead.
1970 AddUsesToWorkList(I);
1971 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00001972 }
1973 }
Chris Lattner35167c32004-06-09 07:59:58 +00001974 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001975 }
1976 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001977
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001978 case Instruction::Cast: { // (setcc (cast X to larger), CI)
1979 const Type *SrcTy = LHSI->getOperand(0)->getType();
1980 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00001981 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001982 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00001983 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001984 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
1985 if (SrcBits < DestBits) {
1986 // Check to see if the comparison is always true or false.
1987 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
1988 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
1989 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
1990 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
1991 Min = ConstantExpr::getCast(Min, LHSI->getType());
1992 Max = ConstantExpr::getCast(Max, LHSI->getType());
1993 switch (I.getOpcode()) {
1994 default: assert(0 && "unknown integer comparison");
1995 case Instruction::SetEQ:
1996 return ReplaceInstUsesWith(I, ConstantBool::False);
1997 case Instruction::SetNE:
1998 return ReplaceInstUsesWith(I, ConstantBool::True);
1999 case Instruction::SetLT:
2000 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002001 case Instruction::SetGT:
2002 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002003 }
2004 }
2005
2006 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
2007 ConstantExpr::getCast(CI, SrcTy));
2008 }
2009 }
2010 break;
2011 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00002012 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2013 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2014 switch (I.getOpcode()) {
2015 default: break;
2016 case Instruction::SetEQ:
2017 case Instruction::SetNE: {
2018 // If we are comparing against bits always shifted out, the
2019 // comparison cannot succeed.
2020 Constant *Comp =
2021 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2022 if (Comp != CI) {// Comparing against a bit that we know is zero.
2023 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2024 Constant *Cst = ConstantBool::get(IsSetNE);
2025 return ReplaceInstUsesWith(I, Cst);
2026 }
2027
2028 if (LHSI->hasOneUse()) {
2029 // Otherwise strength reduce the shift into an and.
2030 unsigned ShAmtVal = ShAmt->getValue();
2031 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2032 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2033
2034 Constant *Mask;
2035 if (CI->getType()->isUnsigned()) {
2036 Mask = ConstantUInt::get(CI->getType(), Val);
2037 } else if (ShAmtVal != 0) {
2038 Mask = ConstantSInt::get(CI->getType(), Val);
2039 } else {
2040 Mask = ConstantInt::getAllOnesValue(CI->getType());
2041 }
2042
2043 Instruction *AndI =
2044 BinaryOperator::createAnd(LHSI->getOperand(0),
2045 Mask, LHSI->getName()+".mask");
2046 Value *And = InsertNewInstBefore(AndI, I);
2047 return new SetCondInst(I.getOpcode(), And,
2048 ConstantExpr::getUShr(CI, ShAmt));
2049 }
2050 }
2051 }
2052 }
2053 break;
2054
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002055 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002056 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002057 switch (I.getOpcode()) {
2058 default: break;
2059 case Instruction::SetEQ:
2060 case Instruction::SetNE: {
2061 // If we are comparing against bits always shifted out, the
2062 // comparison cannot succeed.
2063 Constant *Comp =
2064 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2065
2066 if (Comp != CI) {// Comparing against a bit that we know is zero.
2067 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2068 Constant *Cst = ConstantBool::get(IsSetNE);
2069 return ReplaceInstUsesWith(I, Cst);
2070 }
2071
2072 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002073 unsigned ShAmtVal = ShAmt->getValue();
2074
Chris Lattner1023b872004-09-27 16:18:50 +00002075 // Otherwise strength reduce the shift into an and.
2076 uint64_t Val = ~0ULL; // All ones.
2077 Val <<= ShAmtVal; // Shift over to the right spot.
2078
2079 Constant *Mask;
2080 if (CI->getType()->isUnsigned()) {
2081 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2082 Val &= (1ULL << TypeBits)-1;
2083 Mask = ConstantUInt::get(CI->getType(), Val);
2084 } else {
2085 Mask = ConstantSInt::get(CI->getType(), Val);
2086 }
2087
2088 Instruction *AndI =
2089 BinaryOperator::createAnd(LHSI->getOperand(0),
2090 Mask, LHSI->getName()+".mask");
2091 Value *And = InsertNewInstBefore(AndI, I);
2092 return new SetCondInst(I.getOpcode(), And,
2093 ConstantExpr::getShl(CI, ShAmt));
2094 }
2095 break;
2096 }
2097 }
2098 }
2099 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002100
Chris Lattner6862fbd2004-09-29 17:40:11 +00002101 case Instruction::Div:
2102 // Fold: (div X, C1) op C2 -> range check
2103 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2104 // Fold this div into the comparison, producing a range check.
2105 // Determine, based on the divide type, what the range is being
2106 // checked. If there is an overflow on the low or high side, remember
2107 // it, otherwise compute the range [low, hi) bounding the new value.
2108 bool LoOverflow = false, HiOverflow = 0;
2109 ConstantInt *LoBound = 0, *HiBound = 0;
2110
2111 ConstantInt *Prod;
2112 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2113
2114 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2115 } else if (LHSI->getType()->isUnsigned()) { // udiv
2116 LoBound = Prod;
2117 LoOverflow = ProdOV;
2118 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2119 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2120 if (CI->isNullValue()) { // (X / pos) op 0
2121 // Can't overflow.
2122 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2123 HiBound = DivRHS;
2124 } else if (isPositive(CI)) { // (X / pos) op pos
2125 LoBound = Prod;
2126 LoOverflow = ProdOV;
2127 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2128 } else { // (X / pos) op neg
2129 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2130 LoOverflow = AddWithOverflow(LoBound, Prod,
2131 cast<ConstantInt>(DivRHSH));
2132 HiBound = Prod;
2133 HiOverflow = ProdOV;
2134 }
2135 } else { // Divisor is < 0.
2136 if (CI->isNullValue()) { // (X / neg) op 0
2137 LoBound = AddOne(DivRHS);
2138 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2139 } else if (isPositive(CI)) { // (X / neg) op pos
2140 HiOverflow = LoOverflow = ProdOV;
2141 if (!LoOverflow)
2142 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2143 HiBound = AddOne(Prod);
2144 } else { // (X / neg) op neg
2145 LoBound = Prod;
2146 LoOverflow = HiOverflow = ProdOV;
2147 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2148 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002149
2150 /// FIXME: This code is disabled, because we do not compile the
2151 /// divisor case < 0 correctly. For example, this code is incorrect
2152 /// in the case of "X/-10 < 1".
2153 LoBound = 0;
Chris Lattner6862fbd2004-09-29 17:40:11 +00002154 }
2155
2156 if (LoBound) {
2157 Value *X = LHSI->getOperand(0);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002158 switch (I.getOpcode()) {
2159 default: assert(0 && "Unhandled setcc opcode!");
2160 case Instruction::SetEQ:
2161 if (LoOverflow && HiOverflow)
2162 return ReplaceInstUsesWith(I, ConstantBool::False);
2163 else if (HiOverflow)
2164 return new SetCondInst(Instruction::SetGE, X, LoBound);
2165 else if (LoOverflow)
2166 return new SetCondInst(Instruction::SetLT, X, HiBound);
2167 else
2168 return InsertRangeTest(X, LoBound, HiBound, true, I);
2169 case Instruction::SetNE:
2170 if (LoOverflow && HiOverflow)
2171 return ReplaceInstUsesWith(I, ConstantBool::True);
2172 else if (HiOverflow)
2173 return new SetCondInst(Instruction::SetLT, X, LoBound);
2174 else if (LoOverflow)
2175 return new SetCondInst(Instruction::SetGE, X, HiBound);
2176 else
2177 return InsertRangeTest(X, LoBound, HiBound, false, I);
2178 case Instruction::SetLT:
2179 if (LoOverflow)
2180 return ReplaceInstUsesWith(I, ConstantBool::False);
2181 return new SetCondInst(Instruction::SetLT, X, LoBound);
2182 case Instruction::SetGT:
2183 if (HiOverflow)
2184 return ReplaceInstUsesWith(I, ConstantBool::False);
2185 return new SetCondInst(Instruction::SetGE, X, HiBound);
2186 }
2187 }
2188 }
2189 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002190 case Instruction::Select:
2191 // If either operand of the select is a constant, we can fold the
2192 // comparison into the select arms, which will cause one to be
2193 // constant folded and the select turned into a bitwise or.
2194 Value *Op1 = 0, *Op2 = 0;
2195 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002196 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002197 // Fold the known value into the constant operand.
2198 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2199 // Insert a new SetCC of the other select operand.
2200 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002201 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002202 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002203 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002204 // Fold the known value into the constant operand.
2205 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2206 // Insert a new SetCC of the other select operand.
2207 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002208 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002209 I.getName()), I);
2210 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002211 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002212
2213 if (Op1)
2214 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2215 break;
2216 }
2217
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002218 // Simplify seteq and setne instructions...
2219 if (I.getOpcode() == Instruction::SetEQ ||
2220 I.getOpcode() == Instruction::SetNE) {
2221 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2222
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002223 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002224 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002225 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2226 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002227 case Instruction::Rem:
2228 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2229 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2230 BO->hasOneUse() &&
2231 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2232 if (unsigned L2 =
2233 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2234 const Type *UTy = BO->getType()->getUnsignedVersion();
2235 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2236 UTy, "tmp"), I);
2237 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2238 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2239 RHSCst, BO->getName()), I);
2240 return BinaryOperator::create(I.getOpcode(), NewRem,
2241 Constant::getNullValue(UTy));
2242 }
2243 break;
2244
Chris Lattnerc992add2003-08-13 05:33:12 +00002245 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002246 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2247 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002248 if (BO->hasOneUse())
2249 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2250 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002251 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002252 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2253 // efficiently invertible, or if the add has just this one use.
2254 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002255
Chris Lattnerc992add2003-08-13 05:33:12 +00002256 if (Value *NegVal = dyn_castNegVal(BOp1))
2257 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2258 else if (Value *NegVal = dyn_castNegVal(BOp0))
2259 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002260 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002261 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2262 BO->setName("");
2263 InsertNewInstBefore(Neg, I);
2264 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2265 }
2266 }
2267 break;
2268 case Instruction::Xor:
2269 // For the xor case, we can xor two constants together, eliminating
2270 // the explicit xor.
2271 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2272 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002273 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002274
2275 // FALLTHROUGH
2276 case Instruction::Sub:
2277 // Replace (([sub|xor] A, B) != 0) with (A != B)
2278 if (CI->isNullValue())
2279 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2280 BO->getOperand(1));
2281 break;
2282
2283 case Instruction::Or:
2284 // If bits are being or'd in that are not present in the constant we
2285 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002286 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002287 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002288 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002289 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002290 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002291 break;
2292
2293 case Instruction::And:
2294 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002295 // If bits are being compared against that are and'd out, then the
2296 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002297 if (!ConstantExpr::getAnd(CI,
2298 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002299 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002300
Chris Lattner35167c32004-06-09 07:59:58 +00002301 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002302 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002303 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2304 Instruction::SetNE, Op0,
2305 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002306
Chris Lattnerc992add2003-08-13 05:33:12 +00002307 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2308 // to be a signed value as appropriate.
2309 if (isSignBit(BOC)) {
2310 Value *X = BO->getOperand(0);
2311 // If 'X' is not signed, insert a cast now...
2312 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002313 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002314 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002315 }
2316 return new SetCondInst(isSetNE ? Instruction::SetLT :
2317 Instruction::SetGE, X,
2318 Constant::getNullValue(X->getType()));
2319 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002320
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002321 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002322 if (CI->isNullValue() && isHighOnes(BOC)) {
2323 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002324 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002325
2326 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002327 if (NegX->getType()->isSigned()) {
2328 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2329 X = InsertCastBefore(X, DestTy, I);
2330 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002331 }
2332
2333 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002334 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002335 }
2336
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002337 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002338 default: break;
2339 }
2340 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002341 } else { // Not a SetEQ/SetNE
2342 // If the LHS is a cast from an integral value of the same size,
2343 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2344 Value *CastOp = Cast->getOperand(0);
2345 const Type *SrcTy = CastOp->getType();
2346 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2347 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2348 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2349 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2350 "Source and destination signednesses should differ!");
2351 if (Cast->getType()->isSigned()) {
2352 // If this is a signed comparison, check for comparisons in the
2353 // vicinity of zero.
2354 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2355 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002356 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002357 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2358 else if (I.getOpcode() == Instruction::SetGT &&
2359 cast<ConstantSInt>(CI)->getValue() == -1)
2360 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002361 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002362 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2363 } else {
2364 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2365 if (I.getOpcode() == Instruction::SetLT &&
2366 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2367 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002368 return BinaryOperator::createSetGT(CastOp,
2369 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002370 else if (I.getOpcode() == Instruction::SetGT &&
2371 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2372 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002373 return BinaryOperator::createSetLT(CastOp,
2374 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002375 }
2376 }
2377 }
Chris Lattnere967b342003-06-04 05:10:11 +00002378 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002379 }
2380
Chris Lattner16930792003-11-03 04:25:02 +00002381 // Test to see if the operands of the setcc are casted versions of other
2382 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002383 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2384 Value *CastOp0 = CI->getOperand(0);
2385 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002386 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002387 (I.getOpcode() == Instruction::SetEQ ||
2388 I.getOpcode() == Instruction::SetNE)) {
2389 // We keep moving the cast from the left operand over to the right
2390 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002391 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002392
2393 // If operand #1 is a cast instruction, see if we can eliminate it as
2394 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002395 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2396 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002397 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002398 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002399
2400 // If Op1 is a constant, we can fold the cast into the constant.
2401 if (Op1->getType() != Op0->getType())
2402 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2403 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2404 } else {
2405 // Otherwise, cast the RHS right before the setcc
2406 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2407 InsertNewInstBefore(cast<Instruction>(Op1), I);
2408 }
2409 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2410 }
2411
Chris Lattner6444c372003-11-03 05:17:03 +00002412 // Handle the special case of: setcc (cast bool to X), <cst>
2413 // This comes up when you have code like
2414 // int X = A < B;
2415 // if (X) ...
2416 // For generality, we handle any zero-extension of any operand comparison
2417 // with a constant.
2418 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2419 const Type *SrcTy = CastOp0->getType();
2420 const Type *DestTy = Op0->getType();
2421 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2422 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2423 // Ok, we have an expansion of operand 0 into a new type. Get the
2424 // constant value, masink off bits which are not set in the RHS. These
2425 // could be set if the destination value is signed.
2426 uint64_t ConstVal = ConstantRHS->getRawValue();
2427 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2428
2429 // If the constant we are comparing it with has high bits set, which
2430 // don't exist in the original value, the values could never be equal,
2431 // because the source would be zero extended.
2432 unsigned SrcBits =
2433 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002434 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2435 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002436 switch (I.getOpcode()) {
2437 default: assert(0 && "Unknown comparison type!");
2438 case Instruction::SetEQ:
2439 return ReplaceInstUsesWith(I, ConstantBool::False);
2440 case Instruction::SetNE:
2441 return ReplaceInstUsesWith(I, ConstantBool::True);
2442 case Instruction::SetLT:
2443 case Instruction::SetLE:
2444 if (DestTy->isSigned() && HasSignBit)
2445 return ReplaceInstUsesWith(I, ConstantBool::False);
2446 return ReplaceInstUsesWith(I, ConstantBool::True);
2447 case Instruction::SetGT:
2448 case Instruction::SetGE:
2449 if (DestTy->isSigned() && HasSignBit)
2450 return ReplaceInstUsesWith(I, ConstantBool::True);
2451 return ReplaceInstUsesWith(I, ConstantBool::False);
2452 }
2453 }
2454
2455 // Otherwise, we can replace the setcc with a setcc of the smaller
2456 // operand value.
2457 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2458 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2459 }
2460 }
2461 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002462 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002463}
2464
2465
2466
Chris Lattnere8d6c602003-03-10 19:16:08 +00002467Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002468 assert(I.getOperand(1)->getType() == Type::UByteTy);
2469 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002470 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002471
2472 // shl X, 0 == X and shr X, 0 == X
2473 // shl 0, X == 0 and shr 0, X == 0
2474 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002475 Op0 == Constant::getNullValue(Op0->getType()))
2476 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002477
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002478 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2479 if (!isLeftShift)
2480 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2481 if (CSI->isAllOnesValue())
2482 return ReplaceInstUsesWith(I, CSI);
2483
Chris Lattner183b3362004-04-09 19:05:30 +00002484 // Try to fold constant and into select arguments.
2485 if (isa<Constant>(Op0))
2486 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2487 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2488 return R;
2489
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002490 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002491 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2492 // of a signed value.
2493 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002494 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002495 if (CUI->getValue() >= TypeBits) {
2496 if (!Op0->getType()->isSigned() || isLeftShift)
2497 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2498 else {
2499 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2500 return &I;
2501 }
2502 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002503
Chris Lattnerede3fe02003-08-13 04:18:28 +00002504 // ((X*C1) << C2) == (X * (C1 << C2))
2505 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2506 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2507 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002508 return BinaryOperator::createMul(BO->getOperand(0),
2509 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002510
Chris Lattner183b3362004-04-09 19:05:30 +00002511 // Try to fold constant and into select arguments.
2512 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2513 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2514 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002515 if (isa<PHINode>(Op0))
2516 if (Instruction *NV = FoldOpIntoPhi(I))
2517 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002518
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002519 // If the operand is an bitwise operator with a constant RHS, and the
2520 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002521 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002522 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2523 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2524 bool isValid = true; // Valid only for And, Or, Xor
2525 bool highBitSet = false; // Transform if high bit of constant set?
2526
2527 switch (Op0BO->getOpcode()) {
2528 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002529 case Instruction::Add:
2530 isValid = isLeftShift;
2531 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002532 case Instruction::Or:
2533 case Instruction::Xor:
2534 highBitSet = false;
2535 break;
2536 case Instruction::And:
2537 highBitSet = true;
2538 break;
2539 }
2540
2541 // If this is a signed shift right, and the high bit is modified
2542 // by the logical operation, do not perform the transformation.
2543 // The highBitSet boolean indicates the value of the high bit of
2544 // the constant which would cause it to be modified for this
2545 // operation.
2546 //
2547 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2548 uint64_t Val = Op0C->getRawValue();
2549 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2550 }
2551
2552 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002553 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002554
2555 Instruction *NewShift =
2556 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2557 Op0BO->getName());
2558 Op0BO->setName("");
2559 InsertNewInstBefore(NewShift, I);
2560
2561 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2562 NewRHS);
2563 }
2564 }
2565
Chris Lattner3204d4e2003-07-24 17:52:58 +00002566 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002567 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002568 if (ConstantUInt *ShiftAmt1C =
2569 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002570 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2571 unsigned ShiftAmt2 = CUI->getValue();
2572
2573 // Check for (A << c1) << c2 and (A >> c1) >> c2
2574 if (I.getOpcode() == Op0SI->getOpcode()) {
2575 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002576 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2577 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002578 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2579 ConstantUInt::get(Type::UByteTy, Amt));
2580 }
2581
Chris Lattnerab780df2003-07-24 18:38:56 +00002582 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2583 // signed types, we can only support the (A >> c1) << c2 configuration,
2584 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002585 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002586 // Calculate bitmask for what gets shifted off the edge...
2587 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002588 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002589 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002590 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002591 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002592
2593 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002594 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2595 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002596 InsertNewInstBefore(Mask, I);
2597
2598 // Figure out what flavor of shift we should use...
2599 if (ShiftAmt1 == ShiftAmt2)
2600 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2601 else if (ShiftAmt1 < ShiftAmt2) {
2602 return new ShiftInst(I.getOpcode(), Mask,
2603 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2604 } else {
2605 return new ShiftInst(Op0SI->getOpcode(), Mask,
2606 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2607 }
2608 }
2609 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002610 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002611
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002612 return 0;
2613}
2614
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002615enum CastType {
2616 Noop = 0,
2617 Truncate = 1,
2618 Signext = 2,
2619 Zeroext = 3
2620};
2621
2622/// getCastType - In the future, we will split the cast instruction into these
2623/// various types. Until then, we have to do the analysis here.
2624static CastType getCastType(const Type *Src, const Type *Dest) {
2625 assert(Src->isIntegral() && Dest->isIntegral() &&
2626 "Only works on integral types!");
2627 unsigned SrcSize = Src->getPrimitiveSize()*8;
2628 if (Src == Type::BoolTy) SrcSize = 1;
2629 unsigned DestSize = Dest->getPrimitiveSize()*8;
2630 if (Dest == Type::BoolTy) DestSize = 1;
2631
2632 if (SrcSize == DestSize) return Noop;
2633 if (SrcSize > DestSize) return Truncate;
2634 if (Src->isSigned()) return Signext;
2635 return Zeroext;
2636}
2637
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002638
Chris Lattner48a44f72002-05-02 17:06:02 +00002639// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2640// instruction.
2641//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002642static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002643 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002644
Chris Lattner650b6da2002-08-02 20:00:25 +00002645 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2646 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002647 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002648 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002649 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002650
Chris Lattner4fbad962004-07-21 04:27:24 +00002651 // If we are casting between pointer and integer types, treat pointers as
2652 // integers of the appropriate size for the code below.
2653 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2654 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2655 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002656
Chris Lattner48a44f72002-05-02 17:06:02 +00002657 // Allow free casting and conversion of sizes as long as the sign doesn't
2658 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002659 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002660 CastType FirstCast = getCastType(SrcTy, MidTy);
2661 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002662
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002663 // Capture the effect of these two casts. If the result is a legal cast,
2664 // the CastType is stored here, otherwise a special code is used.
2665 static const unsigned CastResult[] = {
2666 // First cast is noop
2667 0, 1, 2, 3,
2668 // First cast is a truncate
2669 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2670 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002671 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002672 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002673 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002674 };
2675
2676 unsigned Result = CastResult[FirstCast*4+SecondCast];
2677 switch (Result) {
2678 default: assert(0 && "Illegal table value!");
2679 case 0:
2680 case 1:
2681 case 2:
2682 case 3:
2683 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2684 // truncates, we could eliminate more casts.
2685 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2686 case 4:
2687 return false; // Not possible to eliminate this here.
2688 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002689 // Sign or zero extend followed by truncate is always ok if the result
2690 // is a truncate or noop.
2691 CastType ResultCast = getCastType(SrcTy, DstTy);
2692 if (ResultCast == Noop || ResultCast == Truncate)
2693 return true;
2694 // Otherwise we are still growing the value, we are only safe if the
2695 // result will match the sign/zeroextendness of the result.
2696 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002697 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002698 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002699 return false;
2700}
2701
Chris Lattner11ffd592004-07-20 05:21:00 +00002702static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002703 if (V->getType() == Ty || isa<Constant>(V)) return false;
2704 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002705 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2706 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002707 return false;
2708 return true;
2709}
2710
2711/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2712/// InsertBefore instruction. This is specialized a bit to avoid inserting
2713/// casts that are known to not do anything...
2714///
2715Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2716 Instruction *InsertBefore) {
2717 if (V->getType() == DestTy) return V;
2718 if (Constant *C = dyn_cast<Constant>(V))
2719 return ConstantExpr::getCast(C, DestTy);
2720
2721 CastInst *CI = new CastInst(V, DestTy, V->getName());
2722 InsertNewInstBefore(CI, *InsertBefore);
2723 return CI;
2724}
Chris Lattner48a44f72002-05-02 17:06:02 +00002725
2726// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002727//
Chris Lattner113f4f42002-06-25 16:13:24 +00002728Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002729 Value *Src = CI.getOperand(0);
2730
Chris Lattner48a44f72002-05-02 17:06:02 +00002731 // If the user is casting a value to the same type, eliminate this cast
2732 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002733 if (CI.getType() == Src->getType())
2734 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002735
Chris Lattner48a44f72002-05-02 17:06:02 +00002736 // If casting the result of another cast instruction, try to eliminate this
2737 // one!
2738 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002739 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002740 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002741 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002742 // This instruction now refers directly to the cast's src operand. This
2743 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002744 CI.setOperand(0, CSrc->getOperand(0));
2745 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002746 }
2747
Chris Lattner650b6da2002-08-02 20:00:25 +00002748 // If this is an A->B->A cast, and we are dealing with integral types, try
2749 // to convert this into a logical 'and' instruction.
2750 //
2751 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002752 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002753 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2754 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2755 assert(CSrc->getType() != Type::ULongTy &&
2756 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002757 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002758 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002759 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002760 }
2761 }
2762
Chris Lattner03841652004-05-25 04:29:21 +00002763 // If this is a cast to bool, turn it into the appropriate setne instruction.
2764 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002765 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002766 Constant::getNullValue(CI.getOperand(0)->getType()));
2767
Chris Lattnerd0d51602003-06-21 23:12:02 +00002768 // If casting the result of a getelementptr instruction with no offset, turn
2769 // this into a cast of the original pointer!
2770 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002771 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002772 bool AllZeroOperands = true;
2773 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2774 if (!isa<Constant>(GEP->getOperand(i)) ||
2775 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2776 AllZeroOperands = false;
2777 break;
2778 }
2779 if (AllZeroOperands) {
2780 CI.setOperand(0, GEP->getOperand(0));
2781 return &CI;
2782 }
2783 }
2784
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002785 // If we are casting a malloc or alloca to a pointer to a type of the same
2786 // size, rewrite the allocation instruction to allocate the "right" type.
2787 //
2788 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002789 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002790 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2791 // Get the type really allocated and the type casted to...
2792 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002793 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002794 if (AllocElTy->isSized() && CastElTy->isSized()) {
2795 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2796 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002797
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002798 // If the allocation is for an even multiple of the cast type size
2799 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2800 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002801 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002802 std::string Name = AI->getName(); AI->setName("");
2803 AllocationInst *New;
2804 if (isa<MallocInst>(AI))
2805 New = new MallocInst(CastElTy, Amt, Name);
2806 else
2807 New = new AllocaInst(CastElTy, Amt, Name);
2808 InsertNewInstBefore(New, *AI);
2809 return ReplaceInstUsesWith(CI, New);
2810 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002811 }
2812 }
2813
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002814 if (isa<PHINode>(Src))
2815 if (Instruction *NV = FoldOpIntoPhi(CI))
2816 return NV;
2817
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002818 // If the source value is an instruction with only this use, we can attempt to
2819 // propagate the cast into the instruction. Also, only handle integral types
2820 // for now.
2821 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002822 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002823 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2824 const Type *DestTy = CI.getType();
2825 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2826 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2827
2828 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2829 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2830
2831 switch (SrcI->getOpcode()) {
2832 case Instruction::Add:
2833 case Instruction::Mul:
2834 case Instruction::And:
2835 case Instruction::Or:
2836 case Instruction::Xor:
2837 // If we are discarding information, or just changing the sign, rewrite.
2838 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2839 // Don't insert two casts if they cannot be eliminated. We allow two
2840 // casts to be inserted if the sizes are the same. This could only be
2841 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002842 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2843 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002844 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2845 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2846 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2847 ->getOpcode(), Op0c, Op1c);
2848 }
2849 }
2850 break;
2851 case Instruction::Shl:
2852 // Allow changing the sign of the source operand. Do not allow changing
2853 // the size of the shift, UNLESS the shift amount is a constant. We
2854 // mush not change variable sized shifts to a smaller size, because it
2855 // is undefined to shift more bits out than exist in the value.
2856 if (DestBitSize == SrcBitSize ||
2857 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2858 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2859 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2860 }
2861 break;
2862 }
2863 }
2864
Chris Lattner260ab202002-04-18 17:39:14 +00002865 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002866}
2867
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002868/// GetSelectFoldableOperands - We want to turn code that looks like this:
2869/// %C = or %A, %B
2870/// %D = select %cond, %C, %A
2871/// into:
2872/// %C = select %cond, %B, 0
2873/// %D = or %A, %C
2874///
2875/// Assuming that the specified instruction is an operand to the select, return
2876/// a bitmask indicating which operands of this instruction are foldable if they
2877/// equal the other incoming value of the select.
2878///
2879static unsigned GetSelectFoldableOperands(Instruction *I) {
2880 switch (I->getOpcode()) {
2881 case Instruction::Add:
2882 case Instruction::Mul:
2883 case Instruction::And:
2884 case Instruction::Or:
2885 case Instruction::Xor:
2886 return 3; // Can fold through either operand.
2887 case Instruction::Sub: // Can only fold on the amount subtracted.
2888 case Instruction::Shl: // Can only fold on the shift amount.
2889 case Instruction::Shr:
2890 return 1;
2891 default:
2892 return 0; // Cannot fold
2893 }
2894}
2895
2896/// GetSelectFoldableConstant - For the same transformation as the previous
2897/// function, return the identity constant that goes into the select.
2898static Constant *GetSelectFoldableConstant(Instruction *I) {
2899 switch (I->getOpcode()) {
2900 default: assert(0 && "This cannot happen!"); abort();
2901 case Instruction::Add:
2902 case Instruction::Sub:
2903 case Instruction::Or:
2904 case Instruction::Xor:
2905 return Constant::getNullValue(I->getType());
2906 case Instruction::Shl:
2907 case Instruction::Shr:
2908 return Constant::getNullValue(Type::UByteTy);
2909 case Instruction::And:
2910 return ConstantInt::getAllOnesValue(I->getType());
2911 case Instruction::Mul:
2912 return ConstantInt::get(I->getType(), 1);
2913 }
2914}
2915
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002916Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002917 Value *CondVal = SI.getCondition();
2918 Value *TrueVal = SI.getTrueValue();
2919 Value *FalseVal = SI.getFalseValue();
2920
2921 // select true, X, Y -> X
2922 // select false, X, Y -> Y
2923 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002924 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002925 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002926 else {
2927 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002928 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002929 }
Chris Lattner533bc492004-03-30 19:37:13 +00002930
2931 // select C, X, X -> X
2932 if (TrueVal == FalseVal)
2933 return ReplaceInstUsesWith(SI, TrueVal);
2934
Chris Lattner1c631e82004-04-08 04:43:23 +00002935 if (SI.getType() == Type::BoolTy)
2936 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2937 if (C == ConstantBool::True) {
2938 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002939 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002940 } else {
2941 // Change: A = select B, false, C --> A = and !B, C
2942 Value *NotCond =
2943 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2944 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002945 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002946 }
2947 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2948 if (C == ConstantBool::False) {
2949 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002950 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002951 } else {
2952 // Change: A = select B, C, true --> A = or !B, C
2953 Value *NotCond =
2954 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2955 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002956 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002957 }
2958 }
2959
Chris Lattner183b3362004-04-09 19:05:30 +00002960 // Selecting between two integer constants?
2961 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2962 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2963 // select C, 1, 0 -> cast C to int
2964 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2965 return new CastInst(CondVal, SI.getType());
2966 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2967 // select C, 0, 1 -> cast !C to int
2968 Value *NotCond =
2969 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002970 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002971 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002972 }
Chris Lattner35167c32004-06-09 07:59:58 +00002973
2974 // If one of the constants is zero (we know they can't both be) and we
2975 // have a setcc instruction with zero, and we have an 'and' with the
2976 // non-constant value, eliminate this whole mess. This corresponds to
2977 // cases like this: ((X & 27) ? 27 : 0)
2978 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2979 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2980 if ((IC->getOpcode() == Instruction::SetEQ ||
2981 IC->getOpcode() == Instruction::SetNE) &&
2982 isa<ConstantInt>(IC->getOperand(1)) &&
2983 cast<Constant>(IC->getOperand(1))->isNullValue())
2984 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2985 if (ICA->getOpcode() == Instruction::And &&
2986 isa<ConstantInt>(ICA->getOperand(1)) &&
2987 (ICA->getOperand(1) == TrueValC ||
2988 ICA->getOperand(1) == FalseValC) &&
2989 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2990 // Okay, now we know that everything is set up, we just don't
2991 // know whether we have a setne or seteq and whether the true or
2992 // false val is the zero.
2993 bool ShouldNotVal = !TrueValC->isNullValue();
2994 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2995 Value *V = ICA;
2996 if (ShouldNotVal)
2997 V = InsertNewInstBefore(BinaryOperator::create(
2998 Instruction::Xor, V, ICA->getOperand(1)), SI);
2999 return ReplaceInstUsesWith(SI, V);
3000 }
Chris Lattner533bc492004-03-30 19:37:13 +00003001 }
Chris Lattner623fba12004-04-10 22:21:27 +00003002
3003 // See if we are selecting two values based on a comparison of the two values.
3004 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3005 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3006 // Transform (X == Y) ? X : Y -> Y
3007 if (SCI->getOpcode() == Instruction::SetEQ)
3008 return ReplaceInstUsesWith(SI, FalseVal);
3009 // Transform (X != Y) ? X : Y -> X
3010 if (SCI->getOpcode() == Instruction::SetNE)
3011 return ReplaceInstUsesWith(SI, TrueVal);
3012 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3013
3014 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3015 // Transform (X == Y) ? Y : X -> X
3016 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003017 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003018 // Transform (X != Y) ? Y : X -> Y
3019 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003020 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003021 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3022 }
3023 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003024
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003025 // See if we can fold the select into one of our operands.
3026 if (SI.getType()->isInteger()) {
3027 // See the comment above GetSelectFoldableOperands for a description of the
3028 // transformation we are doing here.
3029 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3030 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3031 !isa<Constant>(FalseVal))
3032 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3033 unsigned OpToFold = 0;
3034 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3035 OpToFold = 1;
3036 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3037 OpToFold = 2;
3038 }
3039
3040 if (OpToFold) {
3041 Constant *C = GetSelectFoldableConstant(TVI);
3042 std::string Name = TVI->getName(); TVI->setName("");
3043 Instruction *NewSel =
3044 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3045 Name);
3046 InsertNewInstBefore(NewSel, SI);
3047 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3048 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3049 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3050 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3051 else {
3052 assert(0 && "Unknown instruction!!");
3053 }
3054 }
3055 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003056
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003057 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3058 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3059 !isa<Constant>(TrueVal))
3060 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3061 unsigned OpToFold = 0;
3062 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3063 OpToFold = 1;
3064 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3065 OpToFold = 2;
3066 }
3067
3068 if (OpToFold) {
3069 Constant *C = GetSelectFoldableConstant(FVI);
3070 std::string Name = FVI->getName(); FVI->setName("");
3071 Instruction *NewSel =
3072 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3073 Name);
3074 InsertNewInstBefore(NewSel, SI);
3075 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3076 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3077 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3078 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3079 else {
3080 assert(0 && "Unknown instruction!!");
3081 }
3082 }
3083 }
3084 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003085 return 0;
3086}
3087
3088
Chris Lattner970c33a2003-06-19 17:00:31 +00003089// CallInst simplification
3090//
3091Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003092 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3093 // visitCallSite.
3094 if (Function *F = CI.getCalledFunction())
3095 switch (F->getIntrinsicID()) {
3096 case Intrinsic::memmove:
3097 case Intrinsic::memcpy:
3098 case Intrinsic::memset:
3099 // memmove/cpy/set of zero bytes is a noop.
3100 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
3101 if (NumBytes->isNullValue())
3102 return EraseInstFromFunction(CI);
3103 }
3104 break;
3105 default:
3106 break;
3107 }
3108
Chris Lattneraec3d942003-10-07 22:32:43 +00003109 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003110}
3111
3112// InvokeInst simplification
3113//
3114Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003115 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003116}
3117
Chris Lattneraec3d942003-10-07 22:32:43 +00003118// visitCallSite - Improvements for call and invoke instructions.
3119//
3120Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003121 bool Changed = false;
3122
3123 // If the callee is a constexpr cast of a function, attempt to move the cast
3124 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003125 if (transformConstExprCastCall(CS)) return 0;
3126
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003127 Value *Callee = CS.getCalledValue();
3128 const PointerType *PTy = cast<PointerType>(Callee->getType());
3129 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3130 if (FTy->isVarArg()) {
3131 // See if we can optimize any arguments passed through the varargs area of
3132 // the call.
3133 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3134 E = CS.arg_end(); I != E; ++I)
3135 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3136 // If this cast does not effect the value passed through the varargs
3137 // area, we can eliminate the use of the cast.
3138 Value *Op = CI->getOperand(0);
3139 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3140 *I = Op;
3141 Changed = true;
3142 }
3143 }
3144 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003145
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003146 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003147}
3148
Chris Lattner970c33a2003-06-19 17:00:31 +00003149// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3150// attempt to move the cast to the arguments of the call/invoke.
3151//
3152bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3153 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3154 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003155 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003156 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003157 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003158 Instruction *Caller = CS.getInstruction();
3159
3160 // Okay, this is a cast from a function to a different type. Unless doing so
3161 // would cause a type conversion of one of our arguments, change this call to
3162 // be a direct call with arguments casted to the appropriate types.
3163 //
3164 const FunctionType *FT = Callee->getFunctionType();
3165 const Type *OldRetTy = Caller->getType();
3166
Chris Lattner1f7942f2004-01-14 06:06:08 +00003167 // Check to see if we are changing the return type...
3168 if (OldRetTy != FT->getReturnType()) {
3169 if (Callee->isExternal() &&
3170 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3171 !Caller->use_empty())
3172 return false; // Cannot transform this return value...
3173
3174 // If the callsite is an invoke instruction, and the return value is used by
3175 // a PHI node in a successor, we cannot change the return type of the call
3176 // because there is no place to put the cast instruction (without breaking
3177 // the critical edge). Bail out in this case.
3178 if (!Caller->use_empty())
3179 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3180 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3181 UI != E; ++UI)
3182 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3183 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003184 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003185 return false;
3186 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003187
3188 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3189 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3190
3191 CallSite::arg_iterator AI = CS.arg_begin();
3192 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3193 const Type *ParamTy = FT->getParamType(i);
3194 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3195 if (Callee->isExternal() && !isConvertible) return false;
3196 }
3197
3198 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3199 Callee->isExternal())
3200 return false; // Do not delete arguments unless we have a function body...
3201
3202 // Okay, we decided that this is a safe thing to do: go ahead and start
3203 // inserting cast instructions as necessary...
3204 std::vector<Value*> Args;
3205 Args.reserve(NumActualArgs);
3206
3207 AI = CS.arg_begin();
3208 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3209 const Type *ParamTy = FT->getParamType(i);
3210 if ((*AI)->getType() == ParamTy) {
3211 Args.push_back(*AI);
3212 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003213 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3214 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003215 }
3216 }
3217
3218 // If the function takes more arguments than the call was taking, add them
3219 // now...
3220 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3221 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3222
3223 // If we are removing arguments to the function, emit an obnoxious warning...
3224 if (FT->getNumParams() < NumActualArgs)
3225 if (!FT->isVarArg()) {
3226 std::cerr << "WARNING: While resolving call to function '"
3227 << Callee->getName() << "' arguments were dropped!\n";
3228 } else {
3229 // Add all of the arguments in their promoted form to the arg list...
3230 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3231 const Type *PTy = getPromotedType((*AI)->getType());
3232 if (PTy != (*AI)->getType()) {
3233 // Must promote to pass through va_arg area!
3234 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3235 InsertNewInstBefore(Cast, *Caller);
3236 Args.push_back(Cast);
3237 } else {
3238 Args.push_back(*AI);
3239 }
3240 }
3241 }
3242
3243 if (FT->getReturnType() == Type::VoidTy)
3244 Caller->setName(""); // Void type should not have a name...
3245
3246 Instruction *NC;
3247 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003248 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003249 Args, Caller->getName(), Caller);
3250 } else {
3251 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3252 }
3253
3254 // Insert a cast of the return type as necessary...
3255 Value *NV = NC;
3256 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3257 if (NV->getType() != Type::VoidTy) {
3258 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003259
3260 // If this is an invoke instruction, we should insert it after the first
3261 // non-phi, instruction in the normal successor block.
3262 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3263 BasicBlock::iterator I = II->getNormalDest()->begin();
3264 while (isa<PHINode>(I)) ++I;
3265 InsertNewInstBefore(NC, *I);
3266 } else {
3267 // Otherwise, it's a call, just insert cast right after the call instr
3268 InsertNewInstBefore(NC, *Caller);
3269 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003270 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003271 } else {
3272 NV = Constant::getNullValue(Caller->getType());
3273 }
3274 }
3275
3276 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3277 Caller->replaceAllUsesWith(NV);
3278 Caller->getParent()->getInstList().erase(Caller);
3279 removeFromWorkList(Caller);
3280 return true;
3281}
3282
3283
Chris Lattner48a44f72002-05-02 17:06:02 +00003284
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003285// PHINode simplification
3286//
Chris Lattner113f4f42002-06-25 16:13:24 +00003287Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00003288 if (Value *V = hasConstantValue(&PN))
3289 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00003290
3291 // If the only user of this instruction is a cast instruction, and all of the
3292 // incoming values are constants, change this PHI to merge together the casted
3293 // constants.
3294 if (PN.hasOneUse())
3295 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3296 if (CI->getType() != PN.getType()) { // noop casts will be folded
3297 bool AllConstant = true;
3298 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3299 if (!isa<Constant>(PN.getIncomingValue(i))) {
3300 AllConstant = false;
3301 break;
3302 }
3303 if (AllConstant) {
3304 // Make a new PHI with all casted values.
3305 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3306 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3307 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3308 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3309 PN.getIncomingBlock(i));
3310 }
3311
3312 // Update the cast instruction.
3313 CI->setOperand(0, New);
3314 WorkList.push_back(CI); // revisit the cast instruction to fold.
3315 WorkList.push_back(New); // Make sure to revisit the new Phi
3316 return &PN; // PN is now dead!
3317 }
3318 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003319 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003320}
3321
Chris Lattner69193f92004-04-05 01:30:19 +00003322static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3323 Instruction *InsertPoint,
3324 InstCombiner *IC) {
3325 unsigned PS = IC->getTargetData().getPointerSize();
3326 const Type *VTy = V->getType();
3327 Instruction *Cast;
3328 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3329 // We must insert a cast to ensure we sign-extend.
3330 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3331 V->getName()), *InsertPoint);
3332 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3333 *InsertPoint);
3334}
3335
Chris Lattner48a44f72002-05-02 17:06:02 +00003336
Chris Lattner113f4f42002-06-25 16:13:24 +00003337Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003338 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003339 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003340 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003341 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003342 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003343
3344 bool HasZeroPointerIndex = false;
3345 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3346 HasZeroPointerIndex = C->isNullValue();
3347
3348 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003349 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003350
Chris Lattner69193f92004-04-05 01:30:19 +00003351 // Eliminate unneeded casts for indices.
3352 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003353 gep_type_iterator GTI = gep_type_begin(GEP);
3354 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3355 if (isa<SequentialType>(*GTI)) {
3356 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3357 Value *Src = CI->getOperand(0);
3358 const Type *SrcTy = Src->getType();
3359 const Type *DestTy = CI->getType();
3360 if (Src->getType()->isInteger()) {
3361 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3362 // We can always eliminate a cast from ulong or long to the other.
3363 // We can always eliminate a cast from uint to int or the other on
3364 // 32-bit pointer platforms.
3365 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3366 MadeChange = true;
3367 GEP.setOperand(i, Src);
3368 }
3369 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3370 SrcTy->getPrimitiveSize() == 4) {
3371 // We can always eliminate a cast from int to [u]long. We can
3372 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3373 // pointer target.
3374 if (SrcTy->isSigned() ||
3375 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3376 MadeChange = true;
3377 GEP.setOperand(i, Src);
3378 }
Chris Lattner69193f92004-04-05 01:30:19 +00003379 }
3380 }
3381 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003382 // If we are using a wider index than needed for this platform, shrink it
3383 // to what we need. If the incoming value needs a cast instruction,
3384 // insert it. This explicit cast can make subsequent optimizations more
3385 // obvious.
3386 Value *Op = GEP.getOperand(i);
3387 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003388 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003389 GEP.setOperand(i, ConstantExpr::getCast(C,
3390 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003391 MadeChange = true;
3392 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003393 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3394 Op->getName()), GEP);
3395 GEP.setOperand(i, Op);
3396 MadeChange = true;
3397 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003398
3399 // If this is a constant idx, make sure to canonicalize it to be a signed
3400 // operand, otherwise CSE and other optimizations are pessimized.
3401 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3402 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3403 CUI->getType()->getSignedVersion()));
3404 MadeChange = true;
3405 }
Chris Lattner69193f92004-04-05 01:30:19 +00003406 }
3407 if (MadeChange) return &GEP;
3408
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003409 // Combine Indices - If the source pointer to this getelementptr instruction
3410 // is a getelementptr instruction, combine the indices of the two
3411 // getelementptr instructions into a single instruction.
3412 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003413 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003414 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003415 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003416 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003417 if (CE->getOpcode() == Instruction::GetElementPtr)
3418 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3419 }
3420
3421 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003422 // Note that if our source is a gep chain itself that we wait for that
3423 // chain to be resolved before we perform this transformation. This
3424 // avoids us creating a TON of code in some cases.
3425 //
3426 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3427 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3428 return 0; // Wait until our source is folded to completion.
3429
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003430 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003431
3432 // Find out whether the last index in the source GEP is a sequential idx.
3433 bool EndsWithSequential = false;
3434 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3435 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003436 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003437
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003438 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003439 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003440 // Replace: gep (gep %P, long B), long A, ...
3441 // With: T = long A+B; gep %P, T, ...
3442 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003443 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003444 if (SO1 == Constant::getNullValue(SO1->getType())) {
3445 Sum = GO1;
3446 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3447 Sum = SO1;
3448 } else {
3449 // If they aren't the same type, convert both to an integer of the
3450 // target's pointer size.
3451 if (SO1->getType() != GO1->getType()) {
3452 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3453 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3454 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3455 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3456 } else {
3457 unsigned PS = TD->getPointerSize();
3458 Instruction *Cast;
3459 if (SO1->getType()->getPrimitiveSize() == PS) {
3460 // Convert GO1 to SO1's type.
3461 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3462
3463 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3464 // Convert SO1 to GO1's type.
3465 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3466 } else {
3467 const Type *PT = TD->getIntPtrType();
3468 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3469 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3470 }
3471 }
3472 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003473 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3474 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3475 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003476 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3477 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003478 }
Chris Lattner69193f92004-04-05 01:30:19 +00003479 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003480
3481 // Recycle the GEP we already have if possible.
3482 if (SrcGEPOperands.size() == 2) {
3483 GEP.setOperand(0, SrcGEPOperands[0]);
3484 GEP.setOperand(1, Sum);
3485 return &GEP;
3486 } else {
3487 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3488 SrcGEPOperands.end()-1);
3489 Indices.push_back(Sum);
3490 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3491 }
Chris Lattner69193f92004-04-05 01:30:19 +00003492 } else if (isa<Constant>(*GEP.idx_begin()) &&
3493 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003494 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003495 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003496 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3497 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003498 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3499 }
3500
3501 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003502 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003503
Chris Lattner5f667a62004-05-07 22:09:22 +00003504 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003505 // GEP of global variable. If all of the indices for this GEP are
3506 // constants, we can promote this to a constexpr instead of an instruction.
3507
3508 // Scan for nonconstants...
3509 std::vector<Constant*> Indices;
3510 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3511 for (; I != E && isa<Constant>(*I); ++I)
3512 Indices.push_back(cast<Constant>(*I));
3513
3514 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003515 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003516
3517 // Replace all uses of the GEP with the new constexpr...
3518 return ReplaceInstUsesWith(GEP, CE);
3519 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003520 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003521 if (CE->getOpcode() == Instruction::Cast) {
3522 if (HasZeroPointerIndex) {
3523 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3524 // into : GEP [10 x ubyte]* X, long 0, ...
3525 //
3526 // This occurs when the program declares an array extern like "int X[];"
3527 //
3528 Constant *X = CE->getOperand(0);
3529 const PointerType *CPTy = cast<PointerType>(CE->getType());
3530 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3531 if (const ArrayType *XATy =
3532 dyn_cast<ArrayType>(XTy->getElementType()))
3533 if (const ArrayType *CATy =
3534 dyn_cast<ArrayType>(CPTy->getElementType()))
3535 if (CATy->getElementType() == XATy->getElementType()) {
3536 // At this point, we know that the cast source type is a pointer
3537 // to an array of the same type as the destination pointer
3538 // array. Because the array type is never stepped over (there
3539 // is a leading zero) we can fold the cast into this GEP.
3540 GEP.setOperand(0, X);
3541 return &GEP;
3542 }
3543 }
3544 }
Chris Lattnerca081252001-12-14 16:52:21 +00003545 }
3546
Chris Lattnerca081252001-12-14 16:52:21 +00003547 return 0;
3548}
3549
Chris Lattner1085bdf2002-11-04 16:18:53 +00003550Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3551 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3552 if (AI.isArrayAllocation()) // Check C != 1
3553 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3554 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003555 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003556
3557 // Create and insert the replacement instruction...
3558 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003559 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003560 else {
3561 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003562 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003563 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003564
3565 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003566
3567 // Scan to the end of the allocation instructions, to skip over a block of
3568 // allocas if possible...
3569 //
3570 BasicBlock::iterator It = New;
3571 while (isa<AllocationInst>(*It)) ++It;
3572
3573 // Now that I is pointing to the first non-allocation-inst in the block,
3574 // insert our getelementptr instruction...
3575 //
Chris Lattner69193f92004-04-05 01:30:19 +00003576 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003577 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3578
3579 // Now make everything use the getelementptr instead of the original
3580 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003581 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003582 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003583
3584 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3585 // Note that we only do this for alloca's, because malloc should allocate and
3586 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003587 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3588 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003589 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3590
Chris Lattner1085bdf2002-11-04 16:18:53 +00003591 return 0;
3592}
3593
Chris Lattner8427bff2003-12-07 01:24:23 +00003594Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3595 Value *Op = FI.getOperand(0);
3596
3597 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3598 if (CastInst *CI = dyn_cast<CastInst>(Op))
3599 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3600 FI.setOperand(0, CI->getOperand(0));
3601 return &FI;
3602 }
3603
Chris Lattnerf3a36602004-02-28 04:57:37 +00003604 // If we have 'free null' delete the instruction. This can happen in stl code
3605 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00003606 if (isa<ConstantPointerNull>(Op))
3607 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003608
Chris Lattner8427bff2003-12-07 01:24:23 +00003609 return 0;
3610}
3611
3612
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003613/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3614/// constantexpr, return the constant value being addressed by the constant
3615/// expression, or null if something is funny.
3616///
3617static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003618 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003619 return 0; // Do not allow stepping over the value!
3620
3621 // Loop over all of the operands, tracking down which value we are
3622 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003623 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3624 for (++I; I != E; ++I)
3625 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3626 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3627 assert(CU->getValue() < STy->getNumElements() &&
3628 "Struct index out of range!");
3629 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003630 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003631 } else if (isa<ConstantAggregateZero>(C)) {
3632 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3633 } else {
3634 return 0;
3635 }
3636 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3637 const ArrayType *ATy = cast<ArrayType>(*I);
3638 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3639 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003640 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003641 else if (isa<ConstantAggregateZero>(C))
3642 C = Constant::getNullValue(ATy->getElementType());
3643 else
3644 return 0;
3645 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003646 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003647 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003648 return C;
3649}
3650
Chris Lattner35e24772004-07-13 01:49:43 +00003651static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3652 User *CI = cast<User>(LI.getOperand(0));
3653
3654 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3655 if (const PointerType *SrcTy =
3656 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3657 const Type *SrcPTy = SrcTy->getElementType();
3658 if (SrcPTy->isSized() && DestPTy->isSized() &&
3659 IC.getTargetData().getTypeSize(SrcPTy) ==
3660 IC.getTargetData().getTypeSize(DestPTy) &&
3661 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3662 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3663 // Okay, we are casting from one integer or pointer type to another of
3664 // the same size. Instead of casting the pointer before the load, cast
3665 // the result of the loaded value.
3666 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003667 CI->getName(),
3668 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003669 // Now cast the result of the load.
3670 return new CastInst(NewLoad, LI.getType());
3671 }
3672 }
3673 return 0;
3674}
3675
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003676/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003677/// from this value cannot trap. If it is not obviously safe to load from the
3678/// specified pointer, we do a quick local scan of the basic block containing
3679/// ScanFrom, to determine if the address is already accessed.
3680static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3681 // If it is an alloca or global variable, it is always safe to load from.
3682 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3683
3684 // Otherwise, be a little bit agressive by scanning the local block where we
3685 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003686 // from/to. If so, the previous load or store would have already trapped,
3687 // so there is no harm doing an extra load (also, CSE will later eliminate
3688 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003689 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3690
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003691 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003692 --BBI;
3693
3694 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3695 if (LI->getOperand(0) == V) return true;
3696 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3697 if (SI->getOperand(1) == V) return true;
3698
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003699 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003700 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003701}
3702
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003703Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3704 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003705
Chris Lattner6679e462004-04-14 03:28:36 +00003706 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003707 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattner6679e462004-04-14 03:28:36 +00003708 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003709
3710 // Instcombine load (constant global) into the value loaded...
3711 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00003712 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003713 return ReplaceInstUsesWith(LI, GV->getInitializer());
3714
3715 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3716 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattner35e24772004-07-13 01:49:43 +00003717 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer87436872004-07-18 00:38:32 +00003718 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3719 if (GV->isConstant() && !GV->isExternal())
3720 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3721 return ReplaceInstUsesWith(LI, V);
Chris Lattner35e24772004-07-13 01:49:43 +00003722 } else if (CE->getOpcode() == Instruction::Cast) {
3723 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3724 return Res;
3725 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003726
3727 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003728 if (CastInst *CI = dyn_cast<CastInst>(Op))
3729 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3730 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003731
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003732 if (!LI.isVolatile() && Op->hasOneUse()) {
3733 // Change select and PHI nodes to select values instead of addresses: this
3734 // helps alias analysis out a lot, allows many others simplifications, and
3735 // exposes redundancy in the code.
3736 //
3737 // Note that we cannot do the transformation unless we know that the
3738 // introduced loads cannot trap! Something like this is valid as long as
3739 // the condition is always false: load (select bool %C, int* null, int* %G),
3740 // but it would not be valid if we transformed it to load from null
3741 // unconditionally.
3742 //
3743 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3744 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003745 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3746 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003747 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003748 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003749 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003750 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003751 return new SelectInst(SI->getCondition(), V1, V2);
3752 }
3753
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003754 // load (select (cond, null, P)) -> load P
3755 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3756 if (C->isNullValue()) {
3757 LI.setOperand(0, SI->getOperand(2));
3758 return &LI;
3759 }
3760
3761 // load (select (cond, P, null)) -> load P
3762 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3763 if (C->isNullValue()) {
3764 LI.setOperand(0, SI->getOperand(1));
3765 return &LI;
3766 }
3767
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003768 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3769 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003770 bool Safe = PN->getParent() == LI.getParent();
3771
3772 // Scan all of the instructions between the PHI and the load to make
3773 // sure there are no instructions that might possibly alter the value
3774 // loaded from the PHI.
3775 if (Safe) {
3776 BasicBlock::iterator I = &LI;
3777 for (--I; !isa<PHINode>(I); --I)
3778 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3779 Safe = false;
3780 break;
3781 }
3782 }
3783
3784 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003785 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003786 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003787 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003788
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003789 if (Safe) {
3790 // Create the PHI.
3791 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3792 InsertNewInstBefore(NewPN, *PN);
3793 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3794
3795 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3796 BasicBlock *BB = PN->getIncomingBlock(i);
3797 Value *&TheLoad = LoadMap[BB];
3798 if (TheLoad == 0) {
3799 Value *InVal = PN->getIncomingValue(i);
3800 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3801 InVal->getName()+".val"),
3802 *BB->getTerminator());
3803 }
3804 NewPN->addIncoming(TheLoad, BB);
3805 }
3806 return ReplaceInstUsesWith(LI, NewPN);
3807 }
3808 }
3809 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003810 return 0;
3811}
3812
3813
Chris Lattner9eef8a72003-06-04 04:46:00 +00003814Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3815 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003816 Value *X;
3817 BasicBlock *TrueDest;
3818 BasicBlock *FalseDest;
3819 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3820 !isa<Constant>(X)) {
3821 // Swap Destinations and condition...
3822 BI.setCondition(X);
3823 BI.setSuccessor(0, FalseDest);
3824 BI.setSuccessor(1, TrueDest);
3825 return &BI;
3826 }
3827
3828 // Cannonicalize setne -> seteq
3829 Instruction::BinaryOps Op; Value *Y;
3830 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3831 TrueDest, FalseDest)))
3832 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3833 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3834 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3835 std::string Name = I->getName(); I->setName("");
3836 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3837 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003838 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003839 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003840 BI.setSuccessor(0, FalseDest);
3841 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003842 removeFromWorkList(I);
3843 I->getParent()->getInstList().erase(I);
3844 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003845 return &BI;
3846 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003847
Chris Lattner9eef8a72003-06-04 04:46:00 +00003848 return 0;
3849}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003850
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003851Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3852 Value *Cond = SI.getCondition();
3853 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3854 if (I->getOpcode() == Instruction::Add)
3855 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3856 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3857 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3858 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3859 AddRHS));
3860 SI.setOperand(0, I->getOperand(0));
3861 WorkList.push_back(I);
3862 return &SI;
3863 }
3864 }
3865 return 0;
3866}
3867
Chris Lattnerca081252001-12-14 16:52:21 +00003868
Chris Lattner99f48c62002-09-02 04:59:56 +00003869void InstCombiner::removeFromWorkList(Instruction *I) {
3870 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3871 WorkList.end());
3872}
3873
Chris Lattner113f4f42002-06-25 16:13:24 +00003874bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003875 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003876 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003877
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003878 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3879 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003880
Chris Lattnerca081252001-12-14 16:52:21 +00003881
3882 while (!WorkList.empty()) {
3883 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3884 WorkList.pop_back();
3885
Misha Brukman632df282002-10-29 23:06:16 +00003886 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003887 // Check to see if we can DIE the instruction...
3888 if (isInstructionTriviallyDead(I)) {
3889 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003890 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003891 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003892 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003893
3894 I->getParent()->getInstList().erase(I);
3895 removeFromWorkList(I);
3896 continue;
3897 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003898
Misha Brukman632df282002-10-29 23:06:16 +00003899 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003900 if (Constant *C = ConstantFoldInstruction(I)) {
3901 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003902 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003903 ReplaceInstUsesWith(*I, C);
3904
Chris Lattner99f48c62002-09-02 04:59:56 +00003905 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003906 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003907 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003908 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003909 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003910
Chris Lattnerca081252001-12-14 16:52:21 +00003911 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003912 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003913 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003914 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003915 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003916 DEBUG(std::cerr << "IC: Old = " << *I
3917 << " New = " << *Result);
3918
Chris Lattner396dbfe2004-06-09 05:08:07 +00003919 // Everything uses the new instruction now.
3920 I->replaceAllUsesWith(Result);
3921
3922 // Push the new instruction and any users onto the worklist.
3923 WorkList.push_back(Result);
3924 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003925
3926 // Move the name to the new instruction first...
3927 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003928 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003929
3930 // Insert the new instruction into the basic block...
3931 BasicBlock *InstParent = I->getParent();
3932 InstParent->getInstList().insert(I, Result);
3933
Chris Lattner63d75af2004-05-01 23:27:23 +00003934 // Make sure that we reprocess all operands now that we reduced their
3935 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003936 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3937 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3938 WorkList.push_back(OpI);
3939
Chris Lattner396dbfe2004-06-09 05:08:07 +00003940 // Instructions can end up on the worklist more than once. Make sure
3941 // we do not process an instruction that has been deleted.
3942 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003943
3944 // Erase the old instruction.
3945 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003946 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003947 DEBUG(std::cerr << "IC: MOD = " << *I);
3948
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003949 // If the instruction was modified, it's possible that it is now dead.
3950 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003951 if (isInstructionTriviallyDead(I)) {
3952 // Make sure we process all operands now that we are reducing their
3953 // use counts.
3954 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3955 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3956 WorkList.push_back(OpI);
3957
3958 // Instructions may end up in the worklist more than once. Erase all
3959 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003960 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003961 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003962 } else {
3963 WorkList.push_back(Result);
3964 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003965 }
Chris Lattner053c0932002-05-14 15:24:07 +00003966 }
Chris Lattner260ab202002-04-18 17:39:14 +00003967 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003968 }
3969 }
3970
Chris Lattner260ab202002-04-18 17:39:14 +00003971 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003972}
3973
Brian Gaeke38b79e82004-07-27 17:43:21 +00003974FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003975 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003976}
Brian Gaeke960707c2003-11-11 22:41:34 +00003977