blob: 9eb30549f47b58dbbc842bd19783e02cac478fc8 [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
46#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000047#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000049#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000050#include "llvm/Support/Debug.h"
51#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000052#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000053using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000054using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000055
Chris Lattner260ab202002-04-18 17:39:14 +000056namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000057 Statistic<> NumCombined ("instcombine", "Number of insts combined");
58 Statistic<> NumConstProp("instcombine", "Number of constant folds");
59 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
60
Chris Lattnerc8e66542002-04-27 06:56:12 +000061 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000062 public InstVisitor<InstCombiner, Instruction*> {
63 // Worklist of all of the instructions that need to be simplified.
64 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000065 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000066
Chris Lattner51ea1272004-02-28 05:22:00 +000067 /// AddUsersToWorkList - When an instruction is simplified, add all users of
68 /// the instruction to the work lists because they might get more simplified
69 /// now.
70 ///
71 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000072 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000073 UI != UE; ++UI)
74 WorkList.push_back(cast<Instruction>(*UI));
75 }
76
Chris Lattner51ea1272004-02-28 05:22:00 +000077 /// AddUsesToWorkList - When an instruction is simplified, add operands to
78 /// the work lists because they might get more simplified now.
79 ///
80 void AddUsesToWorkList(Instruction &I) {
81 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83 WorkList.push_back(Op);
84 }
85
Chris Lattner99f48c62002-09-02 04:59:56 +000086 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000088 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000089 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000090
Chris Lattnerf12cc842002-04-28 21:27:06 +000091 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000092 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000093 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000094 }
95
Chris Lattner69193f92004-04-05 01:30:19 +000096 TargetData &getTargetData() const { return *TD; }
97
Chris Lattner260ab202002-04-18 17:39:14 +000098 // Visitation implementation - Implement instruction combining for different
99 // instruction types. The semantics are as follows:
100 // Return Value:
101 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000102 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000103 // otherwise - Change was made, replace I with returned instruction
104 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000105 Instruction *visitAdd(BinaryOperator &I);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitMul(BinaryOperator &I);
108 Instruction *visitDiv(BinaryOperator &I);
109 Instruction *visitRem(BinaryOperator &I);
110 Instruction *visitAnd(BinaryOperator &I);
111 Instruction *visitOr (BinaryOperator &I);
112 Instruction *visitXor(BinaryOperator &I);
113 Instruction *visitSetCondInst(BinaryOperator &I);
Reid Spencer279fa252004-11-28 21:31:15 +0000114 Instruction *visitSetCondInstWithCastAndConstant(BinaryOperator&I,
115 CastInst*LHSI,
116 ConstantInt* CI);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000117 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000118 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000119 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000120 Instruction *visitCallInst(CallInst &CI);
121 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000122 Instruction *visitPHINode(PHINode &PN);
123 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000124 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000125 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000126 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000127 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000128 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000129
130 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000131 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000132
Chris Lattner970c33a2003-06-19 17:00:31 +0000133 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000134 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000135 bool transformConstExprCastCall(CallSite CS);
136
Chris Lattner69193f92004-04-05 01:30:19 +0000137 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000138 // InsertNewInstBefore - insert an instruction New before instruction Old
139 // in the program. Add the new instruction to the worklist.
140 //
Chris Lattner623826c2004-09-28 21:48:02 +0000141 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000142 assert(New && New->getParent() == 0 &&
143 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000144 BasicBlock *BB = Old.getParent();
145 BB->getInstList().insert(&Old, New); // Insert inst
146 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000147 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000148 }
149
Chris Lattner7e794272004-09-24 15:21:34 +0000150 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
151 /// This also adds the cast to the worklist. Finally, this returns the
152 /// cast.
153 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
154 if (V->getType() == Ty) return V;
155
156 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
157 WorkList.push_back(C);
158 return C;
159 }
160
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000161 // ReplaceInstUsesWith - This method is to be used when an instruction is
162 // found to be dead, replacable with another preexisting expression. Here
163 // we add all uses of I to the worklist, replace all uses of I with the new
164 // value, then return I, so that the inst combiner will know that I was
165 // modified.
166 //
167 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000168 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000169 if (&I != V) {
170 I.replaceAllUsesWith(V);
171 return &I;
172 } else {
173 // If we are replacing the instruction with itself, this must be in a
174 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000175 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000176 return &I;
177 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000178 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000179
180 // EraseInstFromFunction - When dealing with an instruction that has side
181 // effects or produces a void value, we can't rely on DCE to delete the
182 // instruction. Instead, visit methods should return the value returned by
183 // this function.
184 Instruction *EraseInstFromFunction(Instruction &I) {
185 assert(I.use_empty() && "Cannot erase instruction that is used!");
186 AddUsesToWorkList(I);
187 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000188 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000189 return 0; // Don't do anything with FI
190 }
191
192
Chris Lattner3ac7c262003-08-13 20:16:26 +0000193 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000194 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
195 /// InsertBefore instruction. This is specialized a bit to avoid inserting
196 /// casts that are known to not do anything...
197 ///
198 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
199 Instruction *InsertBefore);
200
Chris Lattner7fb29e12003-03-11 00:12:48 +0000201 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000202 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000203 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000204
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000205
206 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
207 // PHI node as operand #0, see if we can fold the instruction into the PHI
208 // (which is only possible if all operands to the PHI are constants).
209 Instruction *FoldOpIntoPhi(Instruction &I);
210
Chris Lattner7515cab2004-11-14 19:13:23 +0000211 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
212 // operator and they all are only used by the PHI, PHI together their
213 // inputs, and do the operation once, to the result of the PHI.
214 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
215
Chris Lattnerba1cb382003-09-19 17:17:26 +0000216 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
217 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000218
219 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
220 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000221 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000222
Chris Lattnerc8b70922002-07-26 21:12:46 +0000223 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000224}
225
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000226// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000227// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000228static unsigned getComplexity(Value *V) {
229 if (isa<Instruction>(V)) {
230 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000231 return 3;
232 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000233 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000234 if (isa<Argument>(V)) return 3;
235 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000236}
Chris Lattner260ab202002-04-18 17:39:14 +0000237
Chris Lattner7fb29e12003-03-11 00:12:48 +0000238// isOnlyUse - Return true if this instruction will be deleted if we stop using
239// it.
240static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000241 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000242}
243
Chris Lattnere79e8542004-02-23 06:38:22 +0000244// getPromotedType - Return the specified type promoted as it would be to pass
245// though a va_arg area...
246static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000247 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000248 case Type::SByteTyID:
249 case Type::ShortTyID: return Type::IntTy;
250 case Type::UByteTyID:
251 case Type::UShortTyID: return Type::UIntTy;
252 case Type::FloatTyID: return Type::DoubleTy;
253 default: return Ty;
254 }
255}
256
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000257// SimplifyCommutative - This performs a few simplifications for commutative
258// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000259//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000260// 1. Order operands such that they are listed from right (least complex) to
261// left (most complex). This puts constants before unary operators before
262// binary operators.
263//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000264// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
265// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000266//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000267bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000268 bool Changed = false;
269 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
270 Changed = !I.swapOperands();
271
272 if (!I.isAssociative()) return Changed;
273 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000274 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
275 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
276 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000277 Constant *Folded = ConstantExpr::get(I.getOpcode(),
278 cast<Constant>(I.getOperand(1)),
279 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000280 I.setOperand(0, Op->getOperand(0));
281 I.setOperand(1, Folded);
282 return true;
283 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
284 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
285 isOnlyUse(Op) && isOnlyUse(Op1)) {
286 Constant *C1 = cast<Constant>(Op->getOperand(1));
287 Constant *C2 = cast<Constant>(Op1->getOperand(1));
288
289 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000290 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000291 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
292 Op1->getOperand(0),
293 Op1->getName(), &I);
294 WorkList.push_back(New);
295 I.setOperand(0, New);
296 I.setOperand(1, Folded);
297 return true;
298 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000299 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000300 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000301}
Chris Lattnerca081252001-12-14 16:52:21 +0000302
Chris Lattnerbb74e222003-03-10 23:06:50 +0000303// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
304// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000305//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000306static inline Value *dyn_castNegVal(Value *V) {
307 if (BinaryOperator::isNeg(V))
308 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
309
Chris Lattner9244df62003-04-30 22:19:10 +0000310 // Constants can be considered to be negated values if they can be folded...
311 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner8f30caf2004-12-08 22:20:34 +0000312 if (!isa<UndefValue>(C))
313 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000314 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000315}
316
Chris Lattnerbb74e222003-03-10 23:06:50 +0000317static inline Value *dyn_castNotVal(Value *V) {
318 if (BinaryOperator::isNot(V))
319 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
320
321 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000322 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000323 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000324 return 0;
325}
326
Chris Lattner7fb29e12003-03-11 00:12:48 +0000327// dyn_castFoldableMul - If this value is a multiply that can be folded into
328// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000329// non-constant operand of the multiply, and set CST to point to the multiplier.
330// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000331//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000332static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000333 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000334 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000335 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000336 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000337 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000338 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000339 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000340 // The multiplier is really 1 << CST.
341 Constant *One = ConstantInt::get(V->getType(), 1);
342 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
343 return I->getOperand(0);
344 }
345 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000346 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000347}
Chris Lattner31ae8632002-08-14 17:51:49 +0000348
Chris Lattner3082c5a2003-02-18 19:28:33 +0000349// Log2 - Calculate the log base 2 for the specified value if it is exactly a
350// power of 2.
351static unsigned Log2(uint64_t Val) {
352 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
353 unsigned Count = 0;
354 while (Val != 1) {
355 if (Val & 1) return 0; // Multiple bits set?
356 Val >>= 1;
357 ++Count;
358 }
359 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000360}
361
Chris Lattner623826c2004-09-28 21:48:02 +0000362// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000363static ConstantInt *AddOne(ConstantInt *C) {
364 return cast<ConstantInt>(ConstantExpr::getAdd(C,
365 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000366}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000367static ConstantInt *SubOne(ConstantInt *C) {
368 return cast<ConstantInt>(ConstantExpr::getSub(C,
369 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000370}
371
372// isTrueWhenEqual - Return true if the specified setcondinst instruction is
373// true when both operands are equal...
374//
375static bool isTrueWhenEqual(Instruction &I) {
376 return I.getOpcode() == Instruction::SetEQ ||
377 I.getOpcode() == Instruction::SetGE ||
378 I.getOpcode() == Instruction::SetLE;
379}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000380
381/// AssociativeOpt - Perform an optimization on an associative operator. This
382/// function is designed to check a chain of associative operators for a
383/// potential to apply a certain optimization. Since the optimization may be
384/// applicable if the expression was reassociated, this checks the chain, then
385/// reassociates the expression as necessary to expose the optimization
386/// opportunity. This makes use of a special Functor, which must define
387/// 'shouldApply' and 'apply' methods.
388///
389template<typename Functor>
390Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
391 unsigned Opcode = Root.getOpcode();
392 Value *LHS = Root.getOperand(0);
393
394 // Quick check, see if the immediate LHS matches...
395 if (F.shouldApply(LHS))
396 return F.apply(Root);
397
398 // Otherwise, if the LHS is not of the same opcode as the root, return.
399 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000400 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000401 // Should we apply this transform to the RHS?
402 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
403
404 // If not to the RHS, check to see if we should apply to the LHS...
405 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
406 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
407 ShouldApply = true;
408 }
409
410 // If the functor wants to apply the optimization to the RHS of LHSI,
411 // reassociate the expression from ((? op A) op B) to (? op (A op B))
412 if (ShouldApply) {
413 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000414
415 // Now all of the instructions are in the current basic block, go ahead
416 // and perform the reassociation.
417 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
418
419 // First move the selected RHS to the LHS of the root...
420 Root.setOperand(0, LHSI->getOperand(1));
421
422 // Make what used to be the LHS of the root be the user of the root...
423 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000424 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000425 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
426 return 0;
427 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000428 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000429 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000430 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
431 BasicBlock::iterator ARI = &Root; ++ARI;
432 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
433 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000434
435 // Now propagate the ExtraOperand down the chain of instructions until we
436 // get to LHSI.
437 while (TmpLHSI != LHSI) {
438 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000439 // Move the instruction to immediately before the chain we are
440 // constructing to avoid breaking dominance properties.
441 NextLHSI->getParent()->getInstList().remove(NextLHSI);
442 BB->getInstList().insert(ARI, NextLHSI);
443 ARI = NextLHSI;
444
Chris Lattnerb8b97502003-08-13 19:01:45 +0000445 Value *NextOp = NextLHSI->getOperand(1);
446 NextLHSI->setOperand(1, ExtraOperand);
447 TmpLHSI = NextLHSI;
448 ExtraOperand = NextOp;
449 }
450
451 // Now that the instructions are reassociated, have the functor perform
452 // the transformation...
453 return F.apply(Root);
454 }
455
456 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
457 }
458 return 0;
459}
460
461
462// AddRHS - Implements: X + X --> X << 1
463struct AddRHS {
464 Value *RHS;
465 AddRHS(Value *rhs) : RHS(rhs) {}
466 bool shouldApply(Value *LHS) const { return LHS == RHS; }
467 Instruction *apply(BinaryOperator &Add) const {
468 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
469 ConstantInt::get(Type::UByteTy, 1));
470 }
471};
472
473// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
474// iff C1&C2 == 0
475struct AddMaskingAnd {
476 Constant *C2;
477 AddMaskingAnd(Constant *c) : C2(c) {}
478 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000479 ConstantInt *C1;
480 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
481 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000482 }
483 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000484 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000485 }
486};
487
Chris Lattner183b3362004-04-09 19:05:30 +0000488static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
489 InstCombiner *IC) {
490 // Figure out if the constant is the left or the right argument.
491 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
492 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000493
Chris Lattner183b3362004-04-09 19:05:30 +0000494 if (Constant *SOC = dyn_cast<Constant>(SO)) {
495 if (ConstIsRHS)
496 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
497 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
498 }
499
500 Value *Op0 = SO, *Op1 = ConstOperand;
501 if (!ConstIsRHS)
502 std::swap(Op0, Op1);
503 Instruction *New;
504 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
505 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
506 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
507 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000508 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000509 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000510 abort();
511 }
Chris Lattner183b3362004-04-09 19:05:30 +0000512 return IC->InsertNewInstBefore(New, BI);
513}
514
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000515
516/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
517/// node as operand #0, see if we can fold the instruction into the PHI (which
518/// is only possible if all operands to the PHI are constants).
519Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
520 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000521 unsigned NumPHIValues = PN->getNumIncomingValues();
522 if (!PN->hasOneUse() || NumPHIValues == 0 ||
523 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000524
525 // Check to see if all of the operands of the PHI are constants. If not, we
526 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000527 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000528 if (!isa<Constant>(PN->getIncomingValue(i)))
529 return 0;
530
531 // Okay, we can do the transformation: create the new PHI node.
532 PHINode *NewPN = new PHINode(I.getType(), I.getName());
533 I.setName("");
534 NewPN->op_reserve(PN->getNumOperands());
535 InsertNewInstBefore(NewPN, *PN);
536
537 // Next, add all of the operands to the PHI.
538 if (I.getNumOperands() == 2) {
539 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000540 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000541 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
542 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
543 PN->getIncomingBlock(i));
544 }
545 } else {
546 assert(isa<CastInst>(I) && "Unary op should be a cast!");
547 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000548 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000549 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
550 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
551 PN->getIncomingBlock(i));
552 }
553 }
554 return ReplaceInstUsesWith(I, NewPN);
555}
556
Chris Lattner183b3362004-04-09 19:05:30 +0000557// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
558// constant as the other operand, try to fold the binary operator into the
559// select arguments.
560static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
561 InstCombiner *IC) {
562 // Don't modify shared select instructions
563 if (!SI->hasOneUse()) return 0;
564 Value *TV = SI->getOperand(1);
565 Value *FV = SI->getOperand(2);
566
567 if (isa<Constant>(TV) || isa<Constant>(FV)) {
568 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
569 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
570
571 return new SelectInst(SI->getCondition(), SelectTrueVal,
572 SelectFalseVal);
573 }
574 return 0;
575}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000576
Chris Lattner113f4f42002-06-25 16:13:24 +0000577Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000578 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000579 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000580
Chris Lattnercf4a9962004-04-10 22:01:55 +0000581 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000582 // X + undef -> undef
583 if (isa<UndefValue>(RHS))
584 return ReplaceInstUsesWith(I, RHS);
585
Chris Lattnercf4a9962004-04-10 22:01:55 +0000586 // X + 0 --> X
587 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
588 RHSC->isNullValue())
589 return ReplaceInstUsesWith(I, LHS);
590
591 // X + (signbit) --> X ^ signbit
592 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
593 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
594 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000595 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000596 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000597 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000598
599 if (isa<PHINode>(LHS))
600 if (Instruction *NV = FoldOpIntoPhi(I))
601 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000602 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000603
Chris Lattnerb8b97502003-08-13 19:01:45 +0000604 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000605 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000606 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000607 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000608
Chris Lattner147e9752002-05-08 22:46:53 +0000609 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000610 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000611 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000612
613 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000614 if (!isa<Constant>(RHS))
615 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000616 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000617
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000618 ConstantInt *C2;
619 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
620 if (X == RHS) // X*C + X --> X * (C+1)
621 return BinaryOperator::createMul(RHS, AddOne(C2));
622
623 // X*C1 + X*C2 --> X * (C1+C2)
624 ConstantInt *C1;
625 if (X == dyn_castFoldableMul(RHS, C1))
626 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000627 }
628
629 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000630 if (dyn_castFoldableMul(RHS, C2) == LHS)
631 return BinaryOperator::createMul(LHS, AddOne(C2));
632
Chris Lattner57c8d992003-02-18 19:57:07 +0000633
Chris Lattnerb8b97502003-08-13 19:01:45 +0000634 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000635 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000636 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000637
Chris Lattnerb9cde762003-10-02 15:11:26 +0000638 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000639 Value *X;
640 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
641 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
642 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000643 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000644
Chris Lattnerbff91d92004-10-08 05:07:56 +0000645 // (X & FF00) + xx00 -> (X+xx00) & FF00
646 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
647 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
648 if (Anded == CRHS) {
649 // See if all bits from the first bit set in the Add RHS up are included
650 // in the mask. First, get the rightmost bit.
651 uint64_t AddRHSV = CRHS->getRawValue();
652
653 // Form a mask of all bits from the lowest bit added through the top.
654 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
655 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
656
657 // See if the and mask includes all of these bits.
658 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
659
660 if (AddRHSHighBits == AddRHSHighBitsAnd) {
661 // Okay, the xform is safe. Insert the new add pronto.
662 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
663 LHS->getName()), I);
664 return BinaryOperator::createAnd(NewAdd, C2);
665 }
666 }
667 }
668
669
Chris Lattnerd4252a72004-07-30 07:50:03 +0000670 // Try to fold constant add into select arguments.
671 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
672 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
673 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000674 }
675
Chris Lattner113f4f42002-06-25 16:13:24 +0000676 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000677}
678
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000679// isSignBit - Return true if the value represented by the constant only has the
680// highest order bit set.
681static bool isSignBit(ConstantInt *CI) {
682 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
683 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
684}
685
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000686static unsigned getTypeSizeInBits(const Type *Ty) {
687 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
688}
689
Chris Lattner022167f2004-03-13 00:11:49 +0000690/// RemoveNoopCast - Strip off nonconverting casts from the value.
691///
692static Value *RemoveNoopCast(Value *V) {
693 if (CastInst *CI = dyn_cast<CastInst>(V)) {
694 const Type *CTy = CI->getType();
695 const Type *OpTy = CI->getOperand(0)->getType();
696 if (CTy->isInteger() && OpTy->isInteger()) {
697 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
698 return RemoveNoopCast(CI->getOperand(0));
699 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
700 return RemoveNoopCast(CI->getOperand(0));
701 }
702 return V;
703}
704
Chris Lattner113f4f42002-06-25 16:13:24 +0000705Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000706 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000707
Chris Lattnere6794492002-08-12 21:17:25 +0000708 if (Op0 == Op1) // sub X, X -> 0
709 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000710
Chris Lattnere6794492002-08-12 21:17:25 +0000711 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000712 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000713 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000714
Chris Lattner81a7a232004-10-16 18:11:37 +0000715 if (isa<UndefValue>(Op0))
716 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
717 if (isa<UndefValue>(Op1))
718 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
719
Chris Lattner8f2f5982003-11-05 01:06:05 +0000720 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
721 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000722 if (C->isAllOnesValue())
723 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000724
Chris Lattner8f2f5982003-11-05 01:06:05 +0000725 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000726 Value *X;
727 if (match(Op1, m_Not(m_Value(X))))
728 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000729 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000730 // -((uint)X >> 31) -> ((int)X >> 31)
731 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000732 if (C->isNullValue()) {
733 Value *NoopCastedRHS = RemoveNoopCast(Op1);
734 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000735 if (SI->getOpcode() == Instruction::Shr)
736 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
737 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000738 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000739 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000740 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000741 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000742 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000743 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000744 // Ok, the transformation is safe. Insert a cast of the incoming
745 // value, then the new shift, then the new cast.
746 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
747 SI->getOperand(0)->getName());
748 Value *InV = InsertNewInstBefore(FirstCast, I);
749 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
750 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000751 if (NewShift->getType() == I.getType())
752 return NewShift;
753 else {
754 InV = InsertNewInstBefore(NewShift, I);
755 return new CastInst(NewShift, I.getType());
756 }
Chris Lattner92295c52004-03-12 23:53:13 +0000757 }
758 }
Chris Lattner022167f2004-03-13 00:11:49 +0000759 }
Chris Lattner183b3362004-04-09 19:05:30 +0000760
761 // Try to fold constant sub into select arguments.
762 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
763 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
764 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000765
766 if (isa<PHINode>(Op0))
767 if (Instruction *NV = FoldOpIntoPhi(I))
768 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000769 }
770
Chris Lattner3082c5a2003-02-18 19:28:33 +0000771 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000772 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000773 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
774 // is not used by anyone else...
775 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000776 if (Op1I->getOpcode() == Instruction::Sub &&
777 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000778 // Swap the two operands of the subexpr...
779 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
780 Op1I->setOperand(0, IIOp1);
781 Op1I->setOperand(1, IIOp0);
782
783 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000784 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000785 }
786
787 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
788 //
789 if (Op1I->getOpcode() == Instruction::And &&
790 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
791 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
792
Chris Lattner396dbfe2004-06-09 05:08:07 +0000793 Value *NewNot =
794 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000795 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000796 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000797
Chris Lattner0aee4b72004-10-06 15:08:25 +0000798 // -(X sdiv C) -> (X sdiv -C)
799 if (Op1I->getOpcode() == Instruction::Div)
800 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
801 if (CSI->getValue() == 0)
802 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
803 return BinaryOperator::createDiv(Op1I->getOperand(0),
804 ConstantExpr::getNeg(DivRHS));
805
Chris Lattner57c8d992003-02-18 19:57:07 +0000806 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000807 ConstantInt *C2;
808 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
809 Constant *CP1 =
810 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000811 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000812 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000813 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000814
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000815
816 ConstantInt *C1;
817 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
818 if (X == Op1) { // X*C - X --> X * (C-1)
819 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
820 return BinaryOperator::createMul(Op1, CP1);
821 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000822
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000823 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
824 if (X == dyn_castFoldableMul(Op1, C2))
825 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
826 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000827 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000828}
829
Chris Lattnere79e8542004-02-23 06:38:22 +0000830/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
831/// really just returns true if the most significant (sign) bit is set.
832static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
833 if (RHS->getType()->isSigned()) {
834 // True if source is LHS < 0 or LHS <= -1
835 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
836 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
837 } else {
838 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
839 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
840 // the size of the integer type.
841 if (Opcode == Instruction::SetGE)
842 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
843 if (Opcode == Instruction::SetGT)
844 return RHSC->getValue() ==
845 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
846 }
847 return false;
848}
849
Chris Lattner113f4f42002-06-25 16:13:24 +0000850Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000851 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000852 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000853
Chris Lattner81a7a232004-10-16 18:11:37 +0000854 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
855 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
856
Chris Lattnere6794492002-08-12 21:17:25 +0000857 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000858 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
859 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000860
861 // ((X << C1)*C2) == (X * (C2 << C1))
862 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
863 if (SI->getOpcode() == Instruction::Shl)
864 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000865 return BinaryOperator::createMul(SI->getOperand(0),
866 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000867
Chris Lattnercce81be2003-09-11 22:24:54 +0000868 if (CI->isNullValue())
869 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
870 if (CI->equalsInt(1)) // X * 1 == X
871 return ReplaceInstUsesWith(I, Op0);
872 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000873 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000874
Chris Lattnercce81be2003-09-11 22:24:54 +0000875 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000876 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
877 return new ShiftInst(Instruction::Shl, Op0,
878 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000879 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000880 if (Op1F->isNullValue())
881 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000882
Chris Lattner3082c5a2003-02-18 19:28:33 +0000883 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
884 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
885 if (Op1F->getValue() == 1.0)
886 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
887 }
Chris Lattner183b3362004-04-09 19:05:30 +0000888
889 // Try to fold constant mul into select arguments.
890 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
891 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
892 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000893
894 if (isa<PHINode>(Op0))
895 if (Instruction *NV = FoldOpIntoPhi(I))
896 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000897 }
898
Chris Lattner934a64cf2003-03-10 23:23:04 +0000899 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
900 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000901 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000902
Chris Lattner2635b522004-02-23 05:39:21 +0000903 // If one of the operands of the multiply is a cast from a boolean value, then
904 // we know the bool is either zero or one, so this is a 'masking' multiply.
905 // See if we can simplify things based on how the boolean was originally
906 // formed.
907 CastInst *BoolCast = 0;
908 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
909 if (CI->getOperand(0)->getType() == Type::BoolTy)
910 BoolCast = CI;
911 if (!BoolCast)
912 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
913 if (CI->getOperand(0)->getType() == Type::BoolTy)
914 BoolCast = CI;
915 if (BoolCast) {
916 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
917 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
918 const Type *SCOpTy = SCIOp0->getType();
919
Chris Lattnere79e8542004-02-23 06:38:22 +0000920 // If the setcc is true iff the sign bit of X is set, then convert this
921 // multiply into a shift/and combination.
922 if (isa<ConstantInt>(SCIOp1) &&
923 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000924 // Shift the X value right to turn it into "all signbits".
925 Constant *Amt = ConstantUInt::get(Type::UByteTy,
926 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000927 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000928 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000929 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
930 SCIOp0->getName()), I);
931 }
932
933 Value *V =
934 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
935 BoolCast->getOperand(0)->getName()+
936 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000937
938 // If the multiply type is not the same as the source type, sign extend
939 // or truncate to the multiply type.
940 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000941 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000942
943 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000944 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000945 }
946 }
947 }
948
Chris Lattner113f4f42002-06-25 16:13:24 +0000949 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000950}
951
Chris Lattner113f4f42002-06-25 16:13:24 +0000952Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000953 if (isa<UndefValue>(I.getOperand(0))) // undef / X -> 0
954 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
955 if (isa<UndefValue>(I.getOperand(1)))
956 return ReplaceInstUsesWith(I, I.getOperand(1)); // X / undef -> undef
957
Chris Lattner3082c5a2003-02-18 19:28:33 +0000958 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000959 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000960 if (RHS->equalsInt(1))
961 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000962
Chris Lattnere20c3342004-04-26 14:01:59 +0000963 // div X, -1 == -X
964 if (RHS->isAllOnesValue())
965 return BinaryOperator::createNeg(I.getOperand(0));
966
Chris Lattner272d5ca2004-09-28 18:22:15 +0000967 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
968 if (LHS->getOpcode() == Instruction::Div)
969 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000970 // (X / C1) / C2 -> X / (C1*C2)
971 return BinaryOperator::createDiv(LHS->getOperand(0),
972 ConstantExpr::getMul(RHS, LHSRHS));
973 }
974
Chris Lattner3082c5a2003-02-18 19:28:33 +0000975 // Check to see if this is an unsigned division with an exact power of 2,
976 // if so, convert to a right shift.
977 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
978 if (uint64_t Val = C->getValue()) // Don't break X / 0
979 if (uint64_t C = Log2(Val))
980 return new ShiftInst(Instruction::Shr, I.getOperand(0),
981 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000982
Chris Lattner4ad08352004-10-09 02:50:40 +0000983 // -X/C -> X/-C
984 if (RHS->getType()->isSigned())
985 if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
986 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
987
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000988 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
989 if (Instruction *NV = FoldOpIntoPhi(I))
990 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000991 }
992
993 // 0 / X == 0, we don't need to preserve faults!
994 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
995 if (LHS->equalsInt(0))
996 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
997
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000998 return 0;
999}
1000
1001
Chris Lattner113f4f42002-06-25 16:13:24 +00001002Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001003 if (I.getType()->isSigned())
1004 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001005 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001006 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001007 // X % -Y -> X % Y
1008 AddUsesToWorkList(I);
1009 I.setOperand(1, RHSNeg);
1010 return &I;
1011 }
1012
Chris Lattner81a7a232004-10-16 18:11:37 +00001013 if (isa<UndefValue>(I.getOperand(0))) // undef % X -> 0
1014 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1015 if (isa<UndefValue>(I.getOperand(1)))
1016 return ReplaceInstUsesWith(I, I.getOperand(1)); // X % undef -> undef
1017
Chris Lattner3082c5a2003-02-18 19:28:33 +00001018 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
1019 if (RHS->equalsInt(1)) // X % 1 == 0
1020 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1021
1022 // Check to see if this is an unsigned remainder with an exact power of 2,
1023 // if so, convert to a bitwise and.
1024 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1025 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001026 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001027 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +00001028 ConstantUInt::get(I.getType(), Val-1));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001029 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1030 if (Instruction *NV = FoldOpIntoPhi(I))
1031 return NV;
Chris Lattner3082c5a2003-02-18 19:28:33 +00001032 }
1033
1034 // 0 % X == 0, we don't need to preserve faults!
1035 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
1036 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001037 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1038
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001039 return 0;
1040}
1041
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001042// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001043static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001044 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1045 // Calculate -1 casted to the right type...
1046 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1047 uint64_t Val = ~0ULL; // All ones
1048 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1049 return CU->getValue() == Val-1;
1050 }
1051
1052 const ConstantSInt *CS = cast<ConstantSInt>(C);
1053
1054 // Calculate 0111111111..11111
1055 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1056 int64_t Val = INT64_MAX; // All ones
1057 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1058 return CS->getValue() == Val-1;
1059}
1060
1061// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001062static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001063 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1064 return CU->getValue() == 1;
1065
1066 const ConstantSInt *CS = cast<ConstantSInt>(C);
1067
1068 // Calculate 1111111111000000000000
1069 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1070 int64_t Val = -1; // All ones
1071 Val <<= TypeBits-1; // Shift over to the right spot
1072 return CS->getValue() == Val+1;
1073}
1074
Chris Lattner35167c32004-06-09 07:59:58 +00001075// isOneBitSet - Return true if there is exactly one bit set in the specified
1076// constant.
1077static bool isOneBitSet(const ConstantInt *CI) {
1078 uint64_t V = CI->getRawValue();
1079 return V && (V & (V-1)) == 0;
1080}
1081
Chris Lattner8fc5af42004-09-23 21:46:38 +00001082#if 0 // Currently unused
1083// isLowOnes - Return true if the constant is of the form 0+1+.
1084static bool isLowOnes(const ConstantInt *CI) {
1085 uint64_t V = CI->getRawValue();
1086
1087 // There won't be bits set in parts that the type doesn't contain.
1088 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1089
1090 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1091 return U && V && (U & V) == 0;
1092}
1093#endif
1094
1095// isHighOnes - Return true if the constant is of the form 1+0+.
1096// This is the same as lowones(~X).
1097static bool isHighOnes(const ConstantInt *CI) {
1098 uint64_t V = ~CI->getRawValue();
1099
1100 // There won't be bits set in parts that the type doesn't contain.
1101 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1102
1103 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1104 return U && V && (U & V) == 0;
1105}
1106
1107
Chris Lattner3ac7c262003-08-13 20:16:26 +00001108/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1109/// are carefully arranged to allow folding of expressions such as:
1110///
1111/// (A < B) | (A > B) --> (A != B)
1112///
1113/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1114/// represents that the comparison is true if A == B, and bit value '1' is true
1115/// if A < B.
1116///
1117static unsigned getSetCondCode(const SetCondInst *SCI) {
1118 switch (SCI->getOpcode()) {
1119 // False -> 0
1120 case Instruction::SetGT: return 1;
1121 case Instruction::SetEQ: return 2;
1122 case Instruction::SetGE: return 3;
1123 case Instruction::SetLT: return 4;
1124 case Instruction::SetNE: return 5;
1125 case Instruction::SetLE: return 6;
1126 // True -> 7
1127 default:
1128 assert(0 && "Invalid SetCC opcode!");
1129 return 0;
1130 }
1131}
1132
1133/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1134/// opcode and two operands into either a constant true or false, or a brand new
1135/// SetCC instruction.
1136static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1137 switch (Opcode) {
1138 case 0: return ConstantBool::False;
1139 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1140 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1141 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1142 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1143 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1144 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1145 case 7: return ConstantBool::True;
1146 default: assert(0 && "Illegal SetCCCode!"); return 0;
1147 }
1148}
1149
1150// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1151struct FoldSetCCLogical {
1152 InstCombiner &IC;
1153 Value *LHS, *RHS;
1154 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1155 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1156 bool shouldApply(Value *V) const {
1157 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1158 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1159 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1160 return false;
1161 }
1162 Instruction *apply(BinaryOperator &Log) const {
1163 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1164 if (SCI->getOperand(0) != LHS) {
1165 assert(SCI->getOperand(1) == LHS);
1166 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1167 }
1168
1169 unsigned LHSCode = getSetCondCode(SCI);
1170 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1171 unsigned Code;
1172 switch (Log.getOpcode()) {
1173 case Instruction::And: Code = LHSCode & RHSCode; break;
1174 case Instruction::Or: Code = LHSCode | RHSCode; break;
1175 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001176 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001177 }
1178
1179 Value *RV = getSetCCValue(Code, LHS, RHS);
1180 if (Instruction *I = dyn_cast<Instruction>(RV))
1181 return I;
1182 // Otherwise, it's a constant boolean value...
1183 return IC.ReplaceInstUsesWith(Log, RV);
1184 }
1185};
1186
1187
Chris Lattnerba1cb382003-09-19 17:17:26 +00001188// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1189// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1190// guaranteed to be either a shift instruction or a binary operator.
1191Instruction *InstCombiner::OptAndOp(Instruction *Op,
1192 ConstantIntegral *OpRHS,
1193 ConstantIntegral *AndRHS,
1194 BinaryOperator &TheAnd) {
1195 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001196 Constant *Together = 0;
1197 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001198 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001199
Chris Lattnerba1cb382003-09-19 17:17:26 +00001200 switch (Op->getOpcode()) {
1201 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001202 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001203 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001204 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001205 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001206 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1207 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001208 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001209 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001210 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001211 }
1212 break;
1213 case Instruction::Or:
1214 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001215 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001216 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001217 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001218 if (Together == AndRHS) // (X | C) & C --> C
1219 return ReplaceInstUsesWith(TheAnd, AndRHS);
1220
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001221 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001222 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1223 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001224 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001225 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001226 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001227 }
1228 }
1229 break;
1230 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001231 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001232 // Adding a one to a single bit bit-field should be turned into an XOR
1233 // of the bit. First thing to check is to see if this AND is with a
1234 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001235 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001236
1237 // Clear bits that are not part of the constant.
1238 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1239
1240 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001241 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001242 // Ok, at this point, we know that we are masking the result of the
1243 // ADD down to exactly one bit. If the constant we are adding has
1244 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001245 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001246
1247 // Check to see if any bits below the one bit set in AndRHSV are set.
1248 if ((AddRHS & (AndRHSV-1)) == 0) {
1249 // If not, the only thing that can effect the output of the AND is
1250 // the bit specified by AndRHSV. If that bit is set, the effect of
1251 // the XOR is to toggle the bit. If it is clear, then the ADD has
1252 // no effect.
1253 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1254 TheAnd.setOperand(0, X);
1255 return &TheAnd;
1256 } else {
1257 std::string Name = Op->getName(); Op->setName("");
1258 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001259 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001260 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001261 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001262 }
1263 }
1264 }
1265 }
1266 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001267
1268 case Instruction::Shl: {
1269 // We know that the AND will not produce any of the bits shifted in, so if
1270 // the anded constant includes them, clear them now!
1271 //
1272 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001273 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1274 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1275
1276 if (CI == ShlMask) { // Masking out bits that the shift already masks
1277 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1278 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001279 TheAnd.setOperand(1, CI);
1280 return &TheAnd;
1281 }
1282 break;
1283 }
1284 case Instruction::Shr:
1285 // We know that the AND will not produce any of the bits shifted in, so if
1286 // the anded constant includes them, clear them now! This only applies to
1287 // unsigned shifts, because a signed shr may bring in set bits!
1288 //
1289 if (AndRHS->getType()->isUnsigned()) {
1290 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001291 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1292 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1293
1294 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1295 return ReplaceInstUsesWith(TheAnd, Op);
1296 } else if (CI != AndRHS) {
1297 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001298 return &TheAnd;
1299 }
Chris Lattner7e794272004-09-24 15:21:34 +00001300 } else { // Signed shr.
1301 // See if this is shifting in some sign extension, then masking it out
1302 // with an and.
1303 if (Op->hasOneUse()) {
1304 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1305 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1306 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001307 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001308 // Make the argument unsigned.
1309 Value *ShVal = Op->getOperand(0);
1310 ShVal = InsertCastBefore(ShVal,
1311 ShVal->getType()->getUnsignedVersion(),
1312 TheAnd);
1313 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1314 OpRHS, Op->getName()),
1315 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001316 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1317 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1318 TheAnd.getName()),
1319 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001320 return new CastInst(ShVal, Op->getType());
1321 }
1322 }
Chris Lattner2da29172003-09-19 19:05:02 +00001323 }
1324 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001325 }
1326 return 0;
1327}
1328
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001329
Chris Lattner6862fbd2004-09-29 17:40:11 +00001330/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1331/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1332/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1333/// insert new instructions.
1334Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1335 bool Inside, Instruction &IB) {
1336 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1337 "Lo is not <= Hi in range emission code!");
1338 if (Inside) {
1339 if (Lo == Hi) // Trivially false.
1340 return new SetCondInst(Instruction::SetNE, V, V);
1341 if (cast<ConstantIntegral>(Lo)->isMinValue())
1342 return new SetCondInst(Instruction::SetLT, V, Hi);
1343
1344 Constant *AddCST = ConstantExpr::getNeg(Lo);
1345 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1346 InsertNewInstBefore(Add, IB);
1347 // Convert to unsigned for the comparison.
1348 const Type *UnsType = Add->getType()->getUnsignedVersion();
1349 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1350 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1351 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1352 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1353 }
1354
1355 if (Lo == Hi) // Trivially true.
1356 return new SetCondInst(Instruction::SetEQ, V, V);
1357
1358 Hi = SubOne(cast<ConstantInt>(Hi));
1359 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1360 return new SetCondInst(Instruction::SetGT, V, Hi);
1361
1362 // Emit X-Lo > Hi-Lo-1
1363 Constant *AddCST = ConstantExpr::getNeg(Lo);
1364 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1365 InsertNewInstBefore(Add, IB);
1366 // Convert to unsigned for the comparison.
1367 const Type *UnsType = Add->getType()->getUnsignedVersion();
1368 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1369 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1370 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1371 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1372}
1373
1374
Chris Lattner113f4f42002-06-25 16:13:24 +00001375Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001376 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001377 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001378
Chris Lattner81a7a232004-10-16 18:11:37 +00001379 if (isa<UndefValue>(Op1)) // X & undef -> 0
1380 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1381
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001382 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001383 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1384 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001385
1386 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001387 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001388 if (RHS->isAllOnesValue())
1389 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001390
Chris Lattnerba1cb382003-09-19 17:17:26 +00001391 // Optimize a variety of ((val OP C1) & C2) combinations...
1392 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1393 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001394 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001395 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001396 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1397 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001398 }
Chris Lattner183b3362004-04-09 19:05:30 +00001399
1400 // Try to fold constant and into select arguments.
1401 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1402 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1403 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001404 if (isa<PHINode>(Op0))
1405 if (Instruction *NV = FoldOpIntoPhi(I))
1406 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001407 }
1408
Chris Lattnerbb74e222003-03-10 23:06:50 +00001409 Value *Op0NotVal = dyn_castNotVal(Op0);
1410 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001411
Chris Lattner023a4832004-06-18 06:07:51 +00001412 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1413 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1414
Misha Brukman9c003d82004-07-30 12:50:08 +00001415 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001416 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001417 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1418 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001419 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001420 return BinaryOperator::createNot(Or);
1421 }
1422
Chris Lattner623826c2004-09-28 21:48:02 +00001423 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1424 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001425 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1426 return R;
1427
Chris Lattner623826c2004-09-28 21:48:02 +00001428 Value *LHSVal, *RHSVal;
1429 ConstantInt *LHSCst, *RHSCst;
1430 Instruction::BinaryOps LHSCC, RHSCC;
1431 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1432 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1433 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1434 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1435 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1436 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1437 // Ensure that the larger constant is on the RHS.
1438 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1439 SetCondInst *LHS = cast<SetCondInst>(Op0);
1440 if (cast<ConstantBool>(Cmp)->getValue()) {
1441 std::swap(LHS, RHS);
1442 std::swap(LHSCst, RHSCst);
1443 std::swap(LHSCC, RHSCC);
1444 }
1445
1446 // At this point, we know we have have two setcc instructions
1447 // comparing a value against two constants and and'ing the result
1448 // together. Because of the above check, we know that we only have
1449 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1450 // FoldSetCCLogical check above), that the two constants are not
1451 // equal.
1452 assert(LHSCst != RHSCst && "Compares not folded above?");
1453
1454 switch (LHSCC) {
1455 default: assert(0 && "Unknown integer condition code!");
1456 case Instruction::SetEQ:
1457 switch (RHSCC) {
1458 default: assert(0 && "Unknown integer condition code!");
1459 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1460 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1461 return ReplaceInstUsesWith(I, ConstantBool::False);
1462 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1463 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1464 return ReplaceInstUsesWith(I, LHS);
1465 }
1466 case Instruction::SetNE:
1467 switch (RHSCC) {
1468 default: assert(0 && "Unknown integer condition code!");
1469 case Instruction::SetLT:
1470 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1471 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1472 break; // (X != 13 & X < 15) -> no change
1473 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1474 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1475 return ReplaceInstUsesWith(I, RHS);
1476 case Instruction::SetNE:
1477 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1478 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1479 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1480 LHSVal->getName()+".off");
1481 InsertNewInstBefore(Add, I);
1482 const Type *UnsType = Add->getType()->getUnsignedVersion();
1483 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1484 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1485 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1486 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1487 }
1488 break; // (X != 13 & X != 15) -> no change
1489 }
1490 break;
1491 case Instruction::SetLT:
1492 switch (RHSCC) {
1493 default: assert(0 && "Unknown integer condition code!");
1494 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1495 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1496 return ReplaceInstUsesWith(I, ConstantBool::False);
1497 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1498 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1499 return ReplaceInstUsesWith(I, LHS);
1500 }
1501 case Instruction::SetGT:
1502 switch (RHSCC) {
1503 default: assert(0 && "Unknown integer condition code!");
1504 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1505 return ReplaceInstUsesWith(I, LHS);
1506 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1507 return ReplaceInstUsesWith(I, RHS);
1508 case Instruction::SetNE:
1509 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1510 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1511 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001512 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1513 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001514 }
1515 }
1516 }
1517 }
1518
Chris Lattner113f4f42002-06-25 16:13:24 +00001519 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001520}
1521
Chris Lattner113f4f42002-06-25 16:13:24 +00001522Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001523 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001524 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001525
Chris Lattner81a7a232004-10-16 18:11:37 +00001526 if (isa<UndefValue>(Op1))
1527 return ReplaceInstUsesWith(I, // X | undef -> -1
1528 ConstantIntegral::getAllOnesValue(I.getType()));
1529
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001530 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001531 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1532 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001533
1534 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001535 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001536 if (RHS->isAllOnesValue())
1537 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001538
Chris Lattnerd4252a72004-07-30 07:50:03 +00001539 ConstantInt *C1; Value *X;
1540 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1541 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1542 std::string Op0Name = Op0->getName(); Op0->setName("");
1543 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1544 InsertNewInstBefore(Or, I);
1545 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1546 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001547
Chris Lattnerd4252a72004-07-30 07:50:03 +00001548 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1549 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1550 std::string Op0Name = Op0->getName(); Op0->setName("");
1551 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1552 InsertNewInstBefore(Or, I);
1553 return BinaryOperator::createXor(Or,
1554 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001555 }
Chris Lattner183b3362004-04-09 19:05:30 +00001556
1557 // Try to fold constant and into select arguments.
1558 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1559 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1560 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001561 if (isa<PHINode>(Op0))
1562 if (Instruction *NV = FoldOpIntoPhi(I))
1563 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001564 }
1565
Chris Lattner812aab72003-08-12 19:11:07 +00001566 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001567 Value *A, *B; ConstantInt *C1, *C2;
1568 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1569 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1570 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001571
Chris Lattnerd4252a72004-07-30 07:50:03 +00001572 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1573 if (A == Op1) // ~A | A == -1
1574 return ReplaceInstUsesWith(I,
1575 ConstantIntegral::getAllOnesValue(I.getType()));
1576 } else {
1577 A = 0;
1578 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001579
Chris Lattnerd4252a72004-07-30 07:50:03 +00001580 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1581 if (Op0 == B)
1582 return ReplaceInstUsesWith(I,
1583 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001584
Misha Brukman9c003d82004-07-30 12:50:08 +00001585 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001586 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1587 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1588 I.getName()+".demorgan"), I);
1589 return BinaryOperator::createNot(And);
1590 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001591 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001592
Chris Lattner3ac7c262003-08-13 20:16:26 +00001593 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001594 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001595 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1596 return R;
1597
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001598 Value *LHSVal, *RHSVal;
1599 ConstantInt *LHSCst, *RHSCst;
1600 Instruction::BinaryOps LHSCC, RHSCC;
1601 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1602 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1603 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1604 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1605 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1606 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1607 // Ensure that the larger constant is on the RHS.
1608 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1609 SetCondInst *LHS = cast<SetCondInst>(Op0);
1610 if (cast<ConstantBool>(Cmp)->getValue()) {
1611 std::swap(LHS, RHS);
1612 std::swap(LHSCst, RHSCst);
1613 std::swap(LHSCC, RHSCC);
1614 }
1615
1616 // At this point, we know we have have two setcc instructions
1617 // comparing a value against two constants and or'ing the result
1618 // together. Because of the above check, we know that we only have
1619 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1620 // FoldSetCCLogical check above), that the two constants are not
1621 // equal.
1622 assert(LHSCst != RHSCst && "Compares not folded above?");
1623
1624 switch (LHSCC) {
1625 default: assert(0 && "Unknown integer condition code!");
1626 case Instruction::SetEQ:
1627 switch (RHSCC) {
1628 default: assert(0 && "Unknown integer condition code!");
1629 case Instruction::SetEQ:
1630 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1631 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1632 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1633 LHSVal->getName()+".off");
1634 InsertNewInstBefore(Add, I);
1635 const Type *UnsType = Add->getType()->getUnsignedVersion();
1636 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1637 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1638 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1639 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1640 }
1641 break; // (X == 13 | X == 15) -> no change
1642
1643 case Instruction::SetGT:
1644 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1645 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1646 break; // (X == 13 | X > 15) -> no change
1647 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1648 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1649 return ReplaceInstUsesWith(I, RHS);
1650 }
1651 break;
1652 case Instruction::SetNE:
1653 switch (RHSCC) {
1654 default: assert(0 && "Unknown integer condition code!");
1655 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1656 return ReplaceInstUsesWith(I, RHS);
1657 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1658 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1659 return ReplaceInstUsesWith(I, LHS);
1660 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1661 return ReplaceInstUsesWith(I, ConstantBool::True);
1662 }
1663 break;
1664 case Instruction::SetLT:
1665 switch (RHSCC) {
1666 default: assert(0 && "Unknown integer condition code!");
1667 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1668 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001669 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1670 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001671 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1672 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1673 return ReplaceInstUsesWith(I, RHS);
1674 }
1675 break;
1676 case Instruction::SetGT:
1677 switch (RHSCC) {
1678 default: assert(0 && "Unknown integer condition code!");
1679 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1680 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1681 return ReplaceInstUsesWith(I, LHS);
1682 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1683 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1684 return ReplaceInstUsesWith(I, ConstantBool::True);
1685 }
1686 }
1687 }
1688 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001689 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001690}
1691
Chris Lattnerc2076352004-02-16 01:20:27 +00001692// XorSelf - Implements: X ^ X --> 0
1693struct XorSelf {
1694 Value *RHS;
1695 XorSelf(Value *rhs) : RHS(rhs) {}
1696 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1697 Instruction *apply(BinaryOperator &Xor) const {
1698 return &Xor;
1699 }
1700};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001701
1702
Chris Lattner113f4f42002-06-25 16:13:24 +00001703Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001704 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001705 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001706
Chris Lattner81a7a232004-10-16 18:11:37 +00001707 if (isa<UndefValue>(Op1))
1708 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1709
Chris Lattnerc2076352004-02-16 01:20:27 +00001710 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1711 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1712 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001713 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001714 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001715
Chris Lattner97638592003-07-23 21:37:07 +00001716 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001717 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001718 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001719 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001720
Chris Lattner97638592003-07-23 21:37:07 +00001721 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001722 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001723 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001724 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001725 return new SetCondInst(SCI->getInverseCondition(),
1726 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001727
Chris Lattner8f2f5982003-11-05 01:06:05 +00001728 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001729 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1730 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001731 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1732 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001733 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001734 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001735 }
Chris Lattner023a4832004-06-18 06:07:51 +00001736
1737 // ~(~X & Y) --> (X | ~Y)
1738 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1739 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1740 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1741 Instruction *NotY =
1742 BinaryOperator::createNot(Op0I->getOperand(1),
1743 Op0I->getOperand(1)->getName()+".not");
1744 InsertNewInstBefore(NotY, I);
1745 return BinaryOperator::createOr(Op0NotVal, NotY);
1746 }
1747 }
Chris Lattner97638592003-07-23 21:37:07 +00001748
1749 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001750 switch (Op0I->getOpcode()) {
1751 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001752 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001753 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001754 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1755 return BinaryOperator::createSub(
1756 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001757 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001758 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001759 }
Chris Lattnere5806662003-11-04 23:50:51 +00001760 break;
1761 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001762 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001763 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1764 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001765 break;
1766 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001767 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001768 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001769 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001770 break;
1771 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001772 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001773 }
Chris Lattner183b3362004-04-09 19:05:30 +00001774
1775 // Try to fold constant and into select arguments.
1776 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1777 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1778 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001779 if (isa<PHINode>(Op0))
1780 if (Instruction *NV = FoldOpIntoPhi(I))
1781 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001782 }
1783
Chris Lattnerbb74e222003-03-10 23:06:50 +00001784 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001785 if (X == Op1)
1786 return ReplaceInstUsesWith(I,
1787 ConstantIntegral::getAllOnesValue(I.getType()));
1788
Chris Lattnerbb74e222003-03-10 23:06:50 +00001789 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001790 if (X == Op0)
1791 return ReplaceInstUsesWith(I,
1792 ConstantIntegral::getAllOnesValue(I.getType()));
1793
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001794 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001795 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001796 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1797 cast<BinaryOperator>(Op1I)->swapOperands();
1798 I.swapOperands();
1799 std::swap(Op0, Op1);
1800 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1801 I.swapOperands();
1802 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001803 }
1804 } else if (Op1I->getOpcode() == Instruction::Xor) {
1805 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1806 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1807 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1808 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1809 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001810
1811 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001812 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001813 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1814 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001815 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001816 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1817 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001818 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001819 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001820 } else if (Op0I->getOpcode() == Instruction::Xor) {
1821 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1822 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1823 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1824 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001825 }
1826
Chris Lattner7aa2d472004-08-01 19:42:59 +00001827 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001828 Value *A, *B; ConstantInt *C1, *C2;
1829 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1830 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001831 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001832 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001833
Chris Lattner3ac7c262003-08-13 20:16:26 +00001834 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1835 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1836 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1837 return R;
1838
Chris Lattner113f4f42002-06-25 16:13:24 +00001839 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001840}
1841
Chris Lattner6862fbd2004-09-29 17:40:11 +00001842/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1843/// overflowed for this type.
1844static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1845 ConstantInt *In2) {
1846 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1847 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1848}
1849
1850static bool isPositive(ConstantInt *C) {
1851 return cast<ConstantSInt>(C)->getValue() >= 0;
1852}
1853
1854/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1855/// overflowed for this type.
1856static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1857 ConstantInt *In2) {
1858 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1859
1860 if (In1->getType()->isUnsigned())
1861 return cast<ConstantUInt>(Result)->getValue() <
1862 cast<ConstantUInt>(In1)->getValue();
1863 if (isPositive(In1) != isPositive(In2))
1864 return false;
1865 if (isPositive(In1))
1866 return cast<ConstantSInt>(Result)->getValue() <
1867 cast<ConstantSInt>(In1)->getValue();
1868 return cast<ConstantSInt>(Result)->getValue() >
1869 cast<ConstantSInt>(In1)->getValue();
1870}
1871
Chris Lattner113f4f42002-06-25 16:13:24 +00001872Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001873 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001874 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1875 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001876
1877 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001878 if (Op0 == Op1)
1879 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001880
Chris Lattner81a7a232004-10-16 18:11:37 +00001881 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1882 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1883
Chris Lattner15ff1e12004-11-14 07:33:16 +00001884 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
1885 // addresses never equal each other! We already know that Op0 != Op1.
1886 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
1887 isa<ConstantPointerNull>(Op0)) &&
1888 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
1889 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001890 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1891
1892 // setcc's with boolean values can always be turned into bitwise operations
1893 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001894 switch (I.getOpcode()) {
1895 default: assert(0 && "Invalid setcc instruction!");
1896 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001897 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001898 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001899 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001900 }
Chris Lattner4456da62004-08-11 00:50:51 +00001901 case Instruction::SetNE:
1902 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001903
Chris Lattner4456da62004-08-11 00:50:51 +00001904 case Instruction::SetGT:
1905 std::swap(Op0, Op1); // Change setgt -> setlt
1906 // FALL THROUGH
1907 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1908 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1909 InsertNewInstBefore(Not, I);
1910 return BinaryOperator::createAnd(Not, Op1);
1911 }
1912 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001913 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001914 // FALL THROUGH
1915 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1916 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1917 InsertNewInstBefore(Not, I);
1918 return BinaryOperator::createOr(Not, Op1);
1919 }
1920 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001921 }
1922
Chris Lattner2dd01742004-06-09 04:24:29 +00001923 // See if we are doing a comparison between a constant and an instruction that
1924 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001925 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00001926 // Check to see if we are comparing against the minimum or maximum value...
1927 if (CI->isMinValue()) {
1928 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1929 return ReplaceInstUsesWith(I, ConstantBool::False);
1930 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1931 return ReplaceInstUsesWith(I, ConstantBool::True);
1932 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1933 return BinaryOperator::createSetEQ(Op0, Op1);
1934 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1935 return BinaryOperator::createSetNE(Op0, Op1);
1936
1937 } else if (CI->isMaxValue()) {
1938 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1939 return ReplaceInstUsesWith(I, ConstantBool::False);
1940 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1941 return ReplaceInstUsesWith(I, ConstantBool::True);
1942 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1943 return BinaryOperator::createSetEQ(Op0, Op1);
1944 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1945 return BinaryOperator::createSetNE(Op0, Op1);
1946
1947 // Comparing against a value really close to min or max?
1948 } else if (isMinValuePlusOne(CI)) {
1949 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1950 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1951 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1952 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1953
1954 } else if (isMaxValueMinusOne(CI)) {
1955 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1956 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1957 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1958 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1959 }
1960
1961 // If we still have a setle or setge instruction, turn it into the
1962 // appropriate setlt or setgt instruction. Since the border cases have
1963 // already been handled above, this requires little checking.
1964 //
1965 if (I.getOpcode() == Instruction::SetLE)
1966 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1967 if (I.getOpcode() == Instruction::SetGE)
1968 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1969
Chris Lattnere1e10e12004-05-25 06:32:08 +00001970 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001971 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001972 case Instruction::PHI:
1973 if (Instruction *NV = FoldOpIntoPhi(I))
1974 return NV;
1975 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001976 case Instruction::And:
1977 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1978 LHSI->getOperand(0)->hasOneUse()) {
1979 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1980 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1981 // happens a LOT in code produced by the C front-end, for bitfield
1982 // access.
1983 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1984 ConstantUInt *ShAmt;
1985 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1986 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1987 const Type *Ty = LHSI->getType();
1988
1989 // We can fold this as long as we can't shift unknown bits
1990 // into the mask. This can only happen with signed shift
1991 // rights, as they sign-extend.
1992 if (ShAmt) {
1993 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00001994 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001995 if (!CanFold) {
1996 // To test for the bad case of the signed shr, see if any
1997 // of the bits shifted in could be tested after the mask.
1998 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001999 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002000 Constant *ShVal =
2001 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2002 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2003 CanFold = true;
2004 }
2005
2006 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002007 Constant *NewCst;
2008 if (Shift->getOpcode() == Instruction::Shl)
2009 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2010 else
2011 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002012
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002013 // Check to see if we are shifting out any of the bits being
2014 // compared.
2015 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2016 // If we shifted bits out, the fold is not going to work out.
2017 // As a special case, check to see if this means that the
2018 // result is always true or false now.
2019 if (I.getOpcode() == Instruction::SetEQ)
2020 return ReplaceInstUsesWith(I, ConstantBool::False);
2021 if (I.getOpcode() == Instruction::SetNE)
2022 return ReplaceInstUsesWith(I, ConstantBool::True);
2023 } else {
2024 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002025 Constant *NewAndCST;
2026 if (Shift->getOpcode() == Instruction::Shl)
2027 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2028 else
2029 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2030 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002031 LHSI->setOperand(0, Shift->getOperand(0));
2032 WorkList.push_back(Shift); // Shift is dead.
2033 AddUsesToWorkList(I);
2034 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002035 }
2036 }
Chris Lattner35167c32004-06-09 07:59:58 +00002037 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002038 }
2039 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002040
Reid Spencer279fa252004-11-28 21:31:15 +00002041 // (setcc (cast X to larger), CI)
2042 case Instruction::Cast: {
2043 Instruction* replacement =
2044 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI);
2045 if (replacement)
2046 return replacement;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002047 break;
2048 }
Reid Spencer279fa252004-11-28 21:31:15 +00002049
Chris Lattner272d5ca2004-09-28 18:22:15 +00002050 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2051 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2052 switch (I.getOpcode()) {
2053 default: break;
2054 case Instruction::SetEQ:
2055 case Instruction::SetNE: {
2056 // If we are comparing against bits always shifted out, the
2057 // comparison cannot succeed.
2058 Constant *Comp =
2059 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2060 if (Comp != CI) {// Comparing against a bit that we know is zero.
2061 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2062 Constant *Cst = ConstantBool::get(IsSetNE);
2063 return ReplaceInstUsesWith(I, Cst);
2064 }
2065
2066 if (LHSI->hasOneUse()) {
2067 // Otherwise strength reduce the shift into an and.
2068 unsigned ShAmtVal = ShAmt->getValue();
2069 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2070 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2071
2072 Constant *Mask;
2073 if (CI->getType()->isUnsigned()) {
2074 Mask = ConstantUInt::get(CI->getType(), Val);
2075 } else if (ShAmtVal != 0) {
2076 Mask = ConstantSInt::get(CI->getType(), Val);
2077 } else {
2078 Mask = ConstantInt::getAllOnesValue(CI->getType());
2079 }
2080
2081 Instruction *AndI =
2082 BinaryOperator::createAnd(LHSI->getOperand(0),
2083 Mask, LHSI->getName()+".mask");
2084 Value *And = InsertNewInstBefore(AndI, I);
2085 return new SetCondInst(I.getOpcode(), And,
2086 ConstantExpr::getUShr(CI, ShAmt));
2087 }
2088 }
2089 }
2090 }
2091 break;
2092
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002093 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002094 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002095 switch (I.getOpcode()) {
2096 default: break;
2097 case Instruction::SetEQ:
2098 case Instruction::SetNE: {
2099 // If we are comparing against bits always shifted out, the
2100 // comparison cannot succeed.
2101 Constant *Comp =
2102 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2103
2104 if (Comp != CI) {// Comparing against a bit that we know is zero.
2105 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2106 Constant *Cst = ConstantBool::get(IsSetNE);
2107 return ReplaceInstUsesWith(I, Cst);
2108 }
2109
2110 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00002111 unsigned ShAmtVal = ShAmt->getValue();
2112
Chris Lattner1023b872004-09-27 16:18:50 +00002113 // Otherwise strength reduce the shift into an and.
2114 uint64_t Val = ~0ULL; // All ones.
2115 Val <<= ShAmtVal; // Shift over to the right spot.
2116
2117 Constant *Mask;
2118 if (CI->getType()->isUnsigned()) {
2119 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2120 Val &= (1ULL << TypeBits)-1;
2121 Mask = ConstantUInt::get(CI->getType(), Val);
2122 } else {
2123 Mask = ConstantSInt::get(CI->getType(), Val);
2124 }
2125
2126 Instruction *AndI =
2127 BinaryOperator::createAnd(LHSI->getOperand(0),
2128 Mask, LHSI->getName()+".mask");
2129 Value *And = InsertNewInstBefore(AndI, I);
2130 return new SetCondInst(I.getOpcode(), And,
2131 ConstantExpr::getShl(CI, ShAmt));
2132 }
2133 break;
2134 }
2135 }
2136 }
2137 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002138
Chris Lattner6862fbd2004-09-29 17:40:11 +00002139 case Instruction::Div:
2140 // Fold: (div X, C1) op C2 -> range check
2141 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2142 // Fold this div into the comparison, producing a range check.
2143 // Determine, based on the divide type, what the range is being
2144 // checked. If there is an overflow on the low or high side, remember
2145 // it, otherwise compute the range [low, hi) bounding the new value.
2146 bool LoOverflow = false, HiOverflow = 0;
2147 ConstantInt *LoBound = 0, *HiBound = 0;
2148
2149 ConstantInt *Prod;
2150 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2151
Chris Lattnera92af962004-10-11 19:40:04 +00002152 Instruction::BinaryOps Opcode = I.getOpcode();
2153
Chris Lattner6862fbd2004-09-29 17:40:11 +00002154 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2155 } else if (LHSI->getType()->isUnsigned()) { // udiv
2156 LoBound = Prod;
2157 LoOverflow = ProdOV;
2158 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2159 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2160 if (CI->isNullValue()) { // (X / pos) op 0
2161 // Can't overflow.
2162 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2163 HiBound = DivRHS;
2164 } else if (isPositive(CI)) { // (X / pos) op pos
2165 LoBound = Prod;
2166 LoOverflow = ProdOV;
2167 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2168 } else { // (X / pos) op neg
2169 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2170 LoOverflow = AddWithOverflow(LoBound, Prod,
2171 cast<ConstantInt>(DivRHSH));
2172 HiBound = Prod;
2173 HiOverflow = ProdOV;
2174 }
2175 } else { // Divisor is < 0.
2176 if (CI->isNullValue()) { // (X / neg) op 0
2177 LoBound = AddOne(DivRHS);
2178 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2179 } else if (isPositive(CI)) { // (X / neg) op pos
2180 HiOverflow = LoOverflow = ProdOV;
2181 if (!LoOverflow)
2182 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2183 HiBound = AddOne(Prod);
2184 } else { // (X / neg) op neg
2185 LoBound = Prod;
2186 LoOverflow = HiOverflow = ProdOV;
2187 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2188 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002189
Chris Lattnera92af962004-10-11 19:40:04 +00002190 // Dividing by a negate swaps the condition.
2191 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002192 }
2193
2194 if (LoBound) {
2195 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002196 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002197 default: assert(0 && "Unhandled setcc opcode!");
2198 case Instruction::SetEQ:
2199 if (LoOverflow && HiOverflow)
2200 return ReplaceInstUsesWith(I, ConstantBool::False);
2201 else if (HiOverflow)
2202 return new SetCondInst(Instruction::SetGE, X, LoBound);
2203 else if (LoOverflow)
2204 return new SetCondInst(Instruction::SetLT, X, HiBound);
2205 else
2206 return InsertRangeTest(X, LoBound, HiBound, true, I);
2207 case Instruction::SetNE:
2208 if (LoOverflow && HiOverflow)
2209 return ReplaceInstUsesWith(I, ConstantBool::True);
2210 else if (HiOverflow)
2211 return new SetCondInst(Instruction::SetLT, X, LoBound);
2212 else if (LoOverflow)
2213 return new SetCondInst(Instruction::SetGE, X, HiBound);
2214 else
2215 return InsertRangeTest(X, LoBound, HiBound, false, I);
2216 case Instruction::SetLT:
2217 if (LoOverflow)
2218 return ReplaceInstUsesWith(I, ConstantBool::False);
2219 return new SetCondInst(Instruction::SetLT, X, LoBound);
2220 case Instruction::SetGT:
2221 if (HiOverflow)
2222 return ReplaceInstUsesWith(I, ConstantBool::False);
2223 return new SetCondInst(Instruction::SetGE, X, HiBound);
2224 }
2225 }
2226 }
2227 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002228 case Instruction::Select:
2229 // If either operand of the select is a constant, we can fold the
2230 // comparison into the select arms, which will cause one to be
2231 // constant folded and the select turned into a bitwise or.
2232 Value *Op1 = 0, *Op2 = 0;
2233 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002234 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002235 // Fold the known value into the constant operand.
2236 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2237 // Insert a new SetCC of the other select operand.
2238 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002239 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002240 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002241 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002242 // Fold the known value into the constant operand.
2243 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2244 // Insert a new SetCC of the other select operand.
2245 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002246 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002247 I.getName()), I);
2248 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002249 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002250
2251 if (Op1)
2252 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2253 break;
2254 }
2255
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002256 // Simplify seteq and setne instructions...
2257 if (I.getOpcode() == Instruction::SetEQ ||
2258 I.getOpcode() == Instruction::SetNE) {
2259 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2260
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002261 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002262 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002263 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2264 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002265 case Instruction::Rem:
2266 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2267 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2268 BO->hasOneUse() &&
2269 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2270 if (unsigned L2 =
2271 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2272 const Type *UTy = BO->getType()->getUnsignedVersion();
2273 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2274 UTy, "tmp"), I);
2275 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2276 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2277 RHSCst, BO->getName()), I);
2278 return BinaryOperator::create(I.getOpcode(), NewRem,
2279 Constant::getNullValue(UTy));
2280 }
2281 break;
2282
Chris Lattnerc992add2003-08-13 05:33:12 +00002283 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002284 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2285 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002286 if (BO->hasOneUse())
2287 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2288 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002289 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002290 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2291 // efficiently invertible, or if the add has just this one use.
2292 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002293
Chris Lattnerc992add2003-08-13 05:33:12 +00002294 if (Value *NegVal = dyn_castNegVal(BOp1))
2295 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2296 else if (Value *NegVal = dyn_castNegVal(BOp0))
2297 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002298 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002299 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2300 BO->setName("");
2301 InsertNewInstBefore(Neg, I);
2302 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2303 }
2304 }
2305 break;
2306 case Instruction::Xor:
2307 // For the xor case, we can xor two constants together, eliminating
2308 // the explicit xor.
2309 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2310 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002311 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002312
2313 // FALLTHROUGH
2314 case Instruction::Sub:
2315 // Replace (([sub|xor] A, B) != 0) with (A != B)
2316 if (CI->isNullValue())
2317 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2318 BO->getOperand(1));
2319 break;
2320
2321 case Instruction::Or:
2322 // If bits are being or'd in that are not present in the constant we
2323 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002324 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002325 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002326 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002327 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002328 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002329 break;
2330
2331 case Instruction::And:
2332 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002333 // If bits are being compared against that are and'd out, then the
2334 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002335 if (!ConstantExpr::getAnd(CI,
2336 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002337 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002338
Chris Lattner35167c32004-06-09 07:59:58 +00002339 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002340 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002341 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2342 Instruction::SetNE, Op0,
2343 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002344
Chris Lattnerc992add2003-08-13 05:33:12 +00002345 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2346 // to be a signed value as appropriate.
2347 if (isSignBit(BOC)) {
2348 Value *X = BO->getOperand(0);
2349 // If 'X' is not signed, insert a cast now...
2350 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002351 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002352 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002353 }
2354 return new SetCondInst(isSetNE ? Instruction::SetLT :
2355 Instruction::SetGE, X,
2356 Constant::getNullValue(X->getType()));
2357 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002358
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002359 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002360 if (CI->isNullValue() && isHighOnes(BOC)) {
2361 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002362 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002363
2364 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002365 if (NegX->getType()->isSigned()) {
2366 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2367 X = InsertCastBefore(X, DestTy, I);
2368 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002369 }
2370
2371 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002372 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002373 }
2374
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002375 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002376 default: break;
2377 }
2378 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002379 } else { // Not a SetEQ/SetNE
2380 // If the LHS is a cast from an integral value of the same size,
2381 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2382 Value *CastOp = Cast->getOperand(0);
2383 const Type *SrcTy = CastOp->getType();
2384 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2385 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2386 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2387 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2388 "Source and destination signednesses should differ!");
2389 if (Cast->getType()->isSigned()) {
2390 // If this is a signed comparison, check for comparisons in the
2391 // vicinity of zero.
2392 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2393 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002394 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002395 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2396 else if (I.getOpcode() == Instruction::SetGT &&
2397 cast<ConstantSInt>(CI)->getValue() == -1)
2398 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002399 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002400 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2401 } else {
2402 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2403 if (I.getOpcode() == Instruction::SetLT &&
2404 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2405 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002406 return BinaryOperator::createSetGT(CastOp,
2407 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002408 else if (I.getOpcode() == Instruction::SetGT &&
2409 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2410 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002411 return BinaryOperator::createSetLT(CastOp,
2412 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002413 }
2414 }
2415 }
Chris Lattnere967b342003-06-04 05:10:11 +00002416 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002417 }
2418
Chris Lattner16930792003-11-03 04:25:02 +00002419 // Test to see if the operands of the setcc are casted versions of other
2420 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002421 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2422 Value *CastOp0 = CI->getOperand(0);
2423 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002424 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002425 (I.getOpcode() == Instruction::SetEQ ||
2426 I.getOpcode() == Instruction::SetNE)) {
2427 // We keep moving the cast from the left operand over to the right
2428 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002429 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002430
2431 // If operand #1 is a cast instruction, see if we can eliminate it as
2432 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002433 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2434 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002435 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002436 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002437
2438 // If Op1 is a constant, we can fold the cast into the constant.
2439 if (Op1->getType() != Op0->getType())
2440 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2441 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2442 } else {
2443 // Otherwise, cast the RHS right before the setcc
2444 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2445 InsertNewInstBefore(cast<Instruction>(Op1), I);
2446 }
2447 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2448 }
2449
Chris Lattner6444c372003-11-03 05:17:03 +00002450 // Handle the special case of: setcc (cast bool to X), <cst>
2451 // This comes up when you have code like
2452 // int X = A < B;
2453 // if (X) ...
2454 // For generality, we handle any zero-extension of any operand comparison
2455 // with a constant.
2456 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2457 const Type *SrcTy = CastOp0->getType();
2458 const Type *DestTy = Op0->getType();
2459 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2460 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2461 // Ok, we have an expansion of operand 0 into a new type. Get the
2462 // constant value, masink off bits which are not set in the RHS. These
2463 // could be set if the destination value is signed.
2464 uint64_t ConstVal = ConstantRHS->getRawValue();
2465 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2466
2467 // If the constant we are comparing it with has high bits set, which
2468 // don't exist in the original value, the values could never be equal,
2469 // because the source would be zero extended.
2470 unsigned SrcBits =
2471 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002472 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2473 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002474 switch (I.getOpcode()) {
2475 default: assert(0 && "Unknown comparison type!");
2476 case Instruction::SetEQ:
2477 return ReplaceInstUsesWith(I, ConstantBool::False);
2478 case Instruction::SetNE:
2479 return ReplaceInstUsesWith(I, ConstantBool::True);
2480 case Instruction::SetLT:
2481 case Instruction::SetLE:
2482 if (DestTy->isSigned() && HasSignBit)
2483 return ReplaceInstUsesWith(I, ConstantBool::False);
2484 return ReplaceInstUsesWith(I, ConstantBool::True);
2485 case Instruction::SetGT:
2486 case Instruction::SetGE:
2487 if (DestTy->isSigned() && HasSignBit)
2488 return ReplaceInstUsesWith(I, ConstantBool::True);
2489 return ReplaceInstUsesWith(I, ConstantBool::False);
2490 }
2491 }
2492
2493 // Otherwise, we can replace the setcc with a setcc of the smaller
2494 // operand value.
2495 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2496 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2497 }
2498 }
2499 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002500 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002501}
2502
Reid Spencer279fa252004-11-28 21:31:15 +00002503// visitSetCondInstWithCastAndConstant - this method is part of the
2504// visitSetCondInst method. It handles the situation where we have:
2505// (setcc (cast X to larger), CI)
2506// It tries to remove the cast and even the setcc if the CI value
2507// and range of the cast allow it.
2508Instruction *
2509InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2510 CastInst* LHSI,
2511 ConstantInt* CI) {
2512 const Type *SrcTy = LHSI->getOperand(0)->getType();
2513 const Type *DestTy = LHSI->getType();
2514 if (SrcTy->isIntegral() && DestTy->isIntegral()) {
2515 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2516 unsigned DestBits = DestTy->getPrimitiveSize()*8;
2517 if (SrcTy == Type::BoolTy)
2518 SrcBits = 1;
2519 if (DestTy == Type::BoolTy)
2520 DestBits = 1;
2521 if (SrcBits < DestBits) {
2522 // There are fewer bits in the source of the cast than in the result
2523 // of the cast. Any other case doesn't matter because the constant
2524 // value won't have changed due to sign extension.
2525 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2526 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
2527 // The constant value operand of the setCC before and after a
2528 // cast to the source type of the cast instruction is the same
2529 // value, so we just replace with the same setcc opcode, but
2530 // using the source value compared to the constant casted to the
2531 // source type.
2532 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
2533 CastInst* Cst = new CastInst(LHSI->getOperand(0),
2534 SrcTy->getUnsignedVersion(), LHSI->getName());
2535 InsertNewInstBefore(Cst,I);
2536 return new SetCondInst(I.getOpcode(), Cst,
2537 ConstantExpr::getCast(CI, SrcTy->getUnsignedVersion()));
2538 }
2539 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
2540 }
2541 // The constant value before and after a cast to the source type
2542 // is different, so various cases are possible depending on the
2543 // opcode and the signs of the types involved in the cast.
2544 switch (I.getOpcode()) {
2545 case Instruction::SetLT: {
2546 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
2547 Max = ConstantExpr::getCast(Max, DestTy);
2548 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2549 }
2550 case Instruction::SetGT: {
2551 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
2552 Min = ConstantExpr::getCast(Min, DestTy);
2553 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2554 }
2555 case Instruction::SetEQ:
2556 // We're looking for equality, and we know the values are not
2557 // equal so replace with constant False.
2558 return ReplaceInstUsesWith(I, ConstantBool::False);
2559 case Instruction::SetNE:
2560 // We're testing for inequality, and we know the values are not
2561 // equal so replace with constant True.
2562 return ReplaceInstUsesWith(I, ConstantBool::True);
2563 case Instruction::SetLE:
2564 case Instruction::SetGE:
2565 assert(!"SetLE and SetGE should be handled elsewhere");
2566 default:
2567 assert(!"unknown integer comparison");
2568 }
2569 }
2570 }
2571 return 0;
2572}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002573
2574
Chris Lattnere8d6c602003-03-10 19:16:08 +00002575Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002576 assert(I.getOperand(1)->getType() == Type::UByteTy);
2577 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002578 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002579
2580 // shl X, 0 == X and shr X, 0 == X
2581 // shl 0, X == 0 and shr 0, X == 0
2582 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002583 Op0 == Constant::getNullValue(Op0->getType()))
2584 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002585
Chris Lattner81a7a232004-10-16 18:11:37 +00002586 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2587 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00002588 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00002589 else // undef << X -> 0 AND undef >>u X -> 0
2590 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2591 }
2592 if (isa<UndefValue>(Op1)) {
2593 if (isLeftShift || I.getType()->isUnsigned())
2594 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2595 else
2596 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2597 }
2598
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002599 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2600 if (!isLeftShift)
2601 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2602 if (CSI->isAllOnesValue())
2603 return ReplaceInstUsesWith(I, CSI);
2604
Chris Lattner183b3362004-04-09 19:05:30 +00002605 // Try to fold constant and into select arguments.
2606 if (isa<Constant>(Op0))
2607 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2608 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2609 return R;
2610
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002611 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002612 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2613 // of a signed value.
2614 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002615 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002616 if (CUI->getValue() >= TypeBits) {
2617 if (!Op0->getType()->isSigned() || isLeftShift)
2618 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2619 else {
2620 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2621 return &I;
2622 }
2623 }
Chris Lattner55f3d942002-09-10 23:04:09 +00002624
Chris Lattnerede3fe02003-08-13 04:18:28 +00002625 // ((X*C1) << C2) == (X * (C1 << C2))
2626 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2627 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2628 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002629 return BinaryOperator::createMul(BO->getOperand(0),
2630 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00002631
Chris Lattner183b3362004-04-09 19:05:30 +00002632 // Try to fold constant and into select arguments.
2633 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2634 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2635 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002636 if (isa<PHINode>(Op0))
2637 if (Instruction *NV = FoldOpIntoPhi(I))
2638 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00002639
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002640 // If the operand is an bitwise operator with a constant RHS, and the
2641 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002642 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002643 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2644 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2645 bool isValid = true; // Valid only for And, Or, Xor
2646 bool highBitSet = false; // Transform if high bit of constant set?
2647
2648 switch (Op0BO->getOpcode()) {
2649 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00002650 case Instruction::Add:
2651 isValid = isLeftShift;
2652 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002653 case Instruction::Or:
2654 case Instruction::Xor:
2655 highBitSet = false;
2656 break;
2657 case Instruction::And:
2658 highBitSet = true;
2659 break;
2660 }
2661
2662 // If this is a signed shift right, and the high bit is modified
2663 // by the logical operation, do not perform the transformation.
2664 // The highBitSet boolean indicates the value of the high bit of
2665 // the constant which would cause it to be modified for this
2666 // operation.
2667 //
2668 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2669 uint64_t Val = Op0C->getRawValue();
2670 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2671 }
2672
2673 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002674 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002675
2676 Instruction *NewShift =
2677 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2678 Op0BO->getName());
2679 Op0BO->setName("");
2680 InsertNewInstBefore(NewShift, I);
2681
2682 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2683 NewRHS);
2684 }
2685 }
2686
Chris Lattner3204d4e2003-07-24 17:52:58 +00002687 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002688 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002689 if (ConstantUInt *ShiftAmt1C =
2690 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002691 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2692 unsigned ShiftAmt2 = CUI->getValue();
2693
2694 // Check for (A << c1) << c2 and (A >> c1) >> c2
2695 if (I.getOpcode() == Op0SI->getOpcode()) {
2696 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002697 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2698 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002699 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2700 ConstantUInt::get(Type::UByteTy, Amt));
2701 }
2702
Chris Lattnerab780df2003-07-24 18:38:56 +00002703 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2704 // signed types, we can only support the (A >> c1) << c2 configuration,
2705 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002706 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002707 // Calculate bitmask for what gets shifted off the edge...
2708 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002709 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002710 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002711 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002712 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002713
2714 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002715 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2716 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002717 InsertNewInstBefore(Mask, I);
2718
2719 // Figure out what flavor of shift we should use...
2720 if (ShiftAmt1 == ShiftAmt2)
2721 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2722 else if (ShiftAmt1 < ShiftAmt2) {
2723 return new ShiftInst(I.getOpcode(), Mask,
2724 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2725 } else {
2726 return new ShiftInst(Op0SI->getOpcode(), Mask,
2727 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2728 }
2729 }
2730 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002731 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002732
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002733 return 0;
2734}
2735
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002736enum CastType {
2737 Noop = 0,
2738 Truncate = 1,
2739 Signext = 2,
2740 Zeroext = 3
2741};
2742
2743/// getCastType - In the future, we will split the cast instruction into these
2744/// various types. Until then, we have to do the analysis here.
2745static CastType getCastType(const Type *Src, const Type *Dest) {
2746 assert(Src->isIntegral() && Dest->isIntegral() &&
2747 "Only works on integral types!");
2748 unsigned SrcSize = Src->getPrimitiveSize()*8;
2749 if (Src == Type::BoolTy) SrcSize = 1;
2750 unsigned DestSize = Dest->getPrimitiveSize()*8;
2751 if (Dest == Type::BoolTy) DestSize = 1;
2752
2753 if (SrcSize == DestSize) return Noop;
2754 if (SrcSize > DestSize) return Truncate;
2755 if (Src->isSigned()) return Signext;
2756 return Zeroext;
2757}
2758
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002759
Chris Lattner48a44f72002-05-02 17:06:02 +00002760// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2761// instruction.
2762//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002763static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002764 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002765
Chris Lattner650b6da2002-08-02 20:00:25 +00002766 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2767 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002768 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002769 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002770 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002771
Chris Lattner4fbad962004-07-21 04:27:24 +00002772 // If we are casting between pointer and integer types, treat pointers as
2773 // integers of the appropriate size for the code below.
2774 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2775 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2776 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002777
Chris Lattner48a44f72002-05-02 17:06:02 +00002778 // Allow free casting and conversion of sizes as long as the sign doesn't
2779 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002780 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002781 CastType FirstCast = getCastType(SrcTy, MidTy);
2782 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002783
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002784 // Capture the effect of these two casts. If the result is a legal cast,
2785 // the CastType is stored here, otherwise a special code is used.
2786 static const unsigned CastResult[] = {
2787 // First cast is noop
2788 0, 1, 2, 3,
2789 // First cast is a truncate
2790 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2791 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002792 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002793 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002794 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002795 };
2796
2797 unsigned Result = CastResult[FirstCast*4+SecondCast];
2798 switch (Result) {
2799 default: assert(0 && "Illegal table value!");
2800 case 0:
2801 case 1:
2802 case 2:
2803 case 3:
2804 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2805 // truncates, we could eliminate more casts.
2806 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2807 case 4:
2808 return false; // Not possible to eliminate this here.
2809 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002810 // Sign or zero extend followed by truncate is always ok if the result
2811 // is a truncate or noop.
2812 CastType ResultCast = getCastType(SrcTy, DstTy);
2813 if (ResultCast == Noop || ResultCast == Truncate)
2814 return true;
2815 // Otherwise we are still growing the value, we are only safe if the
2816 // result will match the sign/zeroextendness of the result.
2817 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002818 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002819 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002820 return false;
2821}
2822
Chris Lattner11ffd592004-07-20 05:21:00 +00002823static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002824 if (V->getType() == Ty || isa<Constant>(V)) return false;
2825 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002826 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2827 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002828 return false;
2829 return true;
2830}
2831
2832/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2833/// InsertBefore instruction. This is specialized a bit to avoid inserting
2834/// casts that are known to not do anything...
2835///
2836Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2837 Instruction *InsertBefore) {
2838 if (V->getType() == DestTy) return V;
2839 if (Constant *C = dyn_cast<Constant>(V))
2840 return ConstantExpr::getCast(C, DestTy);
2841
2842 CastInst *CI = new CastInst(V, DestTy, V->getName());
2843 InsertNewInstBefore(CI, *InsertBefore);
2844 return CI;
2845}
Chris Lattner48a44f72002-05-02 17:06:02 +00002846
2847// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002848//
Chris Lattner113f4f42002-06-25 16:13:24 +00002849Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002850 Value *Src = CI.getOperand(0);
2851
Chris Lattner48a44f72002-05-02 17:06:02 +00002852 // If the user is casting a value to the same type, eliminate this cast
2853 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002854 if (CI.getType() == Src->getType())
2855 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002856
Chris Lattner81a7a232004-10-16 18:11:37 +00002857 if (isa<UndefValue>(Src)) // cast undef -> undef
2858 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2859
Chris Lattner48a44f72002-05-02 17:06:02 +00002860 // If casting the result of another cast instruction, try to eliminate this
2861 // one!
2862 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002863 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002864 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002865 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002866 // This instruction now refers directly to the cast's src operand. This
2867 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002868 CI.setOperand(0, CSrc->getOperand(0));
2869 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002870 }
2871
Chris Lattner650b6da2002-08-02 20:00:25 +00002872 // If this is an A->B->A cast, and we are dealing with integral types, try
2873 // to convert this into a logical 'and' instruction.
2874 //
2875 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002876 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002877 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2878 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2879 assert(CSrc->getType() != Type::ULongTy &&
2880 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002881 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002882 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002883 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002884 }
2885 }
2886
Chris Lattner03841652004-05-25 04:29:21 +00002887 // If this is a cast to bool, turn it into the appropriate setne instruction.
2888 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002889 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002890 Constant::getNullValue(CI.getOperand(0)->getType()));
2891
Chris Lattnerd0d51602003-06-21 23:12:02 +00002892 // If casting the result of a getelementptr instruction with no offset, turn
2893 // this into a cast of the original pointer!
2894 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002895 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002896 bool AllZeroOperands = true;
2897 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2898 if (!isa<Constant>(GEP->getOperand(i)) ||
2899 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2900 AllZeroOperands = false;
2901 break;
2902 }
2903 if (AllZeroOperands) {
2904 CI.setOperand(0, GEP->getOperand(0));
2905 return &CI;
2906 }
2907 }
2908
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002909 // If we are casting a malloc or alloca to a pointer to a type of the same
2910 // size, rewrite the allocation instruction to allocate the "right" type.
2911 //
2912 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002913 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002914 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2915 // Get the type really allocated and the type casted to...
2916 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002917 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002918 if (AllocElTy->isSized() && CastElTy->isSized()) {
2919 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2920 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002921
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002922 // If the allocation is for an even multiple of the cast type size
2923 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2924 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002925 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002926 std::string Name = AI->getName(); AI->setName("");
2927 AllocationInst *New;
2928 if (isa<MallocInst>(AI))
2929 New = new MallocInst(CastElTy, Amt, Name);
2930 else
2931 New = new AllocaInst(CastElTy, Amt, Name);
2932 InsertNewInstBefore(New, *AI);
2933 return ReplaceInstUsesWith(CI, New);
2934 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002935 }
2936 }
2937
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002938 if (isa<PHINode>(Src))
2939 if (Instruction *NV = FoldOpIntoPhi(CI))
2940 return NV;
2941
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002942 // If the source value is an instruction with only this use, we can attempt to
2943 // propagate the cast into the instruction. Also, only handle integral types
2944 // for now.
2945 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002946 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002947 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2948 const Type *DestTy = CI.getType();
2949 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2950 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2951
2952 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2953 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2954
2955 switch (SrcI->getOpcode()) {
2956 case Instruction::Add:
2957 case Instruction::Mul:
2958 case Instruction::And:
2959 case Instruction::Or:
2960 case Instruction::Xor:
2961 // If we are discarding information, or just changing the sign, rewrite.
2962 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2963 // Don't insert two casts if they cannot be eliminated. We allow two
2964 // casts to be inserted if the sizes are the same. This could only be
2965 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002966 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2967 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002968 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2969 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2970 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2971 ->getOpcode(), Op0c, Op1c);
2972 }
2973 }
2974 break;
2975 case Instruction::Shl:
2976 // Allow changing the sign of the source operand. Do not allow changing
2977 // the size of the shift, UNLESS the shift amount is a constant. We
2978 // mush not change variable sized shifts to a smaller size, because it
2979 // is undefined to shift more bits out than exist in the value.
2980 if (DestBitSize == SrcBitSize ||
2981 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2982 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2983 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2984 }
2985 break;
2986 }
2987 }
2988
Chris Lattner260ab202002-04-18 17:39:14 +00002989 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002990}
2991
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002992/// GetSelectFoldableOperands - We want to turn code that looks like this:
2993/// %C = or %A, %B
2994/// %D = select %cond, %C, %A
2995/// into:
2996/// %C = select %cond, %B, 0
2997/// %D = or %A, %C
2998///
2999/// Assuming that the specified instruction is an operand to the select, return
3000/// a bitmask indicating which operands of this instruction are foldable if they
3001/// equal the other incoming value of the select.
3002///
3003static unsigned GetSelectFoldableOperands(Instruction *I) {
3004 switch (I->getOpcode()) {
3005 case Instruction::Add:
3006 case Instruction::Mul:
3007 case Instruction::And:
3008 case Instruction::Or:
3009 case Instruction::Xor:
3010 return 3; // Can fold through either operand.
3011 case Instruction::Sub: // Can only fold on the amount subtracted.
3012 case Instruction::Shl: // Can only fold on the shift amount.
3013 case Instruction::Shr:
3014 return 1;
3015 default:
3016 return 0; // Cannot fold
3017 }
3018}
3019
3020/// GetSelectFoldableConstant - For the same transformation as the previous
3021/// function, return the identity constant that goes into the select.
3022static Constant *GetSelectFoldableConstant(Instruction *I) {
3023 switch (I->getOpcode()) {
3024 default: assert(0 && "This cannot happen!"); abort();
3025 case Instruction::Add:
3026 case Instruction::Sub:
3027 case Instruction::Or:
3028 case Instruction::Xor:
3029 return Constant::getNullValue(I->getType());
3030 case Instruction::Shl:
3031 case Instruction::Shr:
3032 return Constant::getNullValue(Type::UByteTy);
3033 case Instruction::And:
3034 return ConstantInt::getAllOnesValue(I->getType());
3035 case Instruction::Mul:
3036 return ConstantInt::get(I->getType(), 1);
3037 }
3038}
3039
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003040Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003041 Value *CondVal = SI.getCondition();
3042 Value *TrueVal = SI.getTrueValue();
3043 Value *FalseVal = SI.getFalseValue();
3044
3045 // select true, X, Y -> X
3046 // select false, X, Y -> Y
3047 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003048 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003049 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003050 else {
3051 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003052 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003053 }
Chris Lattner533bc492004-03-30 19:37:13 +00003054
3055 // select C, X, X -> X
3056 if (TrueVal == FalseVal)
3057 return ReplaceInstUsesWith(SI, TrueVal);
3058
Chris Lattner81a7a232004-10-16 18:11:37 +00003059 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3060 return ReplaceInstUsesWith(SI, FalseVal);
3061 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3062 return ReplaceInstUsesWith(SI, TrueVal);
3063 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3064 if (isa<Constant>(TrueVal))
3065 return ReplaceInstUsesWith(SI, TrueVal);
3066 else
3067 return ReplaceInstUsesWith(SI, FalseVal);
3068 }
3069
Chris Lattner1c631e82004-04-08 04:43:23 +00003070 if (SI.getType() == Type::BoolTy)
3071 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3072 if (C == ConstantBool::True) {
3073 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003074 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003075 } else {
3076 // Change: A = select B, false, C --> A = and !B, C
3077 Value *NotCond =
3078 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3079 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003080 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003081 }
3082 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3083 if (C == ConstantBool::False) {
3084 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003085 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003086 } else {
3087 // Change: A = select B, C, true --> A = or !B, C
3088 Value *NotCond =
3089 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3090 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003091 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003092 }
3093 }
3094
Chris Lattner183b3362004-04-09 19:05:30 +00003095 // Selecting between two integer constants?
3096 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3097 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3098 // select C, 1, 0 -> cast C to int
3099 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3100 return new CastInst(CondVal, SI.getType());
3101 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3102 // select C, 0, 1 -> cast !C to int
3103 Value *NotCond =
3104 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003105 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003106 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003107 }
Chris Lattner35167c32004-06-09 07:59:58 +00003108
3109 // If one of the constants is zero (we know they can't both be) and we
3110 // have a setcc instruction with zero, and we have an 'and' with the
3111 // non-constant value, eliminate this whole mess. This corresponds to
3112 // cases like this: ((X & 27) ? 27 : 0)
3113 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3114 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3115 if ((IC->getOpcode() == Instruction::SetEQ ||
3116 IC->getOpcode() == Instruction::SetNE) &&
3117 isa<ConstantInt>(IC->getOperand(1)) &&
3118 cast<Constant>(IC->getOperand(1))->isNullValue())
3119 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3120 if (ICA->getOpcode() == Instruction::And &&
3121 isa<ConstantInt>(ICA->getOperand(1)) &&
3122 (ICA->getOperand(1) == TrueValC ||
3123 ICA->getOperand(1) == FalseValC) &&
3124 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3125 // Okay, now we know that everything is set up, we just don't
3126 // know whether we have a setne or seteq and whether the true or
3127 // false val is the zero.
3128 bool ShouldNotVal = !TrueValC->isNullValue();
3129 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3130 Value *V = ICA;
3131 if (ShouldNotVal)
3132 V = InsertNewInstBefore(BinaryOperator::create(
3133 Instruction::Xor, V, ICA->getOperand(1)), SI);
3134 return ReplaceInstUsesWith(SI, V);
3135 }
Chris Lattner533bc492004-03-30 19:37:13 +00003136 }
Chris Lattner623fba12004-04-10 22:21:27 +00003137
3138 // See if we are selecting two values based on a comparison of the two values.
3139 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3140 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3141 // Transform (X == Y) ? X : Y -> Y
3142 if (SCI->getOpcode() == Instruction::SetEQ)
3143 return ReplaceInstUsesWith(SI, FalseVal);
3144 // Transform (X != Y) ? X : Y -> X
3145 if (SCI->getOpcode() == Instruction::SetNE)
3146 return ReplaceInstUsesWith(SI, TrueVal);
3147 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3148
3149 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3150 // Transform (X == Y) ? Y : X -> X
3151 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003152 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003153 // Transform (X != Y) ? Y : X -> Y
3154 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003155 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003156 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3157 }
3158 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003159
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003160 // See if we can fold the select into one of our operands.
3161 if (SI.getType()->isInteger()) {
3162 // See the comment above GetSelectFoldableOperands for a description of the
3163 // transformation we are doing here.
3164 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3165 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3166 !isa<Constant>(FalseVal))
3167 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3168 unsigned OpToFold = 0;
3169 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3170 OpToFold = 1;
3171 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3172 OpToFold = 2;
3173 }
3174
3175 if (OpToFold) {
3176 Constant *C = GetSelectFoldableConstant(TVI);
3177 std::string Name = TVI->getName(); TVI->setName("");
3178 Instruction *NewSel =
3179 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3180 Name);
3181 InsertNewInstBefore(NewSel, SI);
3182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3183 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3184 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3185 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3186 else {
3187 assert(0 && "Unknown instruction!!");
3188 }
3189 }
3190 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003191
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003192 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3193 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3194 !isa<Constant>(TrueVal))
3195 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3196 unsigned OpToFold = 0;
3197 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3198 OpToFold = 1;
3199 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3200 OpToFold = 2;
3201 }
3202
3203 if (OpToFold) {
3204 Constant *C = GetSelectFoldableConstant(FVI);
3205 std::string Name = FVI->getName(); FVI->setName("");
3206 Instruction *NewSel =
3207 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3208 Name);
3209 InsertNewInstBefore(NewSel, SI);
3210 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3211 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3212 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3213 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3214 else {
3215 assert(0 && "Unknown instruction!!");
3216 }
3217 }
3218 }
3219 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003220 return 0;
3221}
3222
3223
Chris Lattner970c33a2003-06-19 17:00:31 +00003224// CallInst simplification
3225//
3226Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003227 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3228 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003229 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3230 bool Changed = false;
3231
3232 // memmove/cpy/set of zero bytes is a noop.
3233 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3234 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3235
3236 // FIXME: Increase alignment here.
3237
3238 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3239 if (CI->getRawValue() == 1) {
3240 // Replace the instruction with just byte operations. We would
3241 // transform other cases to loads/stores, but we don't know if
3242 // alignment is sufficient.
3243 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003244 }
3245
Chris Lattner00648e12004-10-12 04:52:52 +00003246 // If we have a memmove and the source operation is a constant global,
3247 // then the source and dest pointers can't alias, so we can change this
3248 // into a call to memcpy.
3249 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3250 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3251 if (GVSrc->isConstant()) {
3252 Module *M = CI.getParent()->getParent()->getParent();
3253 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3254 CI.getCalledFunction()->getFunctionType());
3255 CI.setOperand(0, MemCpy);
3256 Changed = true;
3257 }
3258
3259 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003260 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3261 // If this stoppoint is at the same source location as the previous
3262 // stoppoint in the chain, it is not needed.
3263 if (DbgStopPointInst *PrevSPI =
3264 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3265 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3266 SPI->getColNo() == PrevSPI->getColNo()) {
3267 SPI->replaceAllUsesWith(PrevSPI);
3268 return EraseInstFromFunction(CI);
3269 }
Chris Lattner00648e12004-10-12 04:52:52 +00003270 }
3271
Chris Lattneraec3d942003-10-07 22:32:43 +00003272 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003273}
3274
3275// InvokeInst simplification
3276//
3277Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003278 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003279}
3280
Chris Lattneraec3d942003-10-07 22:32:43 +00003281// visitCallSite - Improvements for call and invoke instructions.
3282//
3283Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003284 bool Changed = false;
3285
3286 // If the callee is a constexpr cast of a function, attempt to move the cast
3287 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003288 if (transformConstExprCastCall(CS)) return 0;
3289
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003290 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003291
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003292 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3293 // This instruction is not reachable, just remove it. We insert a store to
3294 // undef so that we know that this code is not reachable, despite the fact
3295 // that we can't modify the CFG here.
3296 new StoreInst(ConstantBool::True,
3297 UndefValue::get(PointerType::get(Type::BoolTy)),
3298 CS.getInstruction());
3299
3300 if (!CS.getInstruction()->use_empty())
3301 CS.getInstruction()->
3302 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3303
3304 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3305 // Don't break the CFG, insert a dummy cond branch.
3306 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3307 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003308 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003309 return EraseInstFromFunction(*CS.getInstruction());
3310 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003311
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003312 const PointerType *PTy = cast<PointerType>(Callee->getType());
3313 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3314 if (FTy->isVarArg()) {
3315 // See if we can optimize any arguments passed through the varargs area of
3316 // the call.
3317 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3318 E = CS.arg_end(); I != E; ++I)
3319 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3320 // If this cast does not effect the value passed through the varargs
3321 // area, we can eliminate the use of the cast.
3322 Value *Op = CI->getOperand(0);
3323 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3324 *I = Op;
3325 Changed = true;
3326 }
3327 }
3328 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003329
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003330 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003331}
3332
Chris Lattner970c33a2003-06-19 17:00:31 +00003333// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3334// attempt to move the cast to the arguments of the call/invoke.
3335//
3336bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3337 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3338 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003339 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003340 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003341 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003342 Instruction *Caller = CS.getInstruction();
3343
3344 // Okay, this is a cast from a function to a different type. Unless doing so
3345 // would cause a type conversion of one of our arguments, change this call to
3346 // be a direct call with arguments casted to the appropriate types.
3347 //
3348 const FunctionType *FT = Callee->getFunctionType();
3349 const Type *OldRetTy = Caller->getType();
3350
Chris Lattner1f7942f2004-01-14 06:06:08 +00003351 // Check to see if we are changing the return type...
3352 if (OldRetTy != FT->getReturnType()) {
3353 if (Callee->isExternal() &&
3354 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3355 !Caller->use_empty())
3356 return false; // Cannot transform this return value...
3357
3358 // If the callsite is an invoke instruction, and the return value is used by
3359 // a PHI node in a successor, we cannot change the return type of the call
3360 // because there is no place to put the cast instruction (without breaking
3361 // the critical edge). Bail out in this case.
3362 if (!Caller->use_empty())
3363 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3364 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3365 UI != E; ++UI)
3366 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3367 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003368 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003369 return false;
3370 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003371
3372 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3373 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3374
3375 CallSite::arg_iterator AI = CS.arg_begin();
3376 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3377 const Type *ParamTy = FT->getParamType(i);
3378 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3379 if (Callee->isExternal() && !isConvertible) return false;
3380 }
3381
3382 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3383 Callee->isExternal())
3384 return false; // Do not delete arguments unless we have a function body...
3385
3386 // Okay, we decided that this is a safe thing to do: go ahead and start
3387 // inserting cast instructions as necessary...
3388 std::vector<Value*> Args;
3389 Args.reserve(NumActualArgs);
3390
3391 AI = CS.arg_begin();
3392 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3393 const Type *ParamTy = FT->getParamType(i);
3394 if ((*AI)->getType() == ParamTy) {
3395 Args.push_back(*AI);
3396 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003397 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3398 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003399 }
3400 }
3401
3402 // If the function takes more arguments than the call was taking, add them
3403 // now...
3404 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3405 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3406
3407 // If we are removing arguments to the function, emit an obnoxious warning...
3408 if (FT->getNumParams() < NumActualArgs)
3409 if (!FT->isVarArg()) {
3410 std::cerr << "WARNING: While resolving call to function '"
3411 << Callee->getName() << "' arguments were dropped!\n";
3412 } else {
3413 // Add all of the arguments in their promoted form to the arg list...
3414 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3415 const Type *PTy = getPromotedType((*AI)->getType());
3416 if (PTy != (*AI)->getType()) {
3417 // Must promote to pass through va_arg area!
3418 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3419 InsertNewInstBefore(Cast, *Caller);
3420 Args.push_back(Cast);
3421 } else {
3422 Args.push_back(*AI);
3423 }
3424 }
3425 }
3426
3427 if (FT->getReturnType() == Type::VoidTy)
3428 Caller->setName(""); // Void type should not have a name...
3429
3430 Instruction *NC;
3431 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003432 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003433 Args, Caller->getName(), Caller);
3434 } else {
3435 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3436 }
3437
3438 // Insert a cast of the return type as necessary...
3439 Value *NV = NC;
3440 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3441 if (NV->getType() != Type::VoidTy) {
3442 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003443
3444 // If this is an invoke instruction, we should insert it after the first
3445 // non-phi, instruction in the normal successor block.
3446 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3447 BasicBlock::iterator I = II->getNormalDest()->begin();
3448 while (isa<PHINode>(I)) ++I;
3449 InsertNewInstBefore(NC, *I);
3450 } else {
3451 // Otherwise, it's a call, just insert cast right after the call instr
3452 InsertNewInstBefore(NC, *Caller);
3453 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003454 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003455 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00003456 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00003457 }
3458 }
3459
3460 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3461 Caller->replaceAllUsesWith(NV);
3462 Caller->getParent()->getInstList().erase(Caller);
3463 removeFromWorkList(Caller);
3464 return true;
3465}
3466
3467
Chris Lattner7515cab2004-11-14 19:13:23 +00003468// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
3469// operator and they all are only used by the PHI, PHI together their
3470// inputs, and do the operation once, to the result of the PHI.
3471Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
3472 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
3473
3474 // Scan the instruction, looking for input operations that can be folded away.
3475 // If all input operands to the phi are the same instruction (e.g. a cast from
3476 // the same type or "+42") we can pull the operation through the PHI, reducing
3477 // code size and simplifying code.
3478 Constant *ConstantOp = 0;
3479 const Type *CastSrcTy = 0;
3480 if (isa<CastInst>(FirstInst)) {
3481 CastSrcTy = FirstInst->getOperand(0)->getType();
3482 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
3483 // Can fold binop or shift if the RHS is a constant.
3484 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
3485 if (ConstantOp == 0) return 0;
3486 } else {
3487 return 0; // Cannot fold this operation.
3488 }
3489
3490 // Check to see if all arguments are the same operation.
3491 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3492 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
3493 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
3494 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
3495 return 0;
3496 if (CastSrcTy) {
3497 if (I->getOperand(0)->getType() != CastSrcTy)
3498 return 0; // Cast operation must match.
3499 } else if (I->getOperand(1) != ConstantOp) {
3500 return 0;
3501 }
3502 }
3503
3504 // Okay, they are all the same operation. Create a new PHI node of the
3505 // correct type, and PHI together all of the LHS's of the instructions.
3506 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
3507 PN.getName()+".in");
3508 NewPN->op_reserve(PN.getNumOperands());
Chris Lattner46dd5a62004-11-14 19:29:34 +00003509
3510 Value *InVal = FirstInst->getOperand(0);
3511 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00003512
3513 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00003514 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3515 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
3516 if (NewInVal != InVal)
3517 InVal = 0;
3518 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
3519 }
3520
3521 Value *PhiVal;
3522 if (InVal) {
3523 // The new PHI unions all of the same values together. This is really
3524 // common, so we handle it intelligently here for compile-time speed.
3525 PhiVal = InVal;
3526 delete NewPN;
3527 } else {
3528 InsertNewInstBefore(NewPN, PN);
3529 PhiVal = NewPN;
3530 }
Chris Lattner7515cab2004-11-14 19:13:23 +00003531
3532 // Insert and return the new operation.
3533 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00003534 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00003535 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00003536 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00003537 else
3538 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00003539 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00003540}
Chris Lattner48a44f72002-05-02 17:06:02 +00003541
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003542// PHINode simplification
3543//
Chris Lattner113f4f42002-06-25 16:13:24 +00003544Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00003545 if (Value *V = hasConstantValue(&PN)) {
3546 // If V is an instruction, we have to be certain that it dominates PN.
3547 // However, because we don't have dom info, we can't do a perfect job.
3548 if (Instruction *I = dyn_cast<Instruction>(V)) {
3549 // We know that the instruction dominates the PHI if there are no undef
3550 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00003551 if (I->getParent() != &I->getParent()->getParent()->front() ||
3552 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00003553 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3554 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3555 V = 0;
3556 break;
3557 }
Chris Lattnere29d6342004-10-17 21:22:38 +00003558 }
3559
3560 if (V)
3561 return ReplaceInstUsesWith(PN, V);
3562 }
Chris Lattner4db2d222004-02-16 05:07:08 +00003563
3564 // If the only user of this instruction is a cast instruction, and all of the
3565 // incoming values are constants, change this PHI to merge together the casted
3566 // constants.
3567 if (PN.hasOneUse())
3568 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3569 if (CI->getType() != PN.getType()) { // noop casts will be folded
3570 bool AllConstant = true;
3571 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3572 if (!isa<Constant>(PN.getIncomingValue(i))) {
3573 AllConstant = false;
3574 break;
3575 }
3576 if (AllConstant) {
3577 // Make a new PHI with all casted values.
3578 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3579 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3580 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3581 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3582 PN.getIncomingBlock(i));
3583 }
3584
3585 // Update the cast instruction.
3586 CI->setOperand(0, New);
3587 WorkList.push_back(CI); // revisit the cast instruction to fold.
3588 WorkList.push_back(New); // Make sure to revisit the new Phi
3589 return &PN; // PN is now dead!
3590 }
3591 }
Chris Lattner7515cab2004-11-14 19:13:23 +00003592
3593 // If all PHI operands are the same operation, pull them through the PHI,
3594 // reducing code size.
3595 if (isa<Instruction>(PN.getIncomingValue(0)) &&
3596 PN.getIncomingValue(0)->hasOneUse())
3597 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
3598 return Result;
3599
3600
Chris Lattner91daeb52003-12-19 05:58:40 +00003601 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00003602}
3603
Chris Lattner69193f92004-04-05 01:30:19 +00003604static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3605 Instruction *InsertPoint,
3606 InstCombiner *IC) {
3607 unsigned PS = IC->getTargetData().getPointerSize();
3608 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00003609 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3610 // We must insert a cast to ensure we sign-extend.
3611 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3612 V->getName()), *InsertPoint);
3613 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3614 *InsertPoint);
3615}
3616
Chris Lattner48a44f72002-05-02 17:06:02 +00003617
Chris Lattner113f4f42002-06-25 16:13:24 +00003618Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003619 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00003620 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00003621 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003622 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00003623 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003624
Chris Lattner81a7a232004-10-16 18:11:37 +00003625 if (isa<UndefValue>(GEP.getOperand(0)))
3626 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3627
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003628 bool HasZeroPointerIndex = false;
3629 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3630 HasZeroPointerIndex = C->isNullValue();
3631
3632 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00003633 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00003634
Chris Lattner69193f92004-04-05 01:30:19 +00003635 // Eliminate unneeded casts for indices.
3636 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00003637 gep_type_iterator GTI = gep_type_begin(GEP);
3638 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3639 if (isa<SequentialType>(*GTI)) {
3640 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3641 Value *Src = CI->getOperand(0);
3642 const Type *SrcTy = Src->getType();
3643 const Type *DestTy = CI->getType();
3644 if (Src->getType()->isInteger()) {
3645 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3646 // We can always eliminate a cast from ulong or long to the other.
3647 // We can always eliminate a cast from uint to int or the other on
3648 // 32-bit pointer platforms.
3649 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3650 MadeChange = true;
3651 GEP.setOperand(i, Src);
3652 }
3653 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3654 SrcTy->getPrimitiveSize() == 4) {
3655 // We can always eliminate a cast from int to [u]long. We can
3656 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3657 // pointer target.
3658 if (SrcTy->isSigned() ||
3659 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3660 MadeChange = true;
3661 GEP.setOperand(i, Src);
3662 }
Chris Lattner69193f92004-04-05 01:30:19 +00003663 }
3664 }
3665 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00003666 // If we are using a wider index than needed for this platform, shrink it
3667 // to what we need. If the incoming value needs a cast instruction,
3668 // insert it. This explicit cast can make subsequent optimizations more
3669 // obvious.
3670 Value *Op = GEP.getOperand(i);
3671 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003672 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00003673 GEP.setOperand(i, ConstantExpr::getCast(C,
3674 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00003675 MadeChange = true;
3676 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00003677 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3678 Op->getName()), GEP);
3679 GEP.setOperand(i, Op);
3680 MadeChange = true;
3681 }
Chris Lattner44d0b952004-07-20 01:48:15 +00003682
3683 // If this is a constant idx, make sure to canonicalize it to be a signed
3684 // operand, otherwise CSE and other optimizations are pessimized.
3685 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3686 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3687 CUI->getType()->getSignedVersion()));
3688 MadeChange = true;
3689 }
Chris Lattner69193f92004-04-05 01:30:19 +00003690 }
3691 if (MadeChange) return &GEP;
3692
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003693 // Combine Indices - If the source pointer to this getelementptr instruction
3694 // is a getelementptr instruction, combine the indices of the two
3695 // getelementptr instructions into a single instruction.
3696 //
Chris Lattner57c67b02004-03-25 22:59:29 +00003697 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00003698 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003699 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00003700 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00003701 if (CE->getOpcode() == Instruction::GetElementPtr)
3702 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3703 }
3704
3705 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00003706 // Note that if our source is a gep chain itself that we wait for that
3707 // chain to be resolved before we perform this transformation. This
3708 // avoids us creating a TON of code in some cases.
3709 //
3710 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3711 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3712 return 0; // Wait until our source is folded to completion.
3713
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003714 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00003715
3716 // Find out whether the last index in the source GEP is a sequential idx.
3717 bool EndsWithSequential = false;
3718 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3719 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00003720 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00003721
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003722 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00003723 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00003724 // Replace: gep (gep %P, long B), long A, ...
3725 // With: T = long A+B; gep %P, T, ...
3726 //
Chris Lattner5f667a62004-05-07 22:09:22 +00003727 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00003728 if (SO1 == Constant::getNullValue(SO1->getType())) {
3729 Sum = GO1;
3730 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3731 Sum = SO1;
3732 } else {
3733 // If they aren't the same type, convert both to an integer of the
3734 // target's pointer size.
3735 if (SO1->getType() != GO1->getType()) {
3736 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3737 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3738 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3739 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3740 } else {
3741 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00003742 if (SO1->getType()->getPrimitiveSize() == PS) {
3743 // Convert GO1 to SO1's type.
3744 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3745
3746 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3747 // Convert SO1 to GO1's type.
3748 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3749 } else {
3750 const Type *PT = TD->getIntPtrType();
3751 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3752 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3753 }
3754 }
3755 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003756 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3757 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3758 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003759 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3760 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00003761 }
Chris Lattner69193f92004-04-05 01:30:19 +00003762 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003763
3764 // Recycle the GEP we already have if possible.
3765 if (SrcGEPOperands.size() == 2) {
3766 GEP.setOperand(0, SrcGEPOperands[0]);
3767 GEP.setOperand(1, Sum);
3768 return &GEP;
3769 } else {
3770 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3771 SrcGEPOperands.end()-1);
3772 Indices.push_back(Sum);
3773 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3774 }
Chris Lattner69193f92004-04-05 01:30:19 +00003775 } else if (isa<Constant>(*GEP.idx_begin()) &&
3776 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00003777 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003778 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00003779 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3780 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003781 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3782 }
3783
3784 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00003785 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003786
Chris Lattner5f667a62004-05-07 22:09:22 +00003787 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003788 // GEP of global variable. If all of the indices for this GEP are
3789 // constants, we can promote this to a constexpr instead of an instruction.
3790
3791 // Scan for nonconstants...
3792 std::vector<Constant*> Indices;
3793 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3794 for (; I != E && isa<Constant>(*I); ++I)
3795 Indices.push_back(cast<Constant>(*I));
3796
3797 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00003798 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00003799
3800 // Replace all uses of the GEP with the new constexpr...
3801 return ReplaceInstUsesWith(GEP, CE);
3802 }
Chris Lattner5f667a62004-05-07 22:09:22 +00003803 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003804 if (CE->getOpcode() == Instruction::Cast) {
3805 if (HasZeroPointerIndex) {
3806 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3807 // into : GEP [10 x ubyte]* X, long 0, ...
3808 //
3809 // This occurs when the program declares an array extern like "int X[];"
3810 //
3811 Constant *X = CE->getOperand(0);
3812 const PointerType *CPTy = cast<PointerType>(CE->getType());
3813 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3814 if (const ArrayType *XATy =
3815 dyn_cast<ArrayType>(XTy->getElementType()))
3816 if (const ArrayType *CATy =
3817 dyn_cast<ArrayType>(CPTy->getElementType()))
3818 if (CATy->getElementType() == XATy->getElementType()) {
3819 // At this point, we know that the cast source type is a pointer
3820 // to an array of the same type as the destination pointer
3821 // array. Because the array type is never stepped over (there
3822 // is a leading zero) we can fold the cast into this GEP.
3823 GEP.setOperand(0, X);
3824 return &GEP;
3825 }
Chris Lattner14f3cdc2004-11-27 17:55:46 +00003826 } else if (GEP.getNumOperands() == 2) {
3827 // Transform things like:
3828 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
3829 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
3830 Constant *X = CE->getOperand(0);
3831 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
3832 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
3833 if (isa<ArrayType>(SrcElTy) &&
3834 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
3835 TD->getTypeSize(ResElTy)) {
3836 Value *V = InsertNewInstBefore(
3837 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
3838 GEP.getOperand(1), GEP.getName()), GEP);
3839 return new CastInst(V, GEP.getType());
3840 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00003841 }
3842 }
Chris Lattnerca081252001-12-14 16:52:21 +00003843 }
3844
Chris Lattnerca081252001-12-14 16:52:21 +00003845 return 0;
3846}
3847
Chris Lattner1085bdf2002-11-04 16:18:53 +00003848Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3849 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3850 if (AI.isArrayAllocation()) // Check C != 1
3851 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3852 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003853 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003854
3855 // Create and insert the replacement instruction...
3856 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003857 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003858 else {
3859 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003860 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003861 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003862
3863 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003864
3865 // Scan to the end of the allocation instructions, to skip over a block of
3866 // allocas if possible...
3867 //
3868 BasicBlock::iterator It = New;
3869 while (isa<AllocationInst>(*It)) ++It;
3870
3871 // Now that I is pointing to the first non-allocation-inst in the block,
3872 // insert our getelementptr instruction...
3873 //
Chris Lattner69193f92004-04-05 01:30:19 +00003874 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003875 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3876
3877 // Now make everything use the getelementptr instead of the original
3878 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003879 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00003880 } else if (isa<UndefValue>(AI.getArraySize())) {
3881 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003882 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003883
3884 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3885 // Note that we only do this for alloca's, because malloc should allocate and
3886 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003887 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3888 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003889 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3890
Chris Lattner1085bdf2002-11-04 16:18:53 +00003891 return 0;
3892}
3893
Chris Lattner8427bff2003-12-07 01:24:23 +00003894Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3895 Value *Op = FI.getOperand(0);
3896
3897 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3898 if (CastInst *CI = dyn_cast<CastInst>(Op))
3899 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3900 FI.setOperand(0, CI->getOperand(0));
3901 return &FI;
3902 }
3903
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003904 // free undef -> unreachable.
3905 if (isa<UndefValue>(Op)) {
3906 // Insert a new store to null because we cannot modify the CFG here.
3907 new StoreInst(ConstantBool::True,
3908 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3909 return EraseInstFromFunction(FI);
3910 }
3911
Chris Lattnerf3a36602004-02-28 04:57:37 +00003912 // If we have 'free null' delete the instruction. This can happen in stl code
3913 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003914 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00003915 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003916
Chris Lattner8427bff2003-12-07 01:24:23 +00003917 return 0;
3918}
3919
3920
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003921/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3922/// constantexpr, return the constant value being addressed by the constant
3923/// expression, or null if something is funny.
3924///
3925static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003926 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003927 return 0; // Do not allow stepping over the value!
3928
3929 // Loop over all of the operands, tracking down which value we are
3930 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003931 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3932 for (++I; I != E; ++I)
3933 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3934 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3935 assert(CU->getValue() < STy->getNumElements() &&
3936 "Struct index out of range!");
3937 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003938 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003939 } else if (isa<ConstantAggregateZero>(C)) {
3940 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
Chris Lattner81a7a232004-10-16 18:11:37 +00003941 } else if (isa<UndefValue>(C)) {
3942 C = UndefValue::get(STy->getElementType(CU->getValue()));
Chris Lattnered79d8a2004-05-27 17:30:27 +00003943 } else {
3944 return 0;
3945 }
3946 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3947 const ArrayType *ATy = cast<ArrayType>(*I);
3948 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3949 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003950 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003951 else if (isa<ConstantAggregateZero>(C))
3952 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00003953 else if (isa<UndefValue>(C))
3954 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003955 else
3956 return 0;
3957 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003958 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003959 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003960 return C;
3961}
3962
Chris Lattner35e24772004-07-13 01:49:43 +00003963static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3964 User *CI = cast<User>(LI.getOperand(0));
3965
3966 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3967 if (const PointerType *SrcTy =
3968 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3969 const Type *SrcPTy = SrcTy->getElementType();
3970 if (SrcPTy->isSized() && DestPTy->isSized() &&
3971 IC.getTargetData().getTypeSize(SrcPTy) ==
3972 IC.getTargetData().getTypeSize(DestPTy) &&
3973 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3974 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3975 // Okay, we are casting from one integer or pointer type to another of
3976 // the same size. Instead of casting the pointer before the load, cast
3977 // the result of the loaded value.
3978 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003979 CI->getName(),
3980 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003981 // Now cast the result of the load.
3982 return new CastInst(NewLoad, LI.getType());
3983 }
3984 }
3985 return 0;
3986}
3987
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003988/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003989/// from this value cannot trap. If it is not obviously safe to load from the
3990/// specified pointer, we do a quick local scan of the basic block containing
3991/// ScanFrom, to determine if the address is already accessed.
3992static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3993 // If it is an alloca or global variable, it is always safe to load from.
3994 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3995
3996 // Otherwise, be a little bit agressive by scanning the local block where we
3997 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003998 // from/to. If so, the previous load or store would have already trapped,
3999 // so there is no harm doing an extra load (also, CSE will later eliminate
4000 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004001 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4002
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004003 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004004 --BBI;
4005
4006 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4007 if (LI->getOperand(0) == V) return true;
4008 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4009 if (SI->getOperand(1) == V) return true;
4010
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004011 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004012 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004013}
4014
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004015Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4016 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004017
Chris Lattner81a7a232004-10-16 18:11:37 +00004018 if (Constant *C = dyn_cast<Constant>(Op)) {
4019 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004020 !LI.isVolatile()) { // load null/undef -> undef
4021 // Insert a new store to null instruction before the load to indicate that
4022 // this code is not reachable. We do this instead of inserting an
4023 // unreachable instruction directly because we cannot modify the CFG.
4024 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004025 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004026 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004027
Chris Lattner81a7a232004-10-16 18:11:37 +00004028 // Instcombine load (constant global) into the value loaded.
4029 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4030 if (GV->isConstant() && !GV->isExternal())
4031 return ReplaceInstUsesWith(LI, GV->getInitializer());
4032
4033 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4034 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4035 if (CE->getOpcode() == Instruction::GetElementPtr) {
4036 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4037 if (GV->isConstant() && !GV->isExternal())
4038 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4039 return ReplaceInstUsesWith(LI, V);
4040 } else if (CE->getOpcode() == Instruction::Cast) {
4041 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4042 return Res;
4043 }
4044 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004045
4046 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004047 if (CastInst *CI = dyn_cast<CastInst>(Op))
4048 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4049 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004050
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004051 if (!LI.isVolatile() && Op->hasOneUse()) {
4052 // Change select and PHI nodes to select values instead of addresses: this
4053 // helps alias analysis out a lot, allows many others simplifications, and
4054 // exposes redundancy in the code.
4055 //
4056 // Note that we cannot do the transformation unless we know that the
4057 // introduced loads cannot trap! Something like this is valid as long as
4058 // the condition is always false: load (select bool %C, int* null, int* %G),
4059 // but it would not be valid if we transformed it to load from null
4060 // unconditionally.
4061 //
4062 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4063 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004064 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4065 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004066 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004067 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004068 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004069 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004070 return new SelectInst(SI->getCondition(), V1, V2);
4071 }
4072
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004073 // load (select (cond, null, P)) -> load P
4074 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4075 if (C->isNullValue()) {
4076 LI.setOperand(0, SI->getOperand(2));
4077 return &LI;
4078 }
4079
4080 // load (select (cond, P, null)) -> load P
4081 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4082 if (C->isNullValue()) {
4083 LI.setOperand(0, SI->getOperand(1));
4084 return &LI;
4085 }
4086
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004087 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4088 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004089 bool Safe = PN->getParent() == LI.getParent();
4090
4091 // Scan all of the instructions between the PHI and the load to make
4092 // sure there are no instructions that might possibly alter the value
4093 // loaded from the PHI.
4094 if (Safe) {
4095 BasicBlock::iterator I = &LI;
4096 for (--I; !isa<PHINode>(I); --I)
4097 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4098 Safe = false;
4099 break;
4100 }
4101 }
4102
4103 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004104 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004105 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004106 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004107
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004108 if (Safe) {
4109 // Create the PHI.
4110 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4111 InsertNewInstBefore(NewPN, *PN);
4112 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4113
4114 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4115 BasicBlock *BB = PN->getIncomingBlock(i);
4116 Value *&TheLoad = LoadMap[BB];
4117 if (TheLoad == 0) {
4118 Value *InVal = PN->getIncomingValue(i);
4119 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4120 InVal->getName()+".val"),
4121 *BB->getTerminator());
4122 }
4123 NewPN->addIncoming(TheLoad, BB);
4124 }
4125 return ReplaceInstUsesWith(LI, NewPN);
4126 }
4127 }
4128 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004129 return 0;
4130}
4131
Chris Lattner9eef8a72003-06-04 04:46:00 +00004132Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4133 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004134 Value *X;
4135 BasicBlock *TrueDest;
4136 BasicBlock *FalseDest;
4137 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4138 !isa<Constant>(X)) {
4139 // Swap Destinations and condition...
4140 BI.setCondition(X);
4141 BI.setSuccessor(0, FalseDest);
4142 BI.setSuccessor(1, TrueDest);
4143 return &BI;
4144 }
4145
4146 // Cannonicalize setne -> seteq
4147 Instruction::BinaryOps Op; Value *Y;
4148 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4149 TrueDest, FalseDest)))
4150 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4151 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4152 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4153 std::string Name = I->getName(); I->setName("");
4154 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4155 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004156 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004157 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004158 BI.setSuccessor(0, FalseDest);
4159 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004160 removeFromWorkList(I);
4161 I->getParent()->getInstList().erase(I);
4162 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004163 return &BI;
4164 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004165
Chris Lattner9eef8a72003-06-04 04:46:00 +00004166 return 0;
4167}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004168
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004169Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4170 Value *Cond = SI.getCondition();
4171 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4172 if (I->getOpcode() == Instruction::Add)
4173 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4174 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4175 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004176 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004177 AddRHS));
4178 SI.setOperand(0, I->getOperand(0));
4179 WorkList.push_back(I);
4180 return &SI;
4181 }
4182 }
4183 return 0;
4184}
4185
Chris Lattnerca081252001-12-14 16:52:21 +00004186
Chris Lattner99f48c62002-09-02 04:59:56 +00004187void InstCombiner::removeFromWorkList(Instruction *I) {
4188 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4189 WorkList.end());
4190}
4191
Chris Lattner113f4f42002-06-25 16:13:24 +00004192bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004193 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004194 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004195
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004196 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4197 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004198
Chris Lattnerca081252001-12-14 16:52:21 +00004199
4200 while (!WorkList.empty()) {
4201 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4202 WorkList.pop_back();
4203
Misha Brukman632df282002-10-29 23:06:16 +00004204 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004205 // Check to see if we can DIE the instruction...
4206 if (isInstructionTriviallyDead(I)) {
4207 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004208 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004209 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004210 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004211
4212 I->getParent()->getInstList().erase(I);
4213 removeFromWorkList(I);
4214 continue;
4215 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004216
Misha Brukman632df282002-10-29 23:06:16 +00004217 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004218 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner6580e092004-10-16 19:44:59 +00004219 if (isa<GetElementPtrInst>(I) &&
4220 cast<Constant>(I->getOperand(0))->isNullValue() &&
4221 !isa<ConstantPointerNull>(C)) {
4222 // If this is a constant expr gep that is effectively computing an
4223 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4224 bool isFoldableGEP = true;
4225 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4226 if (!isa<ConstantInt>(I->getOperand(i)))
4227 isFoldableGEP = false;
4228 if (isFoldableGEP) {
4229 uint64_t Offset = TD->getIndexedOffset(I->getOperand(0)->getType(),
4230 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4231 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004232 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004233 C = ConstantExpr::getCast(C, I->getType());
4234 }
4235 }
4236
Chris Lattner99f48c62002-09-02 04:59:56 +00004237 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004238 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004239 ReplaceInstUsesWith(*I, C);
4240
Chris Lattner99f48c62002-09-02 04:59:56 +00004241 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004242 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004243 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004244 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004245 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004246
Chris Lattnerca081252001-12-14 16:52:21 +00004247 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004248 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004249 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004250 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004251 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004252 DEBUG(std::cerr << "IC: Old = " << *I
4253 << " New = " << *Result);
4254
Chris Lattner396dbfe2004-06-09 05:08:07 +00004255 // Everything uses the new instruction now.
4256 I->replaceAllUsesWith(Result);
4257
4258 // Push the new instruction and any users onto the worklist.
4259 WorkList.push_back(Result);
4260 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004261
4262 // Move the name to the new instruction first...
4263 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004264 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004265
4266 // Insert the new instruction into the basic block...
4267 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00004268 BasicBlock::iterator InsertPos = I;
4269
4270 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4271 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4272 ++InsertPos;
4273
4274 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004275
Chris Lattner63d75af2004-05-01 23:27:23 +00004276 // Make sure that we reprocess all operands now that we reduced their
4277 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004278 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4279 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4280 WorkList.push_back(OpI);
4281
Chris Lattner396dbfe2004-06-09 05:08:07 +00004282 // Instructions can end up on the worklist more than once. Make sure
4283 // we do not process an instruction that has been deleted.
4284 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004285
4286 // Erase the old instruction.
4287 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004288 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004289 DEBUG(std::cerr << "IC: MOD = " << *I);
4290
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004291 // If the instruction was modified, it's possible that it is now dead.
4292 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004293 if (isInstructionTriviallyDead(I)) {
4294 // Make sure we process all operands now that we are reducing their
4295 // use counts.
4296 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4297 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4298 WorkList.push_back(OpI);
4299
4300 // Instructions may end up in the worklist more than once. Erase all
4301 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004302 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004303 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004304 } else {
4305 WorkList.push_back(Result);
4306 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004307 }
Chris Lattner053c0932002-05-14 15:24:07 +00004308 }
Chris Lattner260ab202002-04-18 17:39:14 +00004309 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004310 }
4311 }
4312
Chris Lattner260ab202002-04-18 17:39:14 +00004313 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004314}
4315
Brian Gaeke38b79e82004-07-27 17:43:21 +00004316FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00004317 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00004318}
Brian Gaeke960707c2003-11-11 22:41:34 +00004319