blob: ec50320056d488d4e41712159ca7e422fd86840e [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
626 // Try to fold constant add into select arguments.
627 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
628 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
629 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000630 }
631
Chris Lattner113f4f42002-06-25 16:13:24 +0000632 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000633}
634
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000635// isSignBit - Return true if the value represented by the constant only has the
636// highest order bit set.
637static bool isSignBit(ConstantInt *CI) {
638 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
639 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
640}
641
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000642static unsigned getTypeSizeInBits(const Type *Ty) {
643 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
644}
645
Chris Lattner022167f2004-03-13 00:11:49 +0000646/// RemoveNoopCast - Strip off nonconverting casts from the value.
647///
648static Value *RemoveNoopCast(Value *V) {
649 if (CastInst *CI = dyn_cast<CastInst>(V)) {
650 const Type *CTy = CI->getType();
651 const Type *OpTy = CI->getOperand(0)->getType();
652 if (CTy->isInteger() && OpTy->isInteger()) {
653 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
654 return RemoveNoopCast(CI->getOperand(0));
655 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
656 return RemoveNoopCast(CI->getOperand(0));
657 }
658 return V;
659}
660
Chris Lattner113f4f42002-06-25 16:13:24 +0000661Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000662 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000663
Chris Lattnere6794492002-08-12 21:17:25 +0000664 if (Op0 == Op1) // sub X, X -> 0
665 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000666
Chris Lattnere6794492002-08-12 21:17:25 +0000667 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000668 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000669 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000670
Chris Lattner8f2f5982003-11-05 01:06:05 +0000671 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
672 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000673 if (C->isAllOnesValue())
674 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000675
Chris Lattner8f2f5982003-11-05 01:06:05 +0000676 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000677 Value *X;
678 if (match(Op1, m_Not(m_Value(X))))
679 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000680 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000681 // -((uint)X >> 31) -> ((int)X >> 31)
682 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000683 if (C->isNullValue()) {
684 Value *NoopCastedRHS = RemoveNoopCast(Op1);
685 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000686 if (SI->getOpcode() == Instruction::Shr)
687 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
688 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000689 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000690 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000691 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000692 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000693 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000694 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000695 // Ok, the transformation is safe. Insert a cast of the incoming
696 // value, then the new shift, then the new cast.
697 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
698 SI->getOperand(0)->getName());
699 Value *InV = InsertNewInstBefore(FirstCast, I);
700 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
701 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000702 if (NewShift->getType() == I.getType())
703 return NewShift;
704 else {
705 InV = InsertNewInstBefore(NewShift, I);
706 return new CastInst(NewShift, I.getType());
707 }
Chris Lattner92295c52004-03-12 23:53:13 +0000708 }
709 }
Chris Lattner022167f2004-03-13 00:11:49 +0000710 }
Chris Lattner183b3362004-04-09 19:05:30 +0000711
712 // Try to fold constant sub into select arguments.
713 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
714 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
715 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000716
717 if (isa<PHINode>(Op0))
718 if (Instruction *NV = FoldOpIntoPhi(I))
719 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000720 }
721
Chris Lattner3082c5a2003-02-18 19:28:33 +0000722 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000723 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000724 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
725 // is not used by anyone else...
726 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000727 if (Op1I->getOpcode() == Instruction::Sub &&
728 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000729 // Swap the two operands of the subexpr...
730 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
731 Op1I->setOperand(0, IIOp1);
732 Op1I->setOperand(1, IIOp0);
733
734 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000735 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000736 }
737
738 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
739 //
740 if (Op1I->getOpcode() == Instruction::And &&
741 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
742 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
743
Chris Lattner396dbfe2004-06-09 05:08:07 +0000744 Value *NewNot =
745 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000746 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000747 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000748
749 // X - X*C --> X * (1-C)
750 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000751 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000752 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000753 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000754 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000755 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000756 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000757 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000758
Chris Lattner57c8d992003-02-18 19:57:07 +0000759 // X*C - X --> X * (C-1)
760 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000761 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000762 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000763 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000764 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000765 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000766 }
767
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000768 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000769}
770
Chris Lattnere79e8542004-02-23 06:38:22 +0000771/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
772/// really just returns true if the most significant (sign) bit is set.
773static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
774 if (RHS->getType()->isSigned()) {
775 // True if source is LHS < 0 or LHS <= -1
776 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
777 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
778 } else {
779 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
780 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
781 // the size of the integer type.
782 if (Opcode == Instruction::SetGE)
783 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
784 if (Opcode == Instruction::SetGT)
785 return RHSC->getValue() ==
786 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
787 }
788 return false;
789}
790
Chris Lattner113f4f42002-06-25 16:13:24 +0000791Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000792 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000793 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000794
Chris Lattnere6794492002-08-12 21:17:25 +0000795 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000796 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
797 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000798
799 // ((X << C1)*C2) == (X * (C2 << C1))
800 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
801 if (SI->getOpcode() == Instruction::Shl)
802 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000803 return BinaryOperator::createMul(SI->getOperand(0),
804 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000805
Chris Lattnercce81be2003-09-11 22:24:54 +0000806 if (CI->isNullValue())
807 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
808 if (CI->equalsInt(1)) // X * 1 == X
809 return ReplaceInstUsesWith(I, Op0);
810 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000811 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000812
Chris Lattnercce81be2003-09-11 22:24:54 +0000813 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000814 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
815 return new ShiftInst(Instruction::Shl, Op0,
816 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000817 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000818 if (Op1F->isNullValue())
819 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000820
Chris Lattner3082c5a2003-02-18 19:28:33 +0000821 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
822 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
823 if (Op1F->getValue() == 1.0)
824 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
825 }
Chris Lattner183b3362004-04-09 19:05:30 +0000826
827 // Try to fold constant mul into select arguments.
828 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
829 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
830 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000831
832 if (isa<PHINode>(Op0))
833 if (Instruction *NV = FoldOpIntoPhi(I))
834 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000835 }
836
Chris Lattner934a64cf2003-03-10 23:23:04 +0000837 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
838 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000839 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000840
Chris Lattner2635b522004-02-23 05:39:21 +0000841 // If one of the operands of the multiply is a cast from a boolean value, then
842 // we know the bool is either zero or one, so this is a 'masking' multiply.
843 // See if we can simplify things based on how the boolean was originally
844 // formed.
845 CastInst *BoolCast = 0;
846 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
847 if (CI->getOperand(0)->getType() == Type::BoolTy)
848 BoolCast = CI;
849 if (!BoolCast)
850 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
851 if (CI->getOperand(0)->getType() == Type::BoolTy)
852 BoolCast = CI;
853 if (BoolCast) {
854 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
855 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
856 const Type *SCOpTy = SCIOp0->getType();
857
Chris Lattnere79e8542004-02-23 06:38:22 +0000858 // If the setcc is true iff the sign bit of X is set, then convert this
859 // multiply into a shift/and combination.
860 if (isa<ConstantInt>(SCIOp1) &&
861 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000862 // Shift the X value right to turn it into "all signbits".
863 Constant *Amt = ConstantUInt::get(Type::UByteTy,
864 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000865 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000866 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000867 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
868 SCIOp0->getName()), I);
869 }
870
871 Value *V =
872 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
873 BoolCast->getOperand(0)->getName()+
874 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000875
876 // If the multiply type is not the same as the source type, sign extend
877 // or truncate to the multiply type.
878 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000879 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000880
881 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000882 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000883 }
884 }
885 }
886
Chris Lattner113f4f42002-06-25 16:13:24 +0000887 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000888}
889
Chris Lattner113f4f42002-06-25 16:13:24 +0000890Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000891 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000892 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000893 if (RHS->equalsInt(1))
894 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000895
Chris Lattnere20c3342004-04-26 14:01:59 +0000896 // div X, -1 == -X
897 if (RHS->isAllOnesValue())
898 return BinaryOperator::createNeg(I.getOperand(0));
899
Chris Lattner272d5ca2004-09-28 18:22:15 +0000900 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
901 if (LHS->getOpcode() == Instruction::Div)
902 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000903 // (X / C1) / C2 -> X / (C1*C2)
904 return BinaryOperator::createDiv(LHS->getOperand(0),
905 ConstantExpr::getMul(RHS, LHSRHS));
906 }
907
Chris Lattner3082c5a2003-02-18 19:28:33 +0000908 // Check to see if this is an unsigned division with an exact power of 2,
909 // if so, convert to a right shift.
910 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
911 if (uint64_t Val = C->getValue()) // Don't break X / 0
912 if (uint64_t C = Log2(Val))
913 return new ShiftInst(Instruction::Shr, I.getOperand(0),
914 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000915
916 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
917 if (Instruction *NV = FoldOpIntoPhi(I))
918 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000919 }
920
921 // 0 / X == 0, we don't need to preserve faults!
922 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
923 if (LHS->equalsInt(0))
924 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
925
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000926 return 0;
927}
928
929
Chris Lattner113f4f42002-06-25 16:13:24 +0000930Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000931 if (I.getType()->isSigned())
932 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000933 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000934 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000935 // X % -Y -> X % Y
936 AddUsesToWorkList(I);
937 I.setOperand(1, RHSNeg);
938 return &I;
939 }
940
Chris Lattner3082c5a2003-02-18 19:28:33 +0000941 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
942 if (RHS->equalsInt(1)) // X % 1 == 0
943 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
944
945 // Check to see if this is an unsigned remainder with an exact power of 2,
946 // if so, convert to a bitwise and.
947 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
948 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000949 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000950 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000951 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000952 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
953 if (Instruction *NV = FoldOpIntoPhi(I))
954 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000955 }
956
957 // 0 % X == 0, we don't need to preserve faults!
958 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
959 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000960 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
961
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000962 return 0;
963}
964
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000965// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000966static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000967 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
968 // Calculate -1 casted to the right type...
969 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
970 uint64_t Val = ~0ULL; // All ones
971 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
972 return CU->getValue() == Val-1;
973 }
974
975 const ConstantSInt *CS = cast<ConstantSInt>(C);
976
977 // Calculate 0111111111..11111
978 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
979 int64_t Val = INT64_MAX; // All ones
980 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
981 return CS->getValue() == Val-1;
982}
983
984// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000985static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000986 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
987 return CU->getValue() == 1;
988
989 const ConstantSInt *CS = cast<ConstantSInt>(C);
990
991 // Calculate 1111111111000000000000
992 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
993 int64_t Val = -1; // All ones
994 Val <<= TypeBits-1; // Shift over to the right spot
995 return CS->getValue() == Val+1;
996}
997
Chris Lattner35167c32004-06-09 07:59:58 +0000998// isOneBitSet - Return true if there is exactly one bit set in the specified
999// constant.
1000static bool isOneBitSet(const ConstantInt *CI) {
1001 uint64_t V = CI->getRawValue();
1002 return V && (V & (V-1)) == 0;
1003}
1004
Chris Lattner8fc5af42004-09-23 21:46:38 +00001005#if 0 // Currently unused
1006// isLowOnes - Return true if the constant is of the form 0+1+.
1007static bool isLowOnes(const ConstantInt *CI) {
1008 uint64_t V = CI->getRawValue();
1009
1010 // There won't be bits set in parts that the type doesn't contain.
1011 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1012
1013 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1014 return U && V && (U & V) == 0;
1015}
1016#endif
1017
1018// isHighOnes - Return true if the constant is of the form 1+0+.
1019// This is the same as lowones(~X).
1020static bool isHighOnes(const ConstantInt *CI) {
1021 uint64_t V = ~CI->getRawValue();
1022
1023 // There won't be bits set in parts that the type doesn't contain.
1024 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1025
1026 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1027 return U && V && (U & V) == 0;
1028}
1029
1030
Chris Lattner3ac7c262003-08-13 20:16:26 +00001031/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1032/// are carefully arranged to allow folding of expressions such as:
1033///
1034/// (A < B) | (A > B) --> (A != B)
1035///
1036/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1037/// represents that the comparison is true if A == B, and bit value '1' is true
1038/// if A < B.
1039///
1040static unsigned getSetCondCode(const SetCondInst *SCI) {
1041 switch (SCI->getOpcode()) {
1042 // False -> 0
1043 case Instruction::SetGT: return 1;
1044 case Instruction::SetEQ: return 2;
1045 case Instruction::SetGE: return 3;
1046 case Instruction::SetLT: return 4;
1047 case Instruction::SetNE: return 5;
1048 case Instruction::SetLE: return 6;
1049 // True -> 7
1050 default:
1051 assert(0 && "Invalid SetCC opcode!");
1052 return 0;
1053 }
1054}
1055
1056/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1057/// opcode and two operands into either a constant true or false, or a brand new
1058/// SetCC instruction.
1059static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1060 switch (Opcode) {
1061 case 0: return ConstantBool::False;
1062 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1063 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1064 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1065 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1066 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1067 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1068 case 7: return ConstantBool::True;
1069 default: assert(0 && "Illegal SetCCCode!"); return 0;
1070 }
1071}
1072
1073// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1074struct FoldSetCCLogical {
1075 InstCombiner &IC;
1076 Value *LHS, *RHS;
1077 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1078 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1079 bool shouldApply(Value *V) const {
1080 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1081 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1082 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1083 return false;
1084 }
1085 Instruction *apply(BinaryOperator &Log) const {
1086 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1087 if (SCI->getOperand(0) != LHS) {
1088 assert(SCI->getOperand(1) == LHS);
1089 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1090 }
1091
1092 unsigned LHSCode = getSetCondCode(SCI);
1093 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1094 unsigned Code;
1095 switch (Log.getOpcode()) {
1096 case Instruction::And: Code = LHSCode & RHSCode; break;
1097 case Instruction::Or: Code = LHSCode | RHSCode; break;
1098 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001099 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001100 }
1101
1102 Value *RV = getSetCCValue(Code, LHS, RHS);
1103 if (Instruction *I = dyn_cast<Instruction>(RV))
1104 return I;
1105 // Otherwise, it's a constant boolean value...
1106 return IC.ReplaceInstUsesWith(Log, RV);
1107 }
1108};
1109
1110
Chris Lattnerba1cb382003-09-19 17:17:26 +00001111// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1112// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1113// guaranteed to be either a shift instruction or a binary operator.
1114Instruction *InstCombiner::OptAndOp(Instruction *Op,
1115 ConstantIntegral *OpRHS,
1116 ConstantIntegral *AndRHS,
1117 BinaryOperator &TheAnd) {
1118 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001119 Constant *Together = 0;
1120 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001121 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001122
Chris Lattnerba1cb382003-09-19 17:17:26 +00001123 switch (Op->getOpcode()) {
1124 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001125 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001126 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001127 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001128 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001129 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1130 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001131 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001132 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001133 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001134 }
1135 break;
1136 case Instruction::Or:
1137 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001138 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001139 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001140 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001141 if (Together == AndRHS) // (X | C) & C --> C
1142 return ReplaceInstUsesWith(TheAnd, AndRHS);
1143
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001144 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001145 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1146 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001147 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001148 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001149 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001150 }
1151 }
1152 break;
1153 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001154 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001155 // Adding a one to a single bit bit-field should be turned into an XOR
1156 // of the bit. First thing to check is to see if this AND is with a
1157 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001158 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001159
1160 // Clear bits that are not part of the constant.
1161 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1162
1163 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001164 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001165 // Ok, at this point, we know that we are masking the result of the
1166 // ADD down to exactly one bit. If the constant we are adding has
1167 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001168 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001169
1170 // Check to see if any bits below the one bit set in AndRHSV are set.
1171 if ((AddRHS & (AndRHSV-1)) == 0) {
1172 // If not, the only thing that can effect the output of the AND is
1173 // the bit specified by AndRHSV. If that bit is set, the effect of
1174 // the XOR is to toggle the bit. If it is clear, then the ADD has
1175 // no effect.
1176 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1177 TheAnd.setOperand(0, X);
1178 return &TheAnd;
1179 } else {
1180 std::string Name = Op->getName(); Op->setName("");
1181 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001182 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001183 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001184 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001185 }
1186 }
1187 }
1188 }
1189 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001190
1191 case Instruction::Shl: {
1192 // We know that the AND will not produce any of the bits shifted in, so if
1193 // the anded constant includes them, clear them now!
1194 //
1195 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001196 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1197 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1198
1199 if (CI == ShlMask) { // Masking out bits that the shift already masks
1200 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1201 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001202 TheAnd.setOperand(1, CI);
1203 return &TheAnd;
1204 }
1205 break;
1206 }
1207 case Instruction::Shr:
1208 // We know that the AND will not produce any of the bits shifted in, so if
1209 // the anded constant includes them, clear them now! This only applies to
1210 // unsigned shifts, because a signed shr may bring in set bits!
1211 //
1212 if (AndRHS->getType()->isUnsigned()) {
1213 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001214 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1215 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1216
1217 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1218 return ReplaceInstUsesWith(TheAnd, Op);
1219 } else if (CI != AndRHS) {
1220 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001221 return &TheAnd;
1222 }
Chris Lattner7e794272004-09-24 15:21:34 +00001223 } else { // Signed shr.
1224 // See if this is shifting in some sign extension, then masking it out
1225 // with an and.
1226 if (Op->hasOneUse()) {
1227 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1228 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1229 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1230 if (CI == ShrMask) { // Masking out bits shifted in.
1231 // Make the argument unsigned.
1232 Value *ShVal = Op->getOperand(0);
1233 ShVal = InsertCastBefore(ShVal,
1234 ShVal->getType()->getUnsignedVersion(),
1235 TheAnd);
1236 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1237 OpRHS, Op->getName()),
1238 TheAnd);
1239 return new CastInst(ShVal, Op->getType());
1240 }
1241 }
Chris Lattner2da29172003-09-19 19:05:02 +00001242 }
1243 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001244 }
1245 return 0;
1246}
1247
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001248
Chris Lattner6862fbd2004-09-29 17:40:11 +00001249/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1250/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1251/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1252/// insert new instructions.
1253Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1254 bool Inside, Instruction &IB) {
1255 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1256 "Lo is not <= Hi in range emission code!");
1257 if (Inside) {
1258 if (Lo == Hi) // Trivially false.
1259 return new SetCondInst(Instruction::SetNE, V, V);
1260 if (cast<ConstantIntegral>(Lo)->isMinValue())
1261 return new SetCondInst(Instruction::SetLT, V, Hi);
1262
1263 Constant *AddCST = ConstantExpr::getNeg(Lo);
1264 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1265 InsertNewInstBefore(Add, IB);
1266 // Convert to unsigned for the comparison.
1267 const Type *UnsType = Add->getType()->getUnsignedVersion();
1268 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1269 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1270 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1271 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1272 }
1273
1274 if (Lo == Hi) // Trivially true.
1275 return new SetCondInst(Instruction::SetEQ, V, V);
1276
1277 Hi = SubOne(cast<ConstantInt>(Hi));
1278 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1279 return new SetCondInst(Instruction::SetGT, V, Hi);
1280
1281 // Emit X-Lo > Hi-Lo-1
1282 Constant *AddCST = ConstantExpr::getNeg(Lo);
1283 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1284 InsertNewInstBefore(Add, IB);
1285 // Convert to unsigned for the comparison.
1286 const Type *UnsType = Add->getType()->getUnsignedVersion();
1287 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1288 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1289 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1290 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1291}
1292
1293
Chris Lattner113f4f42002-06-25 16:13:24 +00001294Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001295 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001296 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001297
1298 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001299 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1300 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001301
1302 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001303 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001304 if (RHS->isAllOnesValue())
1305 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001306
Chris Lattnerba1cb382003-09-19 17:17:26 +00001307 // Optimize a variety of ((val OP C1) & C2) combinations...
1308 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1309 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001310 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001311 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001312 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1313 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001314 }
Chris Lattner183b3362004-04-09 19:05:30 +00001315
1316 // Try to fold constant and into select arguments.
1317 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1318 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1319 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001320 if (isa<PHINode>(Op0))
1321 if (Instruction *NV = FoldOpIntoPhi(I))
1322 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001323 }
1324
Chris Lattnerbb74e222003-03-10 23:06:50 +00001325 Value *Op0NotVal = dyn_castNotVal(Op0);
1326 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001327
Chris Lattner023a4832004-06-18 06:07:51 +00001328 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1329 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1330
Misha Brukman9c003d82004-07-30 12:50:08 +00001331 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001332 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001333 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1334 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001335 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001336 return BinaryOperator::createNot(Or);
1337 }
1338
Chris Lattner623826c2004-09-28 21:48:02 +00001339 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1340 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001341 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1342 return R;
1343
Chris Lattner623826c2004-09-28 21:48:02 +00001344 Value *LHSVal, *RHSVal;
1345 ConstantInt *LHSCst, *RHSCst;
1346 Instruction::BinaryOps LHSCC, RHSCC;
1347 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1348 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1349 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1350 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1351 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1352 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1353 // Ensure that the larger constant is on the RHS.
1354 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1355 SetCondInst *LHS = cast<SetCondInst>(Op0);
1356 if (cast<ConstantBool>(Cmp)->getValue()) {
1357 std::swap(LHS, RHS);
1358 std::swap(LHSCst, RHSCst);
1359 std::swap(LHSCC, RHSCC);
1360 }
1361
1362 // At this point, we know we have have two setcc instructions
1363 // comparing a value against two constants and and'ing the result
1364 // together. Because of the above check, we know that we only have
1365 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1366 // FoldSetCCLogical check above), that the two constants are not
1367 // equal.
1368 assert(LHSCst != RHSCst && "Compares not folded above?");
1369
1370 switch (LHSCC) {
1371 default: assert(0 && "Unknown integer condition code!");
1372 case Instruction::SetEQ:
1373 switch (RHSCC) {
1374 default: assert(0 && "Unknown integer condition code!");
1375 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1376 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1377 return ReplaceInstUsesWith(I, ConstantBool::False);
1378 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1379 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1380 return ReplaceInstUsesWith(I, LHS);
1381 }
1382 case Instruction::SetNE:
1383 switch (RHSCC) {
1384 default: assert(0 && "Unknown integer condition code!");
1385 case Instruction::SetLT:
1386 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1387 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1388 break; // (X != 13 & X < 15) -> no change
1389 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1390 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1391 return ReplaceInstUsesWith(I, RHS);
1392 case Instruction::SetNE:
1393 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1394 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1395 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1396 LHSVal->getName()+".off");
1397 InsertNewInstBefore(Add, I);
1398 const Type *UnsType = Add->getType()->getUnsignedVersion();
1399 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1400 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1401 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1402 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1403 }
1404 break; // (X != 13 & X != 15) -> no change
1405 }
1406 break;
1407 case Instruction::SetLT:
1408 switch (RHSCC) {
1409 default: assert(0 && "Unknown integer condition code!");
1410 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1411 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1412 return ReplaceInstUsesWith(I, ConstantBool::False);
1413 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1414 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1415 return ReplaceInstUsesWith(I, LHS);
1416 }
1417 case Instruction::SetGT:
1418 switch (RHSCC) {
1419 default: assert(0 && "Unknown integer condition code!");
1420 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1421 return ReplaceInstUsesWith(I, LHS);
1422 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1423 return ReplaceInstUsesWith(I, RHS);
1424 case Instruction::SetNE:
1425 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1426 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1427 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001428 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1429 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001430 }
1431 }
1432 }
1433 }
1434
Chris Lattner113f4f42002-06-25 16:13:24 +00001435 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001436}
1437
Chris Lattner113f4f42002-06-25 16:13:24 +00001438Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001439 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001440 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001441
1442 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001443 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1444 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001445
1446 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001447 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001448 if (RHS->isAllOnesValue())
1449 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001450
Chris Lattnerd4252a72004-07-30 07:50:03 +00001451 ConstantInt *C1; Value *X;
1452 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1453 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1454 std::string Op0Name = Op0->getName(); Op0->setName("");
1455 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1456 InsertNewInstBefore(Or, I);
1457 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1458 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001459
Chris Lattnerd4252a72004-07-30 07:50:03 +00001460 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1461 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1462 std::string Op0Name = Op0->getName(); Op0->setName("");
1463 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1464 InsertNewInstBefore(Or, I);
1465 return BinaryOperator::createXor(Or,
1466 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001467 }
Chris Lattner183b3362004-04-09 19:05:30 +00001468
1469 // Try to fold constant and into select arguments.
1470 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1471 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1472 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001473 if (isa<PHINode>(Op0))
1474 if (Instruction *NV = FoldOpIntoPhi(I))
1475 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001476 }
1477
Chris Lattner812aab72003-08-12 19:11:07 +00001478 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001479 Value *A, *B; ConstantInt *C1, *C2;
1480 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1481 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1482 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001483
Chris Lattnerd4252a72004-07-30 07:50:03 +00001484 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1485 if (A == Op1) // ~A | A == -1
1486 return ReplaceInstUsesWith(I,
1487 ConstantIntegral::getAllOnesValue(I.getType()));
1488 } else {
1489 A = 0;
1490 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001491
Chris Lattnerd4252a72004-07-30 07:50:03 +00001492 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1493 if (Op0 == B)
1494 return ReplaceInstUsesWith(I,
1495 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001496
Misha Brukman9c003d82004-07-30 12:50:08 +00001497 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001498 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1499 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1500 I.getName()+".demorgan"), I);
1501 return BinaryOperator::createNot(And);
1502 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001503 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001504
Chris Lattner3ac7c262003-08-13 20:16:26 +00001505 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001506 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001507 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1508 return R;
1509
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001510 Value *LHSVal, *RHSVal;
1511 ConstantInt *LHSCst, *RHSCst;
1512 Instruction::BinaryOps LHSCC, RHSCC;
1513 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1514 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1515 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1516 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1517 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1518 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1519 // Ensure that the larger constant is on the RHS.
1520 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1521 SetCondInst *LHS = cast<SetCondInst>(Op0);
1522 if (cast<ConstantBool>(Cmp)->getValue()) {
1523 std::swap(LHS, RHS);
1524 std::swap(LHSCst, RHSCst);
1525 std::swap(LHSCC, RHSCC);
1526 }
1527
1528 // At this point, we know we have have two setcc instructions
1529 // comparing a value against two constants and or'ing the result
1530 // together. Because of the above check, we know that we only have
1531 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1532 // FoldSetCCLogical check above), that the two constants are not
1533 // equal.
1534 assert(LHSCst != RHSCst && "Compares not folded above?");
1535
1536 switch (LHSCC) {
1537 default: assert(0 && "Unknown integer condition code!");
1538 case Instruction::SetEQ:
1539 switch (RHSCC) {
1540 default: assert(0 && "Unknown integer condition code!");
1541 case Instruction::SetEQ:
1542 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1543 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1544 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1545 LHSVal->getName()+".off");
1546 InsertNewInstBefore(Add, I);
1547 const Type *UnsType = Add->getType()->getUnsignedVersion();
1548 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1549 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1550 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1551 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1552 }
1553 break; // (X == 13 | X == 15) -> no change
1554
1555 case Instruction::SetGT:
1556 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1557 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1558 break; // (X == 13 | X > 15) -> no change
1559 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1560 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1561 return ReplaceInstUsesWith(I, RHS);
1562 }
1563 break;
1564 case Instruction::SetNE:
1565 switch (RHSCC) {
1566 default: assert(0 && "Unknown integer condition code!");
1567 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1568 return ReplaceInstUsesWith(I, RHS);
1569 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1570 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1571 return ReplaceInstUsesWith(I, LHS);
1572 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1573 return ReplaceInstUsesWith(I, ConstantBool::True);
1574 }
1575 break;
1576 case Instruction::SetLT:
1577 switch (RHSCC) {
1578 default: assert(0 && "Unknown integer condition code!");
1579 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1580 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001581 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1582 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001583 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1584 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1585 return ReplaceInstUsesWith(I, RHS);
1586 }
1587 break;
1588 case Instruction::SetGT:
1589 switch (RHSCC) {
1590 default: assert(0 && "Unknown integer condition code!");
1591 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1592 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1593 return ReplaceInstUsesWith(I, LHS);
1594 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1595 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1596 return ReplaceInstUsesWith(I, ConstantBool::True);
1597 }
1598 }
1599 }
1600 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001601 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001602}
1603
Chris Lattnerc2076352004-02-16 01:20:27 +00001604// XorSelf - Implements: X ^ X --> 0
1605struct XorSelf {
1606 Value *RHS;
1607 XorSelf(Value *rhs) : RHS(rhs) {}
1608 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1609 Instruction *apply(BinaryOperator &Xor) const {
1610 return &Xor;
1611 }
1612};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001613
1614
Chris Lattner113f4f42002-06-25 16:13:24 +00001615Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001616 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001617 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001618
Chris Lattnerc2076352004-02-16 01:20:27 +00001619 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1620 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1621 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001622 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001623 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001624
Chris Lattner97638592003-07-23 21:37:07 +00001625 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001626 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001627 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001628 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001629
Chris Lattner97638592003-07-23 21:37:07 +00001630 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001631 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001632 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001633 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001634 return new SetCondInst(SCI->getInverseCondition(),
1635 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001636
Chris Lattner8f2f5982003-11-05 01:06:05 +00001637 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001638 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1639 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001640 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1641 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001642 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001643 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001644 }
Chris Lattner023a4832004-06-18 06:07:51 +00001645
1646 // ~(~X & Y) --> (X | ~Y)
1647 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1648 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1649 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1650 Instruction *NotY =
1651 BinaryOperator::createNot(Op0I->getOperand(1),
1652 Op0I->getOperand(1)->getName()+".not");
1653 InsertNewInstBefore(NotY, I);
1654 return BinaryOperator::createOr(Op0NotVal, NotY);
1655 }
1656 }
Chris Lattner97638592003-07-23 21:37:07 +00001657
1658 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001659 switch (Op0I->getOpcode()) {
1660 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001661 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001662 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001663 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1664 return BinaryOperator::createSub(
1665 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001666 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001667 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001668 }
Chris Lattnere5806662003-11-04 23:50:51 +00001669 break;
1670 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001671 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001672 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1673 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001674 break;
1675 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001676 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001677 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001678 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001679 break;
1680 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001681 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001682 }
Chris Lattner183b3362004-04-09 19:05:30 +00001683
1684 // Try to fold constant and into select arguments.
1685 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1686 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1687 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001688 if (isa<PHINode>(Op0))
1689 if (Instruction *NV = FoldOpIntoPhi(I))
1690 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001691 }
1692
Chris Lattnerbb74e222003-03-10 23:06:50 +00001693 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001694 if (X == Op1)
1695 return ReplaceInstUsesWith(I,
1696 ConstantIntegral::getAllOnesValue(I.getType()));
1697
Chris Lattnerbb74e222003-03-10 23:06:50 +00001698 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001699 if (X == Op0)
1700 return ReplaceInstUsesWith(I,
1701 ConstantIntegral::getAllOnesValue(I.getType()));
1702
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001703 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001704 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001705 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1706 cast<BinaryOperator>(Op1I)->swapOperands();
1707 I.swapOperands();
1708 std::swap(Op0, Op1);
1709 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1710 I.swapOperands();
1711 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001712 }
1713 } else if (Op1I->getOpcode() == Instruction::Xor) {
1714 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1715 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1716 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1717 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1718 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001719
1720 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001721 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001722 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1723 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001724 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001725 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1726 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001727 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001728 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001729 } else if (Op0I->getOpcode() == Instruction::Xor) {
1730 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1731 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1732 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1733 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001734 }
1735
Chris Lattner7aa2d472004-08-01 19:42:59 +00001736 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001737 Value *A, *B; ConstantInt *C1, *C2;
1738 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1739 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001740 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001741 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001742
Chris Lattner3ac7c262003-08-13 20:16:26 +00001743 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1744 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1745 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1746 return R;
1747
Chris Lattner113f4f42002-06-25 16:13:24 +00001748 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001749}
1750
Chris Lattner6862fbd2004-09-29 17:40:11 +00001751/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1752/// overflowed for this type.
1753static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1754 ConstantInt *In2) {
1755 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1756 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1757}
1758
1759static bool isPositive(ConstantInt *C) {
1760 return cast<ConstantSInt>(C)->getValue() >= 0;
1761}
1762
1763/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1764/// overflowed for this type.
1765static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1766 ConstantInt *In2) {
1767 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1768
1769 if (In1->getType()->isUnsigned())
1770 return cast<ConstantUInt>(Result)->getValue() <
1771 cast<ConstantUInt>(In1)->getValue();
1772 if (isPositive(In1) != isPositive(In2))
1773 return false;
1774 if (isPositive(In1))
1775 return cast<ConstantSInt>(Result)->getValue() <
1776 cast<ConstantSInt>(In1)->getValue();
1777 return cast<ConstantSInt>(Result)->getValue() >
1778 cast<ConstantSInt>(In1)->getValue();
1779}
1780
Chris Lattner113f4f42002-06-25 16:13:24 +00001781Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001782 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001783 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1784 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001785
1786 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001787 if (Op0 == Op1)
1788 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001789
Chris Lattnerd07283a2003-08-13 05:38:46 +00001790 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1791 if (isa<ConstantPointerNull>(Op1) &&
1792 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001793 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1794
Chris Lattnerd07283a2003-08-13 05:38:46 +00001795
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001796 // setcc's with boolean values can always be turned into bitwise operations
1797 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001798 switch (I.getOpcode()) {
1799 default: assert(0 && "Invalid setcc instruction!");
1800 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001801 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001802 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001803 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001804 }
Chris Lattner4456da62004-08-11 00:50:51 +00001805 case Instruction::SetNE:
1806 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001807
Chris Lattner4456da62004-08-11 00:50:51 +00001808 case Instruction::SetGT:
1809 std::swap(Op0, Op1); // Change setgt -> setlt
1810 // FALL THROUGH
1811 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1812 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1813 InsertNewInstBefore(Not, I);
1814 return BinaryOperator::createAnd(Not, Op1);
1815 }
1816 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001817 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001818 // FALL THROUGH
1819 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1820 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1821 InsertNewInstBefore(Not, I);
1822 return BinaryOperator::createOr(Not, Op1);
1823 }
1824 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001825 }
1826
Chris Lattner2dd01742004-06-09 04:24:29 +00001827 // See if we are doing a comparison between a constant and an instruction that
1828 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001829 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001830 // Check to see if we are comparing against the minimum or maximum value...
1831 if (CI->isMinValue()) {
1832 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1833 return ReplaceInstUsesWith(I, ConstantBool::False);
1834 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1835 return ReplaceInstUsesWith(I, ConstantBool::True);
1836 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1837 return BinaryOperator::createSetEQ(Op0, Op1);
1838 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1839 return BinaryOperator::createSetNE(Op0, Op1);
1840
1841 } else if (CI->isMaxValue()) {
1842 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1843 return ReplaceInstUsesWith(I, ConstantBool::False);
1844 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1845 return ReplaceInstUsesWith(I, ConstantBool::True);
1846 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1847 return BinaryOperator::createSetEQ(Op0, Op1);
1848 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1849 return BinaryOperator::createSetNE(Op0, Op1);
1850
1851 // Comparing against a value really close to min or max?
1852 } else if (isMinValuePlusOne(CI)) {
1853 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1854 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1855 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1856 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1857
1858 } else if (isMaxValueMinusOne(CI)) {
1859 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1860 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1861 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1862 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1863 }
1864
1865 // If we still have a setle or setge instruction, turn it into the
1866 // appropriate setlt or setgt instruction. Since the border cases have
1867 // already been handled above, this requires little checking.
1868 //
1869 if (I.getOpcode() == Instruction::SetLE)
1870 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1871 if (I.getOpcode() == Instruction::SetGE)
1872 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1873
Chris Lattnere1e10e12004-05-25 06:32:08 +00001874 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001875 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001876 case Instruction::PHI:
1877 if (Instruction *NV = FoldOpIntoPhi(I))
1878 return NV;
1879 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001880 case Instruction::And:
1881 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1882 LHSI->getOperand(0)->hasOneUse()) {
1883 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1884 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1885 // happens a LOT in code produced by the C front-end, for bitfield
1886 // access.
1887 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1888 ConstantUInt *ShAmt;
1889 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1890 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1891 const Type *Ty = LHSI->getType();
1892
1893 // We can fold this as long as we can't shift unknown bits
1894 // into the mask. This can only happen with signed shift
1895 // rights, as they sign-extend.
1896 if (ShAmt) {
1897 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001898 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001899 if (!CanFold) {
1900 // To test for the bad case of the signed shr, see if any
1901 // of the bits shifted in could be tested after the mask.
1902 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001903 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001904 Constant *ShVal =
1905 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1906 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1907 CanFold = true;
1908 }
1909
1910 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00001911 Constant *NewCst;
1912 if (Shift->getOpcode() == Instruction::Shl)
1913 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1914 else
1915 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001916
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001917 // Check to see if we are shifting out any of the bits being
1918 // compared.
1919 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1920 // If we shifted bits out, the fold is not going to work out.
1921 // As a special case, check to see if this means that the
1922 // result is always true or false now.
1923 if (I.getOpcode() == Instruction::SetEQ)
1924 return ReplaceInstUsesWith(I, ConstantBool::False);
1925 if (I.getOpcode() == Instruction::SetNE)
1926 return ReplaceInstUsesWith(I, ConstantBool::True);
1927 } else {
1928 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00001929 Constant *NewAndCST;
1930 if (Shift->getOpcode() == Instruction::Shl)
1931 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
1932 else
1933 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1934 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001935 LHSI->setOperand(0, Shift->getOperand(0));
1936 WorkList.push_back(Shift); // Shift is dead.
1937 AddUsesToWorkList(I);
1938 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00001939 }
1940 }
Chris Lattner35167c32004-06-09 07:59:58 +00001941 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001942 }
1943 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00001944
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001945 case Instruction::Cast: { // (setcc (cast X to larger), CI)
1946 const Type *SrcTy = LHSI->getOperand(0)->getType();
1947 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
Chris Lattnerc9491282004-09-29 03:16:24 +00001948 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001949 if (SrcTy == Type::BoolTy) SrcBits = 1;
Chris Lattnerc9491282004-09-29 03:16:24 +00001950 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001951 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
1952 if (SrcBits < DestBits) {
1953 // Check to see if the comparison is always true or false.
1954 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
1955 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
1956 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
1957 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
1958 Min = ConstantExpr::getCast(Min, LHSI->getType());
1959 Max = ConstantExpr::getCast(Max, LHSI->getType());
1960 switch (I.getOpcode()) {
1961 default: assert(0 && "unknown integer comparison");
1962 case Instruction::SetEQ:
1963 return ReplaceInstUsesWith(I, ConstantBool::False);
1964 case Instruction::SetNE:
1965 return ReplaceInstUsesWith(I, ConstantBool::True);
1966 case Instruction::SetLT:
1967 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001968 case Instruction::SetGT:
1969 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00001970 }
1971 }
1972
1973 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
1974 ConstantExpr::getCast(CI, SrcTy));
1975 }
1976 }
1977 break;
1978 }
Chris Lattner272d5ca2004-09-28 18:22:15 +00001979 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
1980 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
1981 switch (I.getOpcode()) {
1982 default: break;
1983 case Instruction::SetEQ:
1984 case Instruction::SetNE: {
1985 // If we are comparing against bits always shifted out, the
1986 // comparison cannot succeed.
1987 Constant *Comp =
1988 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
1989 if (Comp != CI) {// Comparing against a bit that we know is zero.
1990 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
1991 Constant *Cst = ConstantBool::get(IsSetNE);
1992 return ReplaceInstUsesWith(I, Cst);
1993 }
1994
1995 if (LHSI->hasOneUse()) {
1996 // Otherwise strength reduce the shift into an and.
1997 unsigned ShAmtVal = ShAmt->getValue();
1998 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
1999 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2000
2001 Constant *Mask;
2002 if (CI->getType()->isUnsigned()) {
2003 Mask = ConstantUInt::get(CI->getType(), Val);
2004 } else if (ShAmtVal != 0) {
2005 Mask = ConstantSInt::get(CI->getType(), Val);
2006 } else {
2007 Mask = ConstantInt::getAllOnesValue(CI->getType());
2008 }
2009
2010 Instruction *AndI =
2011 BinaryOperator::createAnd(LHSI->getOperand(0),
2012 Mask, LHSI->getName()+".mask");
2013 Value *And = InsertNewInstBefore(AndI, I);
2014 return new SetCondInst(I.getOpcode(), And,
2015 ConstantExpr::getUShr(CI, ShAmt));
2016 }
2017 }
2018 }
2019 }
2020 break;
2021
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002022 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002023 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002024 switch (I.getOpcode()) {
2025 default: break;
2026 case Instruction::SetEQ:
2027 case Instruction::SetNE: {
2028 // If we are comparing against bits always shifted out, the
2029 // comparison cannot succeed.
2030 Constant *Comp =
2031 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2032
2033 if (Comp != CI) {// Comparing against a bit that we know is zero.
2034 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2035 Constant *Cst = ConstantBool::get(IsSetNE);
2036 return ReplaceInstUsesWith(I, Cst);
2037 }
2038
2039 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002040 unsigned ShAmtVal = ShAmt->getValue();
2041
Chris Lattner1023b872004-09-27 16:18:50 +00002042 // Otherwise strength reduce the shift into an and.
2043 uint64_t Val = ~0ULL; // All ones.
2044 Val <<= ShAmtVal; // Shift over to the right spot.
2045
2046 Constant *Mask;
2047 if (CI->getType()->isUnsigned()) {
2048 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2049 Val &= (1ULL << TypeBits)-1;
2050 Mask = ConstantUInt::get(CI->getType(), Val);
2051 } else {
2052 Mask = ConstantSInt::get(CI->getType(), Val);
2053 }
2054
2055 Instruction *AndI =
2056 BinaryOperator::createAnd(LHSI->getOperand(0),
2057 Mask, LHSI->getName()+".mask");
2058 Value *And = InsertNewInstBefore(AndI, I);
2059 return new SetCondInst(I.getOpcode(), And,
2060 ConstantExpr::getShl(CI, ShAmt));
2061 }
2062 break;
2063 }
2064 }
2065 }
2066 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002067
Chris Lattner6862fbd2004-09-29 17:40:11 +00002068 case Instruction::Div:
2069 // Fold: (div X, C1) op C2 -> range check
2070 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2071 // Fold this div into the comparison, producing a range check.
2072 // Determine, based on the divide type, what the range is being
2073 // checked. If there is an overflow on the low or high side, remember
2074 // it, otherwise compute the range [low, hi) bounding the new value.
2075 bool LoOverflow = false, HiOverflow = 0;
2076 ConstantInt *LoBound = 0, *HiBound = 0;
2077
2078 ConstantInt *Prod;
2079 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2080
2081 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2082 } else if (LHSI->getType()->isUnsigned()) { // udiv
2083 LoBound = Prod;
2084 LoOverflow = ProdOV;
2085 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2086 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2087 if (CI->isNullValue()) { // (X / pos) op 0
2088 // Can't overflow.
2089 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2090 HiBound = DivRHS;
2091 } else if (isPositive(CI)) { // (X / pos) op pos
2092 LoBound = Prod;
2093 LoOverflow = ProdOV;
2094 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2095 } else { // (X / pos) op neg
2096 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2097 LoOverflow = AddWithOverflow(LoBound, Prod,
2098 cast<ConstantInt>(DivRHSH));
2099 HiBound = Prod;
2100 HiOverflow = ProdOV;
2101 }
2102 } else { // Divisor is < 0.
2103 if (CI->isNullValue()) { // (X / neg) op 0
2104 LoBound = AddOne(DivRHS);
2105 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2106 } else if (isPositive(CI)) { // (X / neg) op pos
2107 HiOverflow = LoOverflow = ProdOV;
2108 if (!LoOverflow)
2109 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2110 HiBound = AddOne(Prod);
2111 } else { // (X / neg) op neg
2112 LoBound = Prod;
2113 LoOverflow = HiOverflow = ProdOV;
2114 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2115 }
2116 }
2117
2118 if (LoBound) {
2119 Value *X = LHSI->getOperand(0);
2120 std::cerr << "DIV FOLD: " << *LHSI;
2121 std::cerr << "DIV FOLD: " << I << "\n";
2122 switch (I.getOpcode()) {
2123 default: assert(0 && "Unhandled setcc opcode!");
2124 case Instruction::SetEQ:
2125 if (LoOverflow && HiOverflow)
2126 return ReplaceInstUsesWith(I, ConstantBool::False);
2127 else if (HiOverflow)
2128 return new SetCondInst(Instruction::SetGE, X, LoBound);
2129 else if (LoOverflow)
2130 return new SetCondInst(Instruction::SetLT, X, HiBound);
2131 else
2132 return InsertRangeTest(X, LoBound, HiBound, true, I);
2133 case Instruction::SetNE:
2134 if (LoOverflow && HiOverflow)
2135 return ReplaceInstUsesWith(I, ConstantBool::True);
2136 else if (HiOverflow)
2137 return new SetCondInst(Instruction::SetLT, X, LoBound);
2138 else if (LoOverflow)
2139 return new SetCondInst(Instruction::SetGE, X, HiBound);
2140 else
2141 return InsertRangeTest(X, LoBound, HiBound, false, I);
2142 case Instruction::SetLT:
2143 if (LoOverflow)
2144 return ReplaceInstUsesWith(I, ConstantBool::False);
2145 return new SetCondInst(Instruction::SetLT, X, LoBound);
2146 case Instruction::SetGT:
2147 if (HiOverflow)
2148 return ReplaceInstUsesWith(I, ConstantBool::False);
2149 return new SetCondInst(Instruction::SetGE, X, HiBound);
2150 }
2151 }
2152 }
2153 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002154 case Instruction::Select:
2155 // If either operand of the select is a constant, we can fold the
2156 // comparison into the select arms, which will cause one to be
2157 // constant folded and the select turned into a bitwise or.
2158 Value *Op1 = 0, *Op2 = 0;
2159 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002160 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002161 // Fold the known value into the constant operand.
2162 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2163 // Insert a new SetCC of the other select operand.
2164 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002165 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002166 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002167 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002168 // Fold the known value into the constant operand.
2169 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2170 // Insert a new SetCC of the other select operand.
2171 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002172 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002173 I.getName()), I);
2174 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002175 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002176
2177 if (Op1)
2178 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2179 break;
2180 }
2181
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002182 // Simplify seteq and setne instructions...
2183 if (I.getOpcode() == Instruction::SetEQ ||
2184 I.getOpcode() == Instruction::SetNE) {
2185 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2186
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002187 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002188 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002189 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2190 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002191 case Instruction::Rem:
2192 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2193 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2194 BO->hasOneUse() &&
2195 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2196 if (unsigned L2 =
2197 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2198 const Type *UTy = BO->getType()->getUnsignedVersion();
2199 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2200 UTy, "tmp"), I);
2201 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2202 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2203 RHSCst, BO->getName()), I);
2204 return BinaryOperator::create(I.getOpcode(), NewRem,
2205 Constant::getNullValue(UTy));
2206 }
2207 break;
2208
Chris Lattnerc992add2003-08-13 05:33:12 +00002209 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002210 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2211 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002212 if (BO->hasOneUse())
2213 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2214 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002215 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002216 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2217 // efficiently invertible, or if the add has just this one use.
2218 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002219
Chris Lattnerc992add2003-08-13 05:33:12 +00002220 if (Value *NegVal = dyn_castNegVal(BOp1))
2221 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2222 else if (Value *NegVal = dyn_castNegVal(BOp0))
2223 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002224 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002225 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2226 BO->setName("");
2227 InsertNewInstBefore(Neg, I);
2228 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2229 }
2230 }
2231 break;
2232 case Instruction::Xor:
2233 // For the xor case, we can xor two constants together, eliminating
2234 // the explicit xor.
2235 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2236 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002237 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002238
2239 // FALLTHROUGH
2240 case Instruction::Sub:
2241 // Replace (([sub|xor] A, B) != 0) with (A != B)
2242 if (CI->isNullValue())
2243 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2244 BO->getOperand(1));
2245 break;
2246
2247 case Instruction::Or:
2248 // If bits are being or'd in that are not present in the constant we
2249 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002250 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002251 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002252 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002253 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002254 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002255 break;
2256
2257 case Instruction::And:
2258 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002259 // If bits are being compared against that are and'd out, then the
2260 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002261 if (!ConstantExpr::getAnd(CI,
2262 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002263 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002264
Chris Lattner35167c32004-06-09 07:59:58 +00002265 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002266 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002267 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2268 Instruction::SetNE, Op0,
2269 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002270
Chris Lattnerc992add2003-08-13 05:33:12 +00002271 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2272 // to be a signed value as appropriate.
2273 if (isSignBit(BOC)) {
2274 Value *X = BO->getOperand(0);
2275 // If 'X' is not signed, insert a cast now...
2276 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002277 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002278 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002279 }
2280 return new SetCondInst(isSetNE ? Instruction::SetLT :
2281 Instruction::SetGE, X,
2282 Constant::getNullValue(X->getType()));
2283 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002284
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002285 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002286 if (CI->isNullValue() && isHighOnes(BOC)) {
2287 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002288 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002289
2290 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002291 if (NegX->getType()->isSigned()) {
2292 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2293 X = InsertCastBefore(X, DestTy, I);
2294 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002295 }
2296
2297 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002298 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002299 }
2300
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002301 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002302 default: break;
2303 }
2304 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002305 } else { // Not a SetEQ/SetNE
2306 // If the LHS is a cast from an integral value of the same size,
2307 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2308 Value *CastOp = Cast->getOperand(0);
2309 const Type *SrcTy = CastOp->getType();
2310 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2311 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2312 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2313 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2314 "Source and destination signednesses should differ!");
2315 if (Cast->getType()->isSigned()) {
2316 // If this is a signed comparison, check for comparisons in the
2317 // vicinity of zero.
2318 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2319 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002320 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002321 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2322 else if (I.getOpcode() == Instruction::SetGT &&
2323 cast<ConstantSInt>(CI)->getValue() == -1)
2324 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002325 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002326 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2327 } else {
2328 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2329 if (I.getOpcode() == Instruction::SetLT &&
2330 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2331 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002332 return BinaryOperator::createSetGT(CastOp,
2333 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002334 else if (I.getOpcode() == Instruction::SetGT &&
2335 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2336 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002337 return BinaryOperator::createSetLT(CastOp,
2338 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002339 }
2340 }
2341 }
Chris Lattnere967b342003-06-04 05:10:11 +00002342 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002343 }
2344
Chris Lattner16930792003-11-03 04:25:02 +00002345 // Test to see if the operands of the setcc are casted versions of other
2346 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002347 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2348 Value *CastOp0 = CI->getOperand(0);
2349 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002350 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002351 (I.getOpcode() == Instruction::SetEQ ||
2352 I.getOpcode() == Instruction::SetNE)) {
2353 // We keep moving the cast from the left operand over to the right
2354 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002355 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002356
2357 // If operand #1 is a cast instruction, see if we can eliminate it as
2358 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002359 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2360 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002361 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002362 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002363
2364 // If Op1 is a constant, we can fold the cast into the constant.
2365 if (Op1->getType() != Op0->getType())
2366 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2367 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2368 } else {
2369 // Otherwise, cast the RHS right before the setcc
2370 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2371 InsertNewInstBefore(cast<Instruction>(Op1), I);
2372 }
2373 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2374 }
2375
Chris Lattner6444c372003-11-03 05:17:03 +00002376 // Handle the special case of: setcc (cast bool to X), <cst>
2377 // This comes up when you have code like
2378 // int X = A < B;
2379 // if (X) ...
2380 // For generality, we handle any zero-extension of any operand comparison
2381 // with a constant.
2382 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2383 const Type *SrcTy = CastOp0->getType();
2384 const Type *DestTy = Op0->getType();
2385 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2386 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2387 // Ok, we have an expansion of operand 0 into a new type. Get the
2388 // constant value, masink off bits which are not set in the RHS. These
2389 // could be set if the destination value is signed.
2390 uint64_t ConstVal = ConstantRHS->getRawValue();
2391 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2392
2393 // If the constant we are comparing it with has high bits set, which
2394 // don't exist in the original value, the values could never be equal,
2395 // because the source would be zero extended.
2396 unsigned SrcBits =
2397 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002398 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2399 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002400 switch (I.getOpcode()) {
2401 default: assert(0 && "Unknown comparison type!");
2402 case Instruction::SetEQ:
2403 return ReplaceInstUsesWith(I, ConstantBool::False);
2404 case Instruction::SetNE:
2405 return ReplaceInstUsesWith(I, ConstantBool::True);
2406 case Instruction::SetLT:
2407 case Instruction::SetLE:
2408 if (DestTy->isSigned() && HasSignBit)
2409 return ReplaceInstUsesWith(I, ConstantBool::False);
2410 return ReplaceInstUsesWith(I, ConstantBool::True);
2411 case Instruction::SetGT:
2412 case Instruction::SetGE:
2413 if (DestTy->isSigned() && HasSignBit)
2414 return ReplaceInstUsesWith(I, ConstantBool::True);
2415 return ReplaceInstUsesWith(I, ConstantBool::False);
2416 }
2417 }
2418
2419 // Otherwise, we can replace the setcc with a setcc of the smaller
2420 // operand value.
2421 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2422 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2423 }
2424 }
2425 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002426 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002427}
2428
2429
2430
Chris Lattnere8d6c602003-03-10 19:16:08 +00002431Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002432 assert(I.getOperand(1)->getType() == Type::UByteTy);
2433 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002434 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002435
2436 // shl X, 0 == X and shr X, 0 == X
2437 // shl 0, X == 0 and shr 0, X == 0
2438 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002439 Op0 == Constant::getNullValue(Op0->getType()))
2440 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002441
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002442 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2443 if (!isLeftShift)
2444 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2445 if (CSI->isAllOnesValue())
2446 return ReplaceInstUsesWith(I, CSI);
2447
Chris Lattner183b3362004-04-09 19:05:30 +00002448 // Try to fold constant and into select arguments.
2449 if (isa<Constant>(Op0))
2450 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2451 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2452 return R;
2453
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002454 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002455 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2456 // of a signed value.
2457 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002458 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002459 if (CUI->getValue() >= TypeBits) {
2460 if (!Op0->getType()->isSigned() || isLeftShift)
2461 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2462 else {
2463 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2464 return &I;
2465 }
2466 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002467
Chris Lattnerede3fe02003-08-13 04:18:28 +00002468 // ((X*C1) << C2) == (X * (C1 << C2))
2469 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2470 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2471 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002472 return BinaryOperator::createMul(BO->getOperand(0),
2473 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002474
Chris Lattner183b3362004-04-09 19:05:30 +00002475 // Try to fold constant and into select arguments.
2476 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2477 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2478 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002479 if (isa<PHINode>(Op0))
2480 if (Instruction *NV = FoldOpIntoPhi(I))
2481 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002482
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002483 // If the operand is an bitwise operator with a constant RHS, and the
2484 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002485 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002486 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2487 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2488 bool isValid = true; // Valid only for And, Or, Xor
2489 bool highBitSet = false; // Transform if high bit of constant set?
2490
2491 switch (Op0BO->getOpcode()) {
2492 default: isValid = false; break; // Do not perform transform!
2493 case Instruction::Or:
2494 case Instruction::Xor:
2495 highBitSet = false;
2496 break;
2497 case Instruction::And:
2498 highBitSet = true;
2499 break;
2500 }
2501
2502 // If this is a signed shift right, and the high bit is modified
2503 // by the logical operation, do not perform the transformation.
2504 // The highBitSet boolean indicates the value of the high bit of
2505 // the constant which would cause it to be modified for this
2506 // operation.
2507 //
2508 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2509 uint64_t Val = Op0C->getRawValue();
2510 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2511 }
2512
2513 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002514 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002515
2516 Instruction *NewShift =
2517 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2518 Op0BO->getName());
2519 Op0BO->setName("");
2520 InsertNewInstBefore(NewShift, I);
2521
2522 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2523 NewRHS);
2524 }
2525 }
2526
Chris Lattner3204d4e2003-07-24 17:52:58 +00002527 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002528 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002529 if (ConstantUInt *ShiftAmt1C =
2530 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002531 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2532 unsigned ShiftAmt2 = CUI->getValue();
2533
2534 // Check for (A << c1) << c2 and (A >> c1) >> c2
2535 if (I.getOpcode() == Op0SI->getOpcode()) {
2536 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002537 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2538 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002539 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2540 ConstantUInt::get(Type::UByteTy, Amt));
2541 }
2542
Chris Lattnerab780df2003-07-24 18:38:56 +00002543 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2544 // signed types, we can only support the (A >> c1) << c2 configuration,
2545 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002546 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002547 // Calculate bitmask for what gets shifted off the edge...
2548 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002549 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002550 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002551 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002552 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002553
2554 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002555 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2556 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002557 InsertNewInstBefore(Mask, I);
2558
2559 // Figure out what flavor of shift we should use...
2560 if (ShiftAmt1 == ShiftAmt2)
2561 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2562 else if (ShiftAmt1 < ShiftAmt2) {
2563 return new ShiftInst(I.getOpcode(), Mask,
2564 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2565 } else {
2566 return new ShiftInst(Op0SI->getOpcode(), Mask,
2567 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2568 }
2569 }
2570 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002571 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002572
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002573 return 0;
2574}
2575
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002576enum CastType {
2577 Noop = 0,
2578 Truncate = 1,
2579 Signext = 2,
2580 Zeroext = 3
2581};
2582
2583/// getCastType - In the future, we will split the cast instruction into these
2584/// various types. Until then, we have to do the analysis here.
2585static CastType getCastType(const Type *Src, const Type *Dest) {
2586 assert(Src->isIntegral() && Dest->isIntegral() &&
2587 "Only works on integral types!");
2588 unsigned SrcSize = Src->getPrimitiveSize()*8;
2589 if (Src == Type::BoolTy) SrcSize = 1;
2590 unsigned DestSize = Dest->getPrimitiveSize()*8;
2591 if (Dest == Type::BoolTy) DestSize = 1;
2592
2593 if (SrcSize == DestSize) return Noop;
2594 if (SrcSize > DestSize) return Truncate;
2595 if (Src->isSigned()) return Signext;
2596 return Zeroext;
2597}
2598
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002599
Chris Lattner48a44f72002-05-02 17:06:02 +00002600// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2601// instruction.
2602//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002603static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002604 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002605
Chris Lattner650b6da2002-08-02 20:00:25 +00002606 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2607 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002608 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002609 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002610 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002611
Chris Lattner4fbad962004-07-21 04:27:24 +00002612 // If we are casting between pointer and integer types, treat pointers as
2613 // integers of the appropriate size for the code below.
2614 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2615 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2616 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002617
Chris Lattner48a44f72002-05-02 17:06:02 +00002618 // Allow free casting and conversion of sizes as long as the sign doesn't
2619 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002620 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002621 CastType FirstCast = getCastType(SrcTy, MidTy);
2622 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002623
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002624 // Capture the effect of these two casts. If the result is a legal cast,
2625 // the CastType is stored here, otherwise a special code is used.
2626 static const unsigned CastResult[] = {
2627 // First cast is noop
2628 0, 1, 2, 3,
2629 // First cast is a truncate
2630 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2631 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002632 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002633 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002634 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002635 };
2636
2637 unsigned Result = CastResult[FirstCast*4+SecondCast];
2638 switch (Result) {
2639 default: assert(0 && "Illegal table value!");
2640 case 0:
2641 case 1:
2642 case 2:
2643 case 3:
2644 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2645 // truncates, we could eliminate more casts.
2646 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2647 case 4:
2648 return false; // Not possible to eliminate this here.
2649 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002650 // Sign or zero extend followed by truncate is always ok if the result
2651 // is a truncate or noop.
2652 CastType ResultCast = getCastType(SrcTy, DstTy);
2653 if (ResultCast == Noop || ResultCast == Truncate)
2654 return true;
2655 // Otherwise we are still growing the value, we are only safe if the
2656 // result will match the sign/zeroextendness of the result.
2657 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002658 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002659 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002660 return false;
2661}
2662
Chris Lattner11ffd592004-07-20 05:21:00 +00002663static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002664 if (V->getType() == Ty || isa<Constant>(V)) return false;
2665 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002666 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2667 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002668 return false;
2669 return true;
2670}
2671
2672/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2673/// InsertBefore instruction. This is specialized a bit to avoid inserting
2674/// casts that are known to not do anything...
2675///
2676Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2677 Instruction *InsertBefore) {
2678 if (V->getType() == DestTy) return V;
2679 if (Constant *C = dyn_cast<Constant>(V))
2680 return ConstantExpr::getCast(C, DestTy);
2681
2682 CastInst *CI = new CastInst(V, DestTy, V->getName());
2683 InsertNewInstBefore(CI, *InsertBefore);
2684 return CI;
2685}
Chris Lattner48a44f72002-05-02 17:06:02 +00002686
2687// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002688//
Chris Lattner113f4f42002-06-25 16:13:24 +00002689Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002690 Value *Src = CI.getOperand(0);
2691
Chris Lattner48a44f72002-05-02 17:06:02 +00002692 // If the user is casting a value to the same type, eliminate this cast
2693 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002694 if (CI.getType() == Src->getType())
2695 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002696
Chris Lattner48a44f72002-05-02 17:06:02 +00002697 // If casting the result of another cast instruction, try to eliminate this
2698 // one!
2699 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002700 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002701 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002702 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002703 // This instruction now refers directly to the cast's src operand. This
2704 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002705 CI.setOperand(0, CSrc->getOperand(0));
2706 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002707 }
2708
Chris Lattner650b6da2002-08-02 20:00:25 +00002709 // If this is an A->B->A cast, and we are dealing with integral types, try
2710 // to convert this into a logical 'and' instruction.
2711 //
2712 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002713 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002714 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2715 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2716 assert(CSrc->getType() != Type::ULongTy &&
2717 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002718 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002719 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002720 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002721 }
2722 }
2723
Chris Lattner03841652004-05-25 04:29:21 +00002724 // If this is a cast to bool, turn it into the appropriate setne instruction.
2725 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002726 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002727 Constant::getNullValue(CI.getOperand(0)->getType()));
2728
Chris Lattnerd0d51602003-06-21 23:12:02 +00002729 // If casting the result of a getelementptr instruction with no offset, turn
2730 // this into a cast of the original pointer!
2731 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002732 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002733 bool AllZeroOperands = true;
2734 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2735 if (!isa<Constant>(GEP->getOperand(i)) ||
2736 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2737 AllZeroOperands = false;
2738 break;
2739 }
2740 if (AllZeroOperands) {
2741 CI.setOperand(0, GEP->getOperand(0));
2742 return &CI;
2743 }
2744 }
2745
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002746 // If we are casting a malloc or alloca to a pointer to a type of the same
2747 // size, rewrite the allocation instruction to allocate the "right" type.
2748 //
2749 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002750 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002751 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2752 // Get the type really allocated and the type casted to...
2753 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002754 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002755 if (AllocElTy->isSized() && CastElTy->isSized()) {
2756 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2757 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002758
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002759 // If the allocation is for an even multiple of the cast type size
2760 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2761 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002762 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002763 std::string Name = AI->getName(); AI->setName("");
2764 AllocationInst *New;
2765 if (isa<MallocInst>(AI))
2766 New = new MallocInst(CastElTy, Amt, Name);
2767 else
2768 New = new AllocaInst(CastElTy, Amt, Name);
2769 InsertNewInstBefore(New, *AI);
2770 return ReplaceInstUsesWith(CI, New);
2771 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002772 }
2773 }
2774
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002775 if (isa<PHINode>(Src))
2776 if (Instruction *NV = FoldOpIntoPhi(CI))
2777 return NV;
2778
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002779 // If the source value is an instruction with only this use, we can attempt to
2780 // propagate the cast into the instruction. Also, only handle integral types
2781 // for now.
2782 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002783 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002784 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2785 const Type *DestTy = CI.getType();
2786 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2787 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2788
2789 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2790 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2791
2792 switch (SrcI->getOpcode()) {
2793 case Instruction::Add:
2794 case Instruction::Mul:
2795 case Instruction::And:
2796 case Instruction::Or:
2797 case Instruction::Xor:
2798 // If we are discarding information, or just changing the sign, rewrite.
2799 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2800 // Don't insert two casts if they cannot be eliminated. We allow two
2801 // casts to be inserted if the sizes are the same. This could only be
2802 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002803 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2804 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002805 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2806 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2807 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2808 ->getOpcode(), Op0c, Op1c);
2809 }
2810 }
2811 break;
2812 case Instruction::Shl:
2813 // Allow changing the sign of the source operand. Do not allow changing
2814 // the size of the shift, UNLESS the shift amount is a constant. We
2815 // mush not change variable sized shifts to a smaller size, because it
2816 // is undefined to shift more bits out than exist in the value.
2817 if (DestBitSize == SrcBitSize ||
2818 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2819 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2820 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2821 }
2822 break;
2823 }
2824 }
2825
Chris Lattner260ab202002-04-18 17:39:14 +00002826 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002827}
2828
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002829/// GetSelectFoldableOperands - We want to turn code that looks like this:
2830/// %C = or %A, %B
2831/// %D = select %cond, %C, %A
2832/// into:
2833/// %C = select %cond, %B, 0
2834/// %D = or %A, %C
2835///
2836/// Assuming that the specified instruction is an operand to the select, return
2837/// a bitmask indicating which operands of this instruction are foldable if they
2838/// equal the other incoming value of the select.
2839///
2840static unsigned GetSelectFoldableOperands(Instruction *I) {
2841 switch (I->getOpcode()) {
2842 case Instruction::Add:
2843 case Instruction::Mul:
2844 case Instruction::And:
2845 case Instruction::Or:
2846 case Instruction::Xor:
2847 return 3; // Can fold through either operand.
2848 case Instruction::Sub: // Can only fold on the amount subtracted.
2849 case Instruction::Shl: // Can only fold on the shift amount.
2850 case Instruction::Shr:
2851 return 1;
2852 default:
2853 return 0; // Cannot fold
2854 }
2855}
2856
2857/// GetSelectFoldableConstant - For the same transformation as the previous
2858/// function, return the identity constant that goes into the select.
2859static Constant *GetSelectFoldableConstant(Instruction *I) {
2860 switch (I->getOpcode()) {
2861 default: assert(0 && "This cannot happen!"); abort();
2862 case Instruction::Add:
2863 case Instruction::Sub:
2864 case Instruction::Or:
2865 case Instruction::Xor:
2866 return Constant::getNullValue(I->getType());
2867 case Instruction::Shl:
2868 case Instruction::Shr:
2869 return Constant::getNullValue(Type::UByteTy);
2870 case Instruction::And:
2871 return ConstantInt::getAllOnesValue(I->getType());
2872 case Instruction::Mul:
2873 return ConstantInt::get(I->getType(), 1);
2874 }
2875}
2876
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002877Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002878 Value *CondVal = SI.getCondition();
2879 Value *TrueVal = SI.getTrueValue();
2880 Value *FalseVal = SI.getFalseValue();
2881
2882 // select true, X, Y -> X
2883 // select false, X, Y -> Y
2884 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002885 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002886 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002887 else {
2888 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002889 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002890 }
Chris Lattner533bc492004-03-30 19:37:13 +00002891
2892 // select C, X, X -> X
2893 if (TrueVal == FalseVal)
2894 return ReplaceInstUsesWith(SI, TrueVal);
2895
Chris Lattner1c631e82004-04-08 04:43:23 +00002896 if (SI.getType() == Type::BoolTy)
2897 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2898 if (C == ConstantBool::True) {
2899 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002900 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002901 } else {
2902 // Change: A = select B, false, C --> A = and !B, C
2903 Value *NotCond =
2904 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2905 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002906 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002907 }
2908 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2909 if (C == ConstantBool::False) {
2910 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002911 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002912 } else {
2913 // Change: A = select B, C, true --> A = or !B, C
2914 Value *NotCond =
2915 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2916 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002917 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002918 }
2919 }
2920
Chris Lattner183b3362004-04-09 19:05:30 +00002921 // Selecting between two integer constants?
2922 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2923 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2924 // select C, 1, 0 -> cast C to int
2925 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2926 return new CastInst(CondVal, SI.getType());
2927 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2928 // select C, 0, 1 -> cast !C to int
2929 Value *NotCond =
2930 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002931 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002932 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002933 }
Chris Lattner35167c32004-06-09 07:59:58 +00002934
2935 // If one of the constants is zero (we know they can't both be) and we
2936 // have a setcc instruction with zero, and we have an 'and' with the
2937 // non-constant value, eliminate this whole mess. This corresponds to
2938 // cases like this: ((X & 27) ? 27 : 0)
2939 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2940 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2941 if ((IC->getOpcode() == Instruction::SetEQ ||
2942 IC->getOpcode() == Instruction::SetNE) &&
2943 isa<ConstantInt>(IC->getOperand(1)) &&
2944 cast<Constant>(IC->getOperand(1))->isNullValue())
2945 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2946 if (ICA->getOpcode() == Instruction::And &&
2947 isa<ConstantInt>(ICA->getOperand(1)) &&
2948 (ICA->getOperand(1) == TrueValC ||
2949 ICA->getOperand(1) == FalseValC) &&
2950 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2951 // Okay, now we know that everything is set up, we just don't
2952 // know whether we have a setne or seteq and whether the true or
2953 // false val is the zero.
2954 bool ShouldNotVal = !TrueValC->isNullValue();
2955 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2956 Value *V = ICA;
2957 if (ShouldNotVal)
2958 V = InsertNewInstBefore(BinaryOperator::create(
2959 Instruction::Xor, V, ICA->getOperand(1)), SI);
2960 return ReplaceInstUsesWith(SI, V);
2961 }
Chris Lattner533bc492004-03-30 19:37:13 +00002962 }
Chris Lattner623fba12004-04-10 22:21:27 +00002963
2964 // See if we are selecting two values based on a comparison of the two values.
2965 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2966 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2967 // Transform (X == Y) ? X : Y -> Y
2968 if (SCI->getOpcode() == Instruction::SetEQ)
2969 return ReplaceInstUsesWith(SI, FalseVal);
2970 // Transform (X != Y) ? X : Y -> X
2971 if (SCI->getOpcode() == Instruction::SetNE)
2972 return ReplaceInstUsesWith(SI, TrueVal);
2973 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2974
2975 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2976 // Transform (X == Y) ? Y : X -> X
2977 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00002978 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002979 // Transform (X != Y) ? Y : X -> Y
2980 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00002981 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002982 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2983 }
2984 }
Chris Lattner1c631e82004-04-08 04:43:23 +00002985
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002986 // See if we can fold the select into one of our operands.
2987 if (SI.getType()->isInteger()) {
2988 // See the comment above GetSelectFoldableOperands for a description of the
2989 // transformation we are doing here.
2990 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2991 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2992 !isa<Constant>(FalseVal))
2993 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2994 unsigned OpToFold = 0;
2995 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2996 OpToFold = 1;
2997 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2998 OpToFold = 2;
2999 }
3000
3001 if (OpToFold) {
3002 Constant *C = GetSelectFoldableConstant(TVI);
3003 std::string Name = TVI->getName(); TVI->setName("");
3004 Instruction *NewSel =
3005 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3006 Name);
3007 InsertNewInstBefore(NewSel, SI);
3008 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3009 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3010 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3011 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3012 else {
3013 assert(0 && "Unknown instruction!!");
3014 }
3015 }
3016 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003017
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003018 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3019 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3020 !isa<Constant>(TrueVal))
3021 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3022 unsigned OpToFold = 0;
3023 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3024 OpToFold = 1;
3025 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3026 OpToFold = 2;
3027 }
3028
3029 if (OpToFold) {
3030 Constant *C = GetSelectFoldableConstant(FVI);
3031 std::string Name = FVI->getName(); FVI->setName("");
3032 Instruction *NewSel =
3033 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3034 Name);
3035 InsertNewInstBefore(NewSel, SI);
3036 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3037 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3038 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3039 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3040 else {
3041 assert(0 && "Unknown instruction!!");
3042 }
3043 }
3044 }
3045 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003046 return 0;
3047}
3048
3049
Chris Lattner970c33a2003-06-19 17:00:31 +00003050// CallInst simplification
3051//
3052Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003053 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3054 // visitCallSite.
3055 if (Function *F = CI.getCalledFunction())
3056 switch (F->getIntrinsicID()) {
3057 case Intrinsic::memmove:
3058 case Intrinsic::memcpy:
3059 case Intrinsic::memset:
3060 // memmove/cpy/set of zero bytes is a noop.
3061 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
3062 if (NumBytes->isNullValue())
3063 return EraseInstFromFunction(CI);
3064 }
3065 break;
3066 default:
3067 break;
3068 }
3069
Chris Lattneraec3d942003-10-07 22:32:43 +00003070 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003071}
3072
3073// InvokeInst simplification
3074//
3075Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003076 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003077}
3078
Chris Lattneraec3d942003-10-07 22:32:43 +00003079// visitCallSite - Improvements for call and invoke instructions.
3080//
3081Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003082 bool Changed = false;
3083
3084 // If the callee is a constexpr cast of a function, attempt to move the cast
3085 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003086 if (transformConstExprCastCall(CS)) return 0;
3087
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003088 Value *Callee = CS.getCalledValue();
3089 const PointerType *PTy = cast<PointerType>(Callee->getType());
3090 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3091 if (FTy->isVarArg()) {
3092 // See if we can optimize any arguments passed through the varargs area of
3093 // the call.
3094 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3095 E = CS.arg_end(); I != E; ++I)
3096 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3097 // If this cast does not effect the value passed through the varargs
3098 // area, we can eliminate the use of the cast.
3099 Value *Op = CI->getOperand(0);
3100 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3101 *I = Op;
3102 Changed = true;
3103 }
3104 }
3105 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003106
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003107 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003108}
3109
Chris Lattner970c33a2003-06-19 17:00:31 +00003110// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3111// attempt to move the cast to the arguments of the call/invoke.
3112//
3113bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3114 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3115 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003116 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003117 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003118 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003119 Instruction *Caller = CS.getInstruction();
3120
3121 // Okay, this is a cast from a function to a different type. Unless doing so
3122 // would cause a type conversion of one of our arguments, change this call to
3123 // be a direct call with arguments casted to the appropriate types.
3124 //
3125 const FunctionType *FT = Callee->getFunctionType();
3126 const Type *OldRetTy = Caller->getType();
3127
Chris Lattner1f7942f2004-01-14 06:06:08 +00003128 // Check to see if we are changing the return type...
3129 if (OldRetTy != FT->getReturnType()) {
3130 if (Callee->isExternal() &&
3131 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3132 !Caller->use_empty())
3133 return false; // Cannot transform this return value...
3134
3135 // If the callsite is an invoke instruction, and the return value is used by
3136 // a PHI node in a successor, we cannot change the return type of the call
3137 // because there is no place to put the cast instruction (without breaking
3138 // the critical edge). Bail out in this case.
3139 if (!Caller->use_empty())
3140 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3141 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3142 UI != E; ++UI)
3143 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3144 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003145 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003146 return false;
3147 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003148
3149 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3150 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3151
3152 CallSite::arg_iterator AI = CS.arg_begin();
3153 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3154 const Type *ParamTy = FT->getParamType(i);
3155 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3156 if (Callee->isExternal() && !isConvertible) return false;
3157 }
3158
3159 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3160 Callee->isExternal())
3161 return false; // Do not delete arguments unless we have a function body...
3162
3163 // Okay, we decided that this is a safe thing to do: go ahead and start
3164 // inserting cast instructions as necessary...
3165 std::vector<Value*> Args;
3166 Args.reserve(NumActualArgs);
3167
3168 AI = CS.arg_begin();
3169 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3170 const Type *ParamTy = FT->getParamType(i);
3171 if ((*AI)->getType() == ParamTy) {
3172 Args.push_back(*AI);
3173 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003174 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3175 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003176 }
3177 }
3178
3179 // If the function takes more arguments than the call was taking, add them
3180 // now...
3181 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3182 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3183
3184 // If we are removing arguments to the function, emit an obnoxious warning...
3185 if (FT->getNumParams() < NumActualArgs)
3186 if (!FT->isVarArg()) {
3187 std::cerr << "WARNING: While resolving call to function '"
3188 << Callee->getName() << "' arguments were dropped!\n";
3189 } else {
3190 // Add all of the arguments in their promoted form to the arg list...
3191 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3192 const Type *PTy = getPromotedType((*AI)->getType());
3193 if (PTy != (*AI)->getType()) {
3194 // Must promote to pass through va_arg area!
3195 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3196 InsertNewInstBefore(Cast, *Caller);
3197 Args.push_back(Cast);
3198 } else {
3199 Args.push_back(*AI);
3200 }
3201 }
3202 }
3203
3204 if (FT->getReturnType() == Type::VoidTy)
3205 Caller->setName(""); // Void type should not have a name...
3206
3207 Instruction *NC;
3208 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003209 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003210 Args, Caller->getName(), Caller);
3211 } else {
3212 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3213 }
3214
3215 // Insert a cast of the return type as necessary...
3216 Value *NV = NC;
3217 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3218 if (NV->getType() != Type::VoidTy) {
3219 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003220
3221 // If this is an invoke instruction, we should insert it after the first
3222 // non-phi, instruction in the normal successor block.
3223 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3224 BasicBlock::iterator I = II->getNormalDest()->begin();
3225 while (isa<PHINode>(I)) ++I;
3226 InsertNewInstBefore(NC, *I);
3227 } else {
3228 // Otherwise, it's a call, just insert cast right after the call instr
3229 InsertNewInstBefore(NC, *Caller);
3230 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003231 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003232 } else {
3233 NV = Constant::getNullValue(Caller->getType());
3234 }
3235 }
3236
3237 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3238 Caller->replaceAllUsesWith(NV);
3239 Caller->getParent()->getInstList().erase(Caller);
3240 removeFromWorkList(Caller);
3241 return true;
3242}
3243
3244
Chris Lattner48a44f72002-05-02 17:06:02 +00003245
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003246// PHINode simplification
3247//
Chris Lattner113f4f42002-06-25 16:13:24 +00003248Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00003249 if (Value *V = hasConstantValue(&PN))
3250 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00003251
3252 // If the only user of this instruction is a cast instruction, and all of the
3253 // incoming values are constants, change this PHI to merge together the casted
3254 // constants.
3255 if (PN.hasOneUse())
3256 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3257 if (CI->getType() != PN.getType()) { // noop casts will be folded
3258 bool AllConstant = true;
3259 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3260 if (!isa<Constant>(PN.getIncomingValue(i))) {
3261 AllConstant = false;
3262 break;
3263 }
3264 if (AllConstant) {
3265 // Make a new PHI with all casted values.
3266 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3267 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3268 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3269 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3270 PN.getIncomingBlock(i));
3271 }
3272
3273 // Update the cast instruction.
3274 CI->setOperand(0, New);
3275 WorkList.push_back(CI); // revisit the cast instruction to fold.
3276 WorkList.push_back(New); // Make sure to revisit the new Phi
3277 return &PN; // PN is now dead!
3278 }
3279 }
Chris Lattner91daeb52003-12-19 05:58:40 +00003280 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003281}
3282
Chris Lattner69193f92004-04-05 01:30:19 +00003283static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3284 Instruction *InsertPoint,
3285 InstCombiner *IC) {
3286 unsigned PS = IC->getTargetData().getPointerSize();
3287 const Type *VTy = V->getType();
3288 Instruction *Cast;
3289 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3290 // We must insert a cast to ensure we sign-extend.
3291 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3292 V->getName()), *InsertPoint);
3293 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3294 *InsertPoint);
3295}
3296
Chris Lattner48a44f72002-05-02 17:06:02 +00003297
Chris Lattner113f4f42002-06-25 16:13:24 +00003298Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003299 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003300 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003301 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003302 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003303 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003304
3305 bool HasZeroPointerIndex = false;
3306 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3307 HasZeroPointerIndex = C->isNullValue();
3308
3309 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003310 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003311
Chris Lattner69193f92004-04-05 01:30:19 +00003312 // Eliminate unneeded casts for indices.
3313 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003314 gep_type_iterator GTI = gep_type_begin(GEP);
3315 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3316 if (isa<SequentialType>(*GTI)) {
3317 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3318 Value *Src = CI->getOperand(0);
3319 const Type *SrcTy = Src->getType();
3320 const Type *DestTy = CI->getType();
3321 if (Src->getType()->isInteger()) {
3322 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3323 // We can always eliminate a cast from ulong or long to the other.
3324 // We can always eliminate a cast from uint to int or the other on
3325 // 32-bit pointer platforms.
3326 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3327 MadeChange = true;
3328 GEP.setOperand(i, Src);
3329 }
3330 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3331 SrcTy->getPrimitiveSize() == 4) {
3332 // We can always eliminate a cast from int to [u]long. We can
3333 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3334 // pointer target.
3335 if (SrcTy->isSigned() ||
3336 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3337 MadeChange = true;
3338 GEP.setOperand(i, Src);
3339 }
Chris Lattner69193f92004-04-05 01:30:19 +00003340 }
3341 }
3342 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003343 // If we are using a wider index than needed for this platform, shrink it
3344 // to what we need. If the incoming value needs a cast instruction,
3345 // insert it. This explicit cast can make subsequent optimizations more
3346 // obvious.
3347 Value *Op = GEP.getOperand(i);
3348 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003349 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003350 GEP.setOperand(i, ConstantExpr::getCast(C,
3351 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003352 MadeChange = true;
3353 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003354 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3355 Op->getName()), GEP);
3356 GEP.setOperand(i, Op);
3357 MadeChange = true;
3358 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003359
3360 // If this is a constant idx, make sure to canonicalize it to be a signed
3361 // operand, otherwise CSE and other optimizations are pessimized.
3362 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3363 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3364 CUI->getType()->getSignedVersion()));
3365 MadeChange = true;
3366 }
Chris Lattner69193f92004-04-05 01:30:19 +00003367 }
3368 if (MadeChange) return &GEP;
3369
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003370 // Combine Indices - If the source pointer to this getelementptr instruction
3371 // is a getelementptr instruction, combine the indices of the two
3372 // getelementptr instructions into a single instruction.
3373 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003374 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003375 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003376 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003377 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003378 if (CE->getOpcode() == Instruction::GetElementPtr)
3379 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3380 }
3381
3382 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003383 // Note that if our source is a gep chain itself that we wait for that
3384 // chain to be resolved before we perform this transformation. This
3385 // avoids us creating a TON of code in some cases.
3386 //
3387 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3388 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3389 return 0; // Wait until our source is folded to completion.
3390
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003391 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003392
3393 // Find out whether the last index in the source GEP is a sequential idx.
3394 bool EndsWithSequential = false;
3395 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3396 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003397 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003398
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003399 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003400 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003401 // Replace: gep (gep %P, long B), long A, ...
3402 // With: T = long A+B; gep %P, T, ...
3403 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003404 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003405 if (SO1 == Constant::getNullValue(SO1->getType())) {
3406 Sum = GO1;
3407 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3408 Sum = SO1;
3409 } else {
3410 // If they aren't the same type, convert both to an integer of the
3411 // target's pointer size.
3412 if (SO1->getType() != GO1->getType()) {
3413 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3414 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3415 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3416 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3417 } else {
3418 unsigned PS = TD->getPointerSize();
3419 Instruction *Cast;
3420 if (SO1->getType()->getPrimitiveSize() == PS) {
3421 // Convert GO1 to SO1's type.
3422 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3423
3424 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3425 // Convert SO1 to GO1's type.
3426 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3427 } else {
3428 const Type *PT = TD->getIntPtrType();
3429 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3430 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3431 }
3432 }
3433 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003434 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3435 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3436 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003437 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3438 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003439 }
Chris Lattner69193f92004-04-05 01:30:19 +00003440 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003441
3442 // Recycle the GEP we already have if possible.
3443 if (SrcGEPOperands.size() == 2) {
3444 GEP.setOperand(0, SrcGEPOperands[0]);
3445 GEP.setOperand(1, Sum);
3446 return &GEP;
3447 } else {
3448 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3449 SrcGEPOperands.end()-1);
3450 Indices.push_back(Sum);
3451 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3452 }
Chris Lattner69193f92004-04-05 01:30:19 +00003453 } else if (isa<Constant>(*GEP.idx_begin()) &&
3454 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003455 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003456 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003457 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3458 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003459 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3460 }
3461
3462 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003463 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003464
Chris Lattner5f667a62004-05-07 22:09:22 +00003465 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003466 // GEP of global variable. If all of the indices for this GEP are
3467 // constants, we can promote this to a constexpr instead of an instruction.
3468
3469 // Scan for nonconstants...
3470 std::vector<Constant*> Indices;
3471 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3472 for (; I != E && isa<Constant>(*I); ++I)
3473 Indices.push_back(cast<Constant>(*I));
3474
3475 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003476 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003477
3478 // Replace all uses of the GEP with the new constexpr...
3479 return ReplaceInstUsesWith(GEP, CE);
3480 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003481 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003482 if (CE->getOpcode() == Instruction::Cast) {
3483 if (HasZeroPointerIndex) {
3484 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3485 // into : GEP [10 x ubyte]* X, long 0, ...
3486 //
3487 // This occurs when the program declares an array extern like "int X[];"
3488 //
3489 Constant *X = CE->getOperand(0);
3490 const PointerType *CPTy = cast<PointerType>(CE->getType());
3491 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3492 if (const ArrayType *XATy =
3493 dyn_cast<ArrayType>(XTy->getElementType()))
3494 if (const ArrayType *CATy =
3495 dyn_cast<ArrayType>(CPTy->getElementType()))
3496 if (CATy->getElementType() == XATy->getElementType()) {
3497 // At this point, we know that the cast source type is a pointer
3498 // to an array of the same type as the destination pointer
3499 // array. Because the array type is never stepped over (there
3500 // is a leading zero) we can fold the cast into this GEP.
3501 GEP.setOperand(0, X);
3502 return &GEP;
3503 }
3504 }
3505 }
Chris Lattnerca081252001-12-14 16:52:21 +00003506 }
3507
Chris Lattnerca081252001-12-14 16:52:21 +00003508 return 0;
3509}
3510
Chris Lattner1085bdf2002-11-04 16:18:53 +00003511Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3512 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3513 if (AI.isArrayAllocation()) // Check C != 1
3514 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3515 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003516 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003517
3518 // Create and insert the replacement instruction...
3519 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003520 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003521 else {
3522 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003523 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003524 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003525
3526 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003527
3528 // Scan to the end of the allocation instructions, to skip over a block of
3529 // allocas if possible...
3530 //
3531 BasicBlock::iterator It = New;
3532 while (isa<AllocationInst>(*It)) ++It;
3533
3534 // Now that I is pointing to the first non-allocation-inst in the block,
3535 // insert our getelementptr instruction...
3536 //
Chris Lattner69193f92004-04-05 01:30:19 +00003537 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003538 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3539
3540 // Now make everything use the getelementptr instead of the original
3541 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003542 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003543 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003544
3545 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3546 // Note that we only do this for alloca's, because malloc should allocate and
3547 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003548 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3549 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003550 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3551
Chris Lattner1085bdf2002-11-04 16:18:53 +00003552 return 0;
3553}
3554
Chris Lattner8427bff2003-12-07 01:24:23 +00003555Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3556 Value *Op = FI.getOperand(0);
3557
3558 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3559 if (CastInst *CI = dyn_cast<CastInst>(Op))
3560 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3561 FI.setOperand(0, CI->getOperand(0));
3562 return &FI;
3563 }
3564
Chris Lattnerf3a36602004-02-28 04:57:37 +00003565 // If we have 'free null' delete the instruction. This can happen in stl code
3566 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00003567 if (isa<ConstantPointerNull>(Op))
3568 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003569
Chris Lattner8427bff2003-12-07 01:24:23 +00003570 return 0;
3571}
3572
3573
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003574/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3575/// constantexpr, return the constant value being addressed by the constant
3576/// expression, or null if something is funny.
3577///
3578static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003579 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003580 return 0; // Do not allow stepping over the value!
3581
3582 // Loop over all of the operands, tracking down which value we are
3583 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003584 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3585 for (++I; I != E; ++I)
3586 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3587 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3588 assert(CU->getValue() < STy->getNumElements() &&
3589 "Struct index out of range!");
3590 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003591 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003592 } else if (isa<ConstantAggregateZero>(C)) {
3593 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3594 } else {
3595 return 0;
3596 }
3597 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3598 const ArrayType *ATy = cast<ArrayType>(*I);
3599 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3600 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003601 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003602 else if (isa<ConstantAggregateZero>(C))
3603 C = Constant::getNullValue(ATy->getElementType());
3604 else
3605 return 0;
3606 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003607 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003608 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003609 return C;
3610}
3611
Chris Lattner35e24772004-07-13 01:49:43 +00003612static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3613 User *CI = cast<User>(LI.getOperand(0));
3614
3615 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3616 if (const PointerType *SrcTy =
3617 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3618 const Type *SrcPTy = SrcTy->getElementType();
3619 if (SrcPTy->isSized() && DestPTy->isSized() &&
3620 IC.getTargetData().getTypeSize(SrcPTy) ==
3621 IC.getTargetData().getTypeSize(DestPTy) &&
3622 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3623 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3624 // Okay, we are casting from one integer or pointer type to another of
3625 // the same size. Instead of casting the pointer before the load, cast
3626 // the result of the loaded value.
3627 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003628 CI->getName(),
3629 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003630 // Now cast the result of the load.
3631 return new CastInst(NewLoad, LI.getType());
3632 }
3633 }
3634 return 0;
3635}
3636
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003637/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003638/// from this value cannot trap. If it is not obviously safe to load from the
3639/// specified pointer, we do a quick local scan of the basic block containing
3640/// ScanFrom, to determine if the address is already accessed.
3641static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3642 // If it is an alloca or global variable, it is always safe to load from.
3643 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3644
3645 // Otherwise, be a little bit agressive by scanning the local block where we
3646 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003647 // from/to. If so, the previous load or store would have already trapped,
3648 // so there is no harm doing an extra load (also, CSE will later eliminate
3649 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003650 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3651
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003652 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003653 --BBI;
3654
3655 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3656 if (LI->getOperand(0) == V) return true;
3657 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3658 if (SI->getOperand(1) == V) return true;
3659
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003660 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003661 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003662}
3663
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003664Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3665 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003666
Chris Lattner6679e462004-04-14 03:28:36 +00003667 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003668 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattner6679e462004-04-14 03:28:36 +00003669 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003670
3671 // Instcombine load (constant global) into the value loaded...
3672 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00003673 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003674 return ReplaceInstUsesWith(LI, GV->getInitializer());
3675
3676 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3677 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattner35e24772004-07-13 01:49:43 +00003678 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer87436872004-07-18 00:38:32 +00003679 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3680 if (GV->isConstant() && !GV->isExternal())
3681 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3682 return ReplaceInstUsesWith(LI, V);
Chris Lattner35e24772004-07-13 01:49:43 +00003683 } else if (CE->getOpcode() == Instruction::Cast) {
3684 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3685 return Res;
3686 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003687
3688 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003689 if (CastInst *CI = dyn_cast<CastInst>(Op))
3690 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3691 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003692
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003693 if (!LI.isVolatile() && Op->hasOneUse()) {
3694 // Change select and PHI nodes to select values instead of addresses: this
3695 // helps alias analysis out a lot, allows many others simplifications, and
3696 // exposes redundancy in the code.
3697 //
3698 // Note that we cannot do the transformation unless we know that the
3699 // introduced loads cannot trap! Something like this is valid as long as
3700 // the condition is always false: load (select bool %C, int* null, int* %G),
3701 // but it would not be valid if we transformed it to load from null
3702 // unconditionally.
3703 //
3704 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3705 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003706 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3707 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003708 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003709 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003710 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003711 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003712 return new SelectInst(SI->getCondition(), V1, V2);
3713 }
3714
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003715 // load (select (cond, null, P)) -> load P
3716 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3717 if (C->isNullValue()) {
3718 LI.setOperand(0, SI->getOperand(2));
3719 return &LI;
3720 }
3721
3722 // load (select (cond, P, null)) -> load P
3723 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3724 if (C->isNullValue()) {
3725 LI.setOperand(0, SI->getOperand(1));
3726 return &LI;
3727 }
3728
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003729 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3730 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003731 bool Safe = PN->getParent() == LI.getParent();
3732
3733 // Scan all of the instructions between the PHI and the load to make
3734 // sure there are no instructions that might possibly alter the value
3735 // loaded from the PHI.
3736 if (Safe) {
3737 BasicBlock::iterator I = &LI;
3738 for (--I; !isa<PHINode>(I); --I)
3739 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3740 Safe = false;
3741 break;
3742 }
3743 }
3744
3745 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003746 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003747 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003748 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003749
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003750 if (Safe) {
3751 // Create the PHI.
3752 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3753 InsertNewInstBefore(NewPN, *PN);
3754 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3755
3756 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3757 BasicBlock *BB = PN->getIncomingBlock(i);
3758 Value *&TheLoad = LoadMap[BB];
3759 if (TheLoad == 0) {
3760 Value *InVal = PN->getIncomingValue(i);
3761 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3762 InVal->getName()+".val"),
3763 *BB->getTerminator());
3764 }
3765 NewPN->addIncoming(TheLoad, BB);
3766 }
3767 return ReplaceInstUsesWith(LI, NewPN);
3768 }
3769 }
3770 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003771 return 0;
3772}
3773
3774
Chris Lattner9eef8a72003-06-04 04:46:00 +00003775Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3776 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003777 Value *X;
3778 BasicBlock *TrueDest;
3779 BasicBlock *FalseDest;
3780 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3781 !isa<Constant>(X)) {
3782 // Swap Destinations and condition...
3783 BI.setCondition(X);
3784 BI.setSuccessor(0, FalseDest);
3785 BI.setSuccessor(1, TrueDest);
3786 return &BI;
3787 }
3788
3789 // Cannonicalize setne -> seteq
3790 Instruction::BinaryOps Op; Value *Y;
3791 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3792 TrueDest, FalseDest)))
3793 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3794 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3795 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3796 std::string Name = I->getName(); I->setName("");
3797 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3798 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003799 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003800 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003801 BI.setSuccessor(0, FalseDest);
3802 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003803 removeFromWorkList(I);
3804 I->getParent()->getInstList().erase(I);
3805 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003806 return &BI;
3807 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003808
Chris Lattner9eef8a72003-06-04 04:46:00 +00003809 return 0;
3810}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003811
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003812Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3813 Value *Cond = SI.getCondition();
3814 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3815 if (I->getOpcode() == Instruction::Add)
3816 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3817 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3818 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3819 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3820 AddRHS));
3821 SI.setOperand(0, I->getOperand(0));
3822 WorkList.push_back(I);
3823 return &SI;
3824 }
3825 }
3826 return 0;
3827}
3828
Chris Lattnerca081252001-12-14 16:52:21 +00003829
Chris Lattner99f48c62002-09-02 04:59:56 +00003830void InstCombiner::removeFromWorkList(Instruction *I) {
3831 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3832 WorkList.end());
3833}
3834
Chris Lattner113f4f42002-06-25 16:13:24 +00003835bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003836 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003837 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003838
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003839 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3840 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003841
Chris Lattnerca081252001-12-14 16:52:21 +00003842
3843 while (!WorkList.empty()) {
3844 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3845 WorkList.pop_back();
3846
Misha Brukman632df282002-10-29 23:06:16 +00003847 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003848 // Check to see if we can DIE the instruction...
3849 if (isInstructionTriviallyDead(I)) {
3850 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003851 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003852 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003853 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003854
3855 I->getParent()->getInstList().erase(I);
3856 removeFromWorkList(I);
3857 continue;
3858 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003859
Misha Brukman632df282002-10-29 23:06:16 +00003860 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003861 if (Constant *C = ConstantFoldInstruction(I)) {
3862 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003863 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003864 ReplaceInstUsesWith(*I, C);
3865
Chris Lattner99f48c62002-09-02 04:59:56 +00003866 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003867 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003868 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003869 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003870 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003871
Chris Lattnerca081252001-12-14 16:52:21 +00003872 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003873 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003874 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003875 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003876 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003877 DEBUG(std::cerr << "IC: Old = " << *I
3878 << " New = " << *Result);
3879
Chris Lattner396dbfe2004-06-09 05:08:07 +00003880 // Everything uses the new instruction now.
3881 I->replaceAllUsesWith(Result);
3882
3883 // Push the new instruction and any users onto the worklist.
3884 WorkList.push_back(Result);
3885 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003886
3887 // Move the name to the new instruction first...
3888 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003889 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003890
3891 // Insert the new instruction into the basic block...
3892 BasicBlock *InstParent = I->getParent();
3893 InstParent->getInstList().insert(I, Result);
3894
Chris Lattner63d75af2004-05-01 23:27:23 +00003895 // Make sure that we reprocess all operands now that we reduced their
3896 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003897 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3898 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3899 WorkList.push_back(OpI);
3900
Chris Lattner396dbfe2004-06-09 05:08:07 +00003901 // Instructions can end up on the worklist more than once. Make sure
3902 // we do not process an instruction that has been deleted.
3903 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003904
3905 // Erase the old instruction.
3906 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003907 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003908 DEBUG(std::cerr << "IC: MOD = " << *I);
3909
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003910 // If the instruction was modified, it's possible that it is now dead.
3911 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003912 if (isInstructionTriviallyDead(I)) {
3913 // Make sure we process all operands now that we are reducing their
3914 // use counts.
3915 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3916 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3917 WorkList.push_back(OpI);
3918
3919 // Instructions may end up in the worklist more than once. Erase all
3920 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003921 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003922 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003923 } else {
3924 WorkList.push_back(Result);
3925 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003926 }
Chris Lattner053c0932002-05-14 15:24:07 +00003927 }
Chris Lattner260ab202002-04-18 17:39:14 +00003928 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003929 }
3930 }
3931
Chris Lattner260ab202002-04-18 17:39:14 +00003932 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003933}
3934
Brian Gaeke38b79e82004-07-27 17:43:21 +00003935FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003936 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003937}
Brian Gaeke960707c2003-11-11 22:41:34 +00003938