blob: a65b834495478648733f4b6a52924251f1b7167e [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattner7515cab2004-11-14 19:13:23 +000032// ... etc.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000033//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner00648e12004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000048#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000049#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattner39c98bb2004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattner053c0932002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000054using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000055using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000056
Chris Lattner260ab202002-04-18 17:39:14 +000057namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000058 Statistic<> NumCombined ("instcombine", "Number of insts combined");
59 Statistic<> NumConstProp("instcombine", "Number of constant folds");
60 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner39c98bb2004-12-08 23:43:58 +000061 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnerbf3a0992002-10-01 22:38:41 +000062
Chris Lattnerc8e66542002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000068
Chris Lattner51ea1272004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner51ea1272004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner99f48c62002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000090 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000092
Chris Lattnerf12cc842002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 }
97
Chris Lattner69193f92004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattner260ab202002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Reid Spencer279fa252004-11-28 21:31:15 +0000116 Instruction *visitSetCondInstWithCastAndConstant(BinaryOperator&I,
117 CastInst*LHSI,
118 ConstantInt* CI);
Chris Lattner0798af32005-01-13 20:14:25 +0000119 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000121 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000122 Instruction *visitCastInst(CastInst &CI);
Chris Lattner411336f2005-01-19 21:50:18 +0000123 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124 Instruction *FI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000125 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000126 Instruction *visitCallInst(CallInst &CI);
127 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000128 Instruction *visitPHINode(PHINode &PN);
129 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000130 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000131 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000132 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000133 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000134 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000135
136 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000137 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000138
Chris Lattner970c33a2003-06-19 17:00:31 +0000139 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000140 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000141 bool transformConstExprCastCall(CallSite CS);
142
Chris Lattner69193f92004-04-05 01:30:19 +0000143 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000144 // InsertNewInstBefore - insert an instruction New before instruction Old
145 // in the program. Add the new instruction to the worklist.
146 //
Chris Lattner623826c2004-09-28 21:48:02 +0000147 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000148 assert(New && New->getParent() == 0 &&
149 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000150 BasicBlock *BB = Old.getParent();
151 BB->getInstList().insert(&Old, New); // Insert inst
152 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000153 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000154 }
155
Chris Lattner7e794272004-09-24 15:21:34 +0000156 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
157 /// This also adds the cast to the worklist. Finally, this returns the
158 /// cast.
159 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
160 if (V->getType() == Ty) return V;
161
162 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
163 WorkList.push_back(C);
164 return C;
165 }
166
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000167 // ReplaceInstUsesWith - This method is to be used when an instruction is
168 // found to be dead, replacable with another preexisting expression. Here
169 // we add all uses of I to the worklist, replace all uses of I with the new
170 // value, then return I, so that the inst combiner will know that I was
171 // modified.
172 //
173 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000174 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000175 if (&I != V) {
176 I.replaceAllUsesWith(V);
177 return &I;
178 } else {
179 // If we are replacing the instruction with itself, this must be in a
180 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000181 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000182 return &I;
183 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000184 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000185
186 // EraseInstFromFunction - When dealing with an instruction that has side
187 // effects or produces a void value, we can't rely on DCE to delete the
188 // instruction. Instead, visit methods should return the value returned by
189 // this function.
190 Instruction *EraseInstFromFunction(Instruction &I) {
191 assert(I.use_empty() && "Cannot erase instruction that is used!");
192 AddUsesToWorkList(I);
193 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000194 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000195 return 0; // Don't do anything with FI
196 }
197
198
Chris Lattner3ac7c262003-08-13 20:16:26 +0000199 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000200 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
201 /// InsertBefore instruction. This is specialized a bit to avoid inserting
202 /// casts that are known to not do anything...
203 ///
204 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
205 Instruction *InsertBefore);
206
Chris Lattner7fb29e12003-03-11 00:12:48 +0000207 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000208 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000209 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000210
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000211
212 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
213 // PHI node as operand #0, see if we can fold the instruction into the PHI
214 // (which is only possible if all operands to the PHI are constants).
215 Instruction *FoldOpIntoPhi(Instruction &I);
216
Chris Lattner7515cab2004-11-14 19:13:23 +0000217 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
218 // operator and they all are only used by the PHI, PHI together their
219 // inputs, and do the operation once, to the result of the PHI.
220 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
221
Chris Lattnerba1cb382003-09-19 17:17:26 +0000222 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
223 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000224
225 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
226 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000227 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000228
Chris Lattnerc8b70922002-07-26 21:12:46 +0000229 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000230}
231
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000232// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000233// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000234static unsigned getComplexity(Value *V) {
235 if (isa<Instruction>(V)) {
236 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000237 return 3;
238 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000239 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000240 if (isa<Argument>(V)) return 3;
241 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000242}
Chris Lattner260ab202002-04-18 17:39:14 +0000243
Chris Lattner7fb29e12003-03-11 00:12:48 +0000244// isOnlyUse - Return true if this instruction will be deleted if we stop using
245// it.
246static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000247 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000248}
249
Chris Lattnere79e8542004-02-23 06:38:22 +0000250// getPromotedType - Return the specified type promoted as it would be to pass
251// though a va_arg area...
252static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000253 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000254 case Type::SByteTyID:
255 case Type::ShortTyID: return Type::IntTy;
256 case Type::UByteTyID:
257 case Type::UShortTyID: return Type::UIntTy;
258 case Type::FloatTyID: return Type::DoubleTy;
259 default: return Ty;
260 }
261}
262
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000263// SimplifyCommutative - This performs a few simplifications for commutative
264// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000265//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000266// 1. Order operands such that they are listed from right (least complex) to
267// left (most complex). This puts constants before unary operators before
268// binary operators.
269//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000270// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
271// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000273bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000274 bool Changed = false;
275 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
276 Changed = !I.swapOperands();
277
278 if (!I.isAssociative()) return Changed;
279 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000280 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
281 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
282 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000283 Constant *Folded = ConstantExpr::get(I.getOpcode(),
284 cast<Constant>(I.getOperand(1)),
285 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000286 I.setOperand(0, Op->getOperand(0));
287 I.setOperand(1, Folded);
288 return true;
289 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
290 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
291 isOnlyUse(Op) && isOnlyUse(Op1)) {
292 Constant *C1 = cast<Constant>(Op->getOperand(1));
293 Constant *C2 = cast<Constant>(Op1->getOperand(1));
294
295 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000296 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000297 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
298 Op1->getOperand(0),
299 Op1->getName(), &I);
300 WorkList.push_back(New);
301 I.setOperand(0, New);
302 I.setOperand(1, Folded);
303 return true;
304 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000305 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000306 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000307}
Chris Lattnerca081252001-12-14 16:52:21 +0000308
Chris Lattnerbb74e222003-03-10 23:06:50 +0000309// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
310// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000311//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000312static inline Value *dyn_castNegVal(Value *V) {
313 if (BinaryOperator::isNeg(V))
314 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
315
Chris Lattner9ad0d552004-12-14 20:08:06 +0000316 // Constants can be considered to be negated values if they can be folded.
317 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
318 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000319 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000320}
321
Chris Lattnerbb74e222003-03-10 23:06:50 +0000322static inline Value *dyn_castNotVal(Value *V) {
323 if (BinaryOperator::isNot(V))
324 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
325
326 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000327 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000328 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000329 return 0;
330}
331
Chris Lattner7fb29e12003-03-11 00:12:48 +0000332// dyn_castFoldableMul - If this value is a multiply that can be folded into
333// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000334// non-constant operand of the multiply, and set CST to point to the multiplier.
335// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000336//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000337static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000338 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000339 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000340 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000341 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000342 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000343 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000344 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000345 // The multiplier is really 1 << CST.
346 Constant *One = ConstantInt::get(V->getType(), 1);
347 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
348 return I->getOperand(0);
349 }
350 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000351 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000352}
Chris Lattner31ae8632002-08-14 17:51:49 +0000353
Chris Lattner0798af32005-01-13 20:14:25 +0000354/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
355/// expression, return it.
356static User *dyn_castGetElementPtr(Value *V) {
357 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
358 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
359 if (CE->getOpcode() == Instruction::GetElementPtr)
360 return cast<User>(V);
361 return false;
362}
363
Chris Lattner3082c5a2003-02-18 19:28:33 +0000364// Log2 - Calculate the log base 2 for the specified value if it is exactly a
365// power of 2.
366static unsigned Log2(uint64_t Val) {
367 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
368 unsigned Count = 0;
369 while (Val != 1) {
370 if (Val & 1) return 0; // Multiple bits set?
371 Val >>= 1;
372 ++Count;
373 }
374 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000375}
376
Chris Lattner623826c2004-09-28 21:48:02 +0000377// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000378static ConstantInt *AddOne(ConstantInt *C) {
379 return cast<ConstantInt>(ConstantExpr::getAdd(C,
380 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000381}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000382static ConstantInt *SubOne(ConstantInt *C) {
383 return cast<ConstantInt>(ConstantExpr::getSub(C,
384 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000385}
386
387// isTrueWhenEqual - Return true if the specified setcondinst instruction is
388// true when both operands are equal...
389//
390static bool isTrueWhenEqual(Instruction &I) {
391 return I.getOpcode() == Instruction::SetEQ ||
392 I.getOpcode() == Instruction::SetGE ||
393 I.getOpcode() == Instruction::SetLE;
394}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000395
396/// AssociativeOpt - Perform an optimization on an associative operator. This
397/// function is designed to check a chain of associative operators for a
398/// potential to apply a certain optimization. Since the optimization may be
399/// applicable if the expression was reassociated, this checks the chain, then
400/// reassociates the expression as necessary to expose the optimization
401/// opportunity. This makes use of a special Functor, which must define
402/// 'shouldApply' and 'apply' methods.
403///
404template<typename Functor>
405Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
406 unsigned Opcode = Root.getOpcode();
407 Value *LHS = Root.getOperand(0);
408
409 // Quick check, see if the immediate LHS matches...
410 if (F.shouldApply(LHS))
411 return F.apply(Root);
412
413 // Otherwise, if the LHS is not of the same opcode as the root, return.
414 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000415 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000416 // Should we apply this transform to the RHS?
417 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
418
419 // If not to the RHS, check to see if we should apply to the LHS...
420 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
421 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
422 ShouldApply = true;
423 }
424
425 // If the functor wants to apply the optimization to the RHS of LHSI,
426 // reassociate the expression from ((? op A) op B) to (? op (A op B))
427 if (ShouldApply) {
428 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000429
430 // Now all of the instructions are in the current basic block, go ahead
431 // and perform the reassociation.
432 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
433
434 // First move the selected RHS to the LHS of the root...
435 Root.setOperand(0, LHSI->getOperand(1));
436
437 // Make what used to be the LHS of the root be the user of the root...
438 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000439 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000440 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
441 return 0;
442 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000443 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000444 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000445 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
446 BasicBlock::iterator ARI = &Root; ++ARI;
447 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
448 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000449
450 // Now propagate the ExtraOperand down the chain of instructions until we
451 // get to LHSI.
452 while (TmpLHSI != LHSI) {
453 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000454 // Move the instruction to immediately before the chain we are
455 // constructing to avoid breaking dominance properties.
456 NextLHSI->getParent()->getInstList().remove(NextLHSI);
457 BB->getInstList().insert(ARI, NextLHSI);
458 ARI = NextLHSI;
459
Chris Lattnerb8b97502003-08-13 19:01:45 +0000460 Value *NextOp = NextLHSI->getOperand(1);
461 NextLHSI->setOperand(1, ExtraOperand);
462 TmpLHSI = NextLHSI;
463 ExtraOperand = NextOp;
464 }
465
466 // Now that the instructions are reassociated, have the functor perform
467 // the transformation...
468 return F.apply(Root);
469 }
470
471 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
472 }
473 return 0;
474}
475
476
477// AddRHS - Implements: X + X --> X << 1
478struct AddRHS {
479 Value *RHS;
480 AddRHS(Value *rhs) : RHS(rhs) {}
481 bool shouldApply(Value *LHS) const { return LHS == RHS; }
482 Instruction *apply(BinaryOperator &Add) const {
483 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
484 ConstantInt::get(Type::UByteTy, 1));
485 }
486};
487
488// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
489// iff C1&C2 == 0
490struct AddMaskingAnd {
491 Constant *C2;
492 AddMaskingAnd(Constant *c) : C2(c) {}
493 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000494 ConstantInt *C1;
495 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
496 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000497 }
498 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000499 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000500 }
501};
502
Chris Lattner86102b82005-01-01 16:22:27 +0000503static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000504 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000505 if (isa<CastInst>(I)) {
506 if (Constant *SOC = dyn_cast<Constant>(SO))
507 return ConstantExpr::getCast(SOC, I.getType());
508
509 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
510 SO->getName() + ".cast"), I);
511 }
512
Chris Lattner183b3362004-04-09 19:05:30 +0000513 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000514 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
515 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000516
Chris Lattner183b3362004-04-09 19:05:30 +0000517 if (Constant *SOC = dyn_cast<Constant>(SO)) {
518 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000519 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
520 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000521 }
522
523 Value *Op0 = SO, *Op1 = ConstOperand;
524 if (!ConstIsRHS)
525 std::swap(Op0, Op1);
526 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
528 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
529 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
530 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000531 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000532 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000533 abort();
534 }
Chris Lattner86102b82005-01-01 16:22:27 +0000535 return IC->InsertNewInstBefore(New, I);
536}
537
538// FoldOpIntoSelect - Given an instruction with a select as one operand and a
539// constant as the other operand, try to fold the binary operator into the
540// select arguments. This also works for Cast instructions, which obviously do
541// not have a second operand.
542static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
543 InstCombiner *IC) {
544 // Don't modify shared select instructions
545 if (!SI->hasOneUse()) return 0;
546 Value *TV = SI->getOperand(1);
547 Value *FV = SI->getOperand(2);
548
549 if (isa<Constant>(TV) || isa<Constant>(FV)) {
550 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
551 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
552
553 return new SelectInst(SI->getCondition(), SelectTrueVal,
554 SelectFalseVal);
555 }
556 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000557}
558
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000559
560/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
561/// node as operand #0, see if we can fold the instruction into the PHI (which
562/// is only possible if all operands to the PHI are constants).
563Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
564 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000565 unsigned NumPHIValues = PN->getNumIncomingValues();
566 if (!PN->hasOneUse() || NumPHIValues == 0 ||
567 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000568
569 // Check to see if all of the operands of the PHI are constants. If not, we
570 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000571 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000572 if (!isa<Constant>(PN->getIncomingValue(i)))
573 return 0;
574
575 // Okay, we can do the transformation: create the new PHI node.
576 PHINode *NewPN = new PHINode(I.getType(), I.getName());
577 I.setName("");
Chris Lattnerd8e20182005-01-29 00:39:08 +0000578 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000579 InsertNewInstBefore(NewPN, *PN);
580
581 // Next, add all of the operands to the PHI.
582 if (I.getNumOperands() == 2) {
583 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000584 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000585 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
586 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
587 PN->getIncomingBlock(i));
588 }
589 } else {
590 assert(isa<CastInst>(I) && "Unary op should be a cast!");
591 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000592 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000593 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
594 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
595 PN->getIncomingBlock(i));
596 }
597 }
598 return ReplaceInstUsesWith(I, NewPN);
599}
600
Chris Lattner113f4f42002-06-25 16:13:24 +0000601Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000602 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000603 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000604
Chris Lattnercf4a9962004-04-10 22:01:55 +0000605 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000606 // X + undef -> undef
607 if (isa<UndefValue>(RHS))
608 return ReplaceInstUsesWith(I, RHS);
609
Chris Lattnercf4a9962004-04-10 22:01:55 +0000610 // X + 0 --> X
611 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
612 RHSC->isNullValue())
613 return ReplaceInstUsesWith(I, LHS);
614
615 // X + (signbit) --> X ^ signbit
616 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
617 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
618 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000619 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000620 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000621 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000622
623 if (isa<PHINode>(LHS))
624 if (Instruction *NV = FoldOpIntoPhi(I))
625 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000626 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000627
Chris Lattnerb8b97502003-08-13 19:01:45 +0000628 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000629 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000630 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000631 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000632
Chris Lattner147e9752002-05-08 22:46:53 +0000633 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000634 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000635 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000636
637 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000638 if (!isa<Constant>(RHS))
639 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000640 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000641
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000642 ConstantInt *C2;
643 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
644 if (X == RHS) // X*C + X --> X * (C+1)
645 return BinaryOperator::createMul(RHS, AddOne(C2));
646
647 // X*C1 + X*C2 --> X * (C1+C2)
648 ConstantInt *C1;
649 if (X == dyn_castFoldableMul(RHS, C1))
650 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000651 }
652
653 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000654 if (dyn_castFoldableMul(RHS, C2) == LHS)
655 return BinaryOperator::createMul(LHS, AddOne(C2));
656
Chris Lattner57c8d992003-02-18 19:57:07 +0000657
Chris Lattnerb8b97502003-08-13 19:01:45 +0000658 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000659 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000660 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000661
Chris Lattnerb9cde762003-10-02 15:11:26 +0000662 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000663 Value *X;
664 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
665 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
666 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000667 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000668
Chris Lattnerbff91d92004-10-08 05:07:56 +0000669 // (X & FF00) + xx00 -> (X+xx00) & FF00
670 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
671 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
672 if (Anded == CRHS) {
673 // See if all bits from the first bit set in the Add RHS up are included
674 // in the mask. First, get the rightmost bit.
675 uint64_t AddRHSV = CRHS->getRawValue();
676
677 // Form a mask of all bits from the lowest bit added through the top.
678 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
679 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
680
681 // See if the and mask includes all of these bits.
682 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
683
684 if (AddRHSHighBits == AddRHSHighBitsAnd) {
685 // Okay, the xform is safe. Insert the new add pronto.
686 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
687 LHS->getName()), I);
688 return BinaryOperator::createAnd(NewAdd, C2);
689 }
690 }
691 }
692
Chris Lattnerd4252a72004-07-30 07:50:03 +0000693 // Try to fold constant add into select arguments.
694 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000695 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000696 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000697 }
698
Chris Lattner113f4f42002-06-25 16:13:24 +0000699 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000700}
701
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000702// isSignBit - Return true if the value represented by the constant only has the
703// highest order bit set.
704static bool isSignBit(ConstantInt *CI) {
705 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
706 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
707}
708
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000709static unsigned getTypeSizeInBits(const Type *Ty) {
710 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
711}
712
Chris Lattner022167f2004-03-13 00:11:49 +0000713/// RemoveNoopCast - Strip off nonconverting casts from the value.
714///
715static Value *RemoveNoopCast(Value *V) {
716 if (CastInst *CI = dyn_cast<CastInst>(V)) {
717 const Type *CTy = CI->getType();
718 const Type *OpTy = CI->getOperand(0)->getType();
719 if (CTy->isInteger() && OpTy->isInteger()) {
720 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
721 return RemoveNoopCast(CI->getOperand(0));
722 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
723 return RemoveNoopCast(CI->getOperand(0));
724 }
725 return V;
726}
727
Chris Lattner113f4f42002-06-25 16:13:24 +0000728Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000729 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000730
Chris Lattnere6794492002-08-12 21:17:25 +0000731 if (Op0 == Op1) // sub X, X -> 0
732 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000733
Chris Lattnere6794492002-08-12 21:17:25 +0000734 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000735 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000736 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000737
Chris Lattner81a7a232004-10-16 18:11:37 +0000738 if (isa<UndefValue>(Op0))
739 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
740 if (isa<UndefValue>(Op1))
741 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
742
Chris Lattner8f2f5982003-11-05 01:06:05 +0000743 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
744 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000745 if (C->isAllOnesValue())
746 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000747
Chris Lattner8f2f5982003-11-05 01:06:05 +0000748 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000749 Value *X;
750 if (match(Op1, m_Not(m_Value(X))))
751 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000752 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000753 // -((uint)X >> 31) -> ((int)X >> 31)
754 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000755 if (C->isNullValue()) {
756 Value *NoopCastedRHS = RemoveNoopCast(Op1);
757 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000758 if (SI->getOpcode() == Instruction::Shr)
759 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
760 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000761 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000762 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000763 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000764 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000765 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000766 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000767 // Ok, the transformation is safe. Insert a cast of the incoming
768 // value, then the new shift, then the new cast.
769 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
770 SI->getOperand(0)->getName());
771 Value *InV = InsertNewInstBefore(FirstCast, I);
772 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
773 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000774 if (NewShift->getType() == I.getType())
775 return NewShift;
776 else {
777 InV = InsertNewInstBefore(NewShift, I);
778 return new CastInst(NewShift, I.getType());
779 }
Chris Lattner92295c52004-03-12 23:53:13 +0000780 }
781 }
Chris Lattner022167f2004-03-13 00:11:49 +0000782 }
Chris Lattner183b3362004-04-09 19:05:30 +0000783
784 // Try to fold constant sub into select arguments.
785 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000786 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000787 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000788
789 if (isa<PHINode>(Op0))
790 if (Instruction *NV = FoldOpIntoPhi(I))
791 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000792 }
793
Chris Lattner3082c5a2003-02-18 19:28:33 +0000794 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000795 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000796 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
797 // is not used by anyone else...
798 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000799 if (Op1I->getOpcode() == Instruction::Sub &&
800 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000801 // Swap the two operands of the subexpr...
802 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
803 Op1I->setOperand(0, IIOp1);
804 Op1I->setOperand(1, IIOp0);
805
806 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000807 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000808 }
809
810 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
811 //
812 if (Op1I->getOpcode() == Instruction::And &&
813 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
814 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
815
Chris Lattner396dbfe2004-06-09 05:08:07 +0000816 Value *NewNot =
817 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000818 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000819 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000820
Chris Lattner0aee4b72004-10-06 15:08:25 +0000821 // -(X sdiv C) -> (X sdiv -C)
822 if (Op1I->getOpcode() == Instruction::Div)
823 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
824 if (CSI->getValue() == 0)
825 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
826 return BinaryOperator::createDiv(Op1I->getOperand(0),
827 ConstantExpr::getNeg(DivRHS));
828
Chris Lattner57c8d992003-02-18 19:57:07 +0000829 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000830 ConstantInt *C2;
831 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
832 Constant *CP1 =
833 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000834 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000835 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000836 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000837
Chris Lattner411336f2005-01-19 21:50:18 +0000838 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
839 if (Op0I->getOpcode() == Instruction::Add)
840 if (!Op0->getType()->isFloatingPoint()) {
841 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
842 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
843 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
844 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
845 }
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000846
847 ConstantInt *C1;
848 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
849 if (X == Op1) { // X*C - X --> X * (C-1)
850 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
851 return BinaryOperator::createMul(Op1, CP1);
852 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000853
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000854 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
855 if (X == dyn_castFoldableMul(Op1, C2))
856 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
857 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000858 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000859}
860
Chris Lattnere79e8542004-02-23 06:38:22 +0000861/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
862/// really just returns true if the most significant (sign) bit is set.
863static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
864 if (RHS->getType()->isSigned()) {
865 // True if source is LHS < 0 or LHS <= -1
866 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
867 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
868 } else {
869 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
870 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
871 // the size of the integer type.
872 if (Opcode == Instruction::SetGE)
873 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
874 if (Opcode == Instruction::SetGT)
875 return RHSC->getValue() ==
876 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
877 }
878 return false;
879}
880
Chris Lattner113f4f42002-06-25 16:13:24 +0000881Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000882 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000883 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000884
Chris Lattner81a7a232004-10-16 18:11:37 +0000885 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
886 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
887
Chris Lattnere6794492002-08-12 21:17:25 +0000888 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000889 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
890 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000891
892 // ((X << C1)*C2) == (X * (C2 << C1))
893 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
894 if (SI->getOpcode() == Instruction::Shl)
895 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000896 return BinaryOperator::createMul(SI->getOperand(0),
897 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000898
Chris Lattnercce81be2003-09-11 22:24:54 +0000899 if (CI->isNullValue())
900 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
901 if (CI->equalsInt(1)) // X * 1 == X
902 return ReplaceInstUsesWith(I, Op0);
903 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000904 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000905
Chris Lattnercce81be2003-09-11 22:24:54 +0000906 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000907 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
908 return new ShiftInst(Instruction::Shl, Op0,
909 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000910 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000911 if (Op1F->isNullValue())
912 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000913
Chris Lattner3082c5a2003-02-18 19:28:33 +0000914 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
915 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
916 if (Op1F->getValue() == 1.0)
917 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
918 }
Chris Lattner183b3362004-04-09 19:05:30 +0000919
920 // Try to fold constant mul into select arguments.
921 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000922 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000923 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000924
925 if (isa<PHINode>(Op0))
926 if (Instruction *NV = FoldOpIntoPhi(I))
927 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000928 }
929
Chris Lattner934a64cf2003-03-10 23:23:04 +0000930 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
931 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000932 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000933
Chris Lattner2635b522004-02-23 05:39:21 +0000934 // If one of the operands of the multiply is a cast from a boolean value, then
935 // we know the bool is either zero or one, so this is a 'masking' multiply.
936 // See if we can simplify things based on how the boolean was originally
937 // formed.
938 CastInst *BoolCast = 0;
939 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
940 if (CI->getOperand(0)->getType() == Type::BoolTy)
941 BoolCast = CI;
942 if (!BoolCast)
943 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
944 if (CI->getOperand(0)->getType() == Type::BoolTy)
945 BoolCast = CI;
946 if (BoolCast) {
947 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
948 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
949 const Type *SCOpTy = SCIOp0->getType();
950
Chris Lattnere79e8542004-02-23 06:38:22 +0000951 // If the setcc is true iff the sign bit of X is set, then convert this
952 // multiply into a shift/and combination.
953 if (isa<ConstantInt>(SCIOp1) &&
954 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000955 // Shift the X value right to turn it into "all signbits".
956 Constant *Amt = ConstantUInt::get(Type::UByteTy,
957 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000958 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000959 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000960 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
961 SCIOp0->getName()), I);
962 }
963
964 Value *V =
965 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
966 BoolCast->getOperand(0)->getName()+
967 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000968
969 // If the multiply type is not the same as the source type, sign extend
970 // or truncate to the multiply type.
971 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000972 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000973
974 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000975 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000976 }
977 }
978 }
979
Chris Lattner113f4f42002-06-25 16:13:24 +0000980 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000981}
982
Chris Lattner113f4f42002-06-25 16:13:24 +0000983Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000984 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +0000985
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000986 if (isa<UndefValue>(Op0)) // undef / X -> 0
987 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
988 if (isa<UndefValue>(Op1))
989 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
990
991 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000992 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000993 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000994 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000995
Chris Lattnere20c3342004-04-26 14:01:59 +0000996 // div X, -1 == -X
997 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000998 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +0000999
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001000 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +00001001 if (LHS->getOpcode() == Instruction::Div)
1002 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +00001003 // (X / C1) / C2 -> X / (C1*C2)
1004 return BinaryOperator::createDiv(LHS->getOperand(0),
1005 ConstantExpr::getMul(RHS, LHSRHS));
1006 }
1007
Chris Lattner3082c5a2003-02-18 19:28:33 +00001008 // Check to see if this is an unsigned division with an exact power of 2,
1009 // if so, convert to a right shift.
1010 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1011 if (uint64_t Val = C->getValue()) // Don't break X / 0
1012 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001013 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001014 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001015
Chris Lattner4ad08352004-10-09 02:50:40 +00001016 // -X/C -> X/-C
1017 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001018 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001019 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1020
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001021 if (!RHS->isNullValue()) {
1022 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001023 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001024 return R;
1025 if (isa<PHINode>(Op0))
1026 if (Instruction *NV = FoldOpIntoPhi(I))
1027 return NV;
1028 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001029 }
1030
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001031 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1032 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1033 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1034 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1035 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1036 if (STO->getValue() == 0) { // Couldn't be this argument.
1037 I.setOperand(1, SFO);
1038 return &I;
1039 } else if (SFO->getValue() == 0) {
1040 I.setOperand(1, STO);
1041 return &I;
1042 }
1043
1044 if (uint64_t TSA = Log2(STO->getValue()))
1045 if (uint64_t FSA = Log2(SFO->getValue())) {
1046 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1047 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1048 TC, SI->getName()+".t");
1049 TSI = InsertNewInstBefore(TSI, I);
1050
1051 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1052 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1053 FC, SI->getName()+".f");
1054 FSI = InsertNewInstBefore(FSI, I);
1055 return new SelectInst(SI->getOperand(0), TSI, FSI);
1056 }
1057 }
1058
Chris Lattner3082c5a2003-02-18 19:28:33 +00001059 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001060 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001061 if (LHS->equalsInt(0))
1062 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1063
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001064 return 0;
1065}
1066
1067
Chris Lattner113f4f42002-06-25 16:13:24 +00001068Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001069 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001070 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001071 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001072 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001073 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001074 // X % -Y -> X % Y
1075 AddUsesToWorkList(I);
1076 I.setOperand(1, RHSNeg);
1077 return &I;
1078 }
1079
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001080 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001081 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001082 if (isa<UndefValue>(Op1))
1083 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001084
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001085 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001086 if (RHS->equalsInt(1)) // X % 1 == 0
1087 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1088
1089 // Check to see if this is an unsigned remainder with an exact power of 2,
1090 // if so, convert to a bitwise and.
1091 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1092 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001093 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001094 return BinaryOperator::createAnd(Op0,
1095 ConstantUInt::get(I.getType(), Val-1));
1096
1097 if (!RHS->isNullValue()) {
1098 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001099 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001100 return R;
1101 if (isa<PHINode>(Op0))
1102 if (Instruction *NV = FoldOpIntoPhi(I))
1103 return NV;
1104 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001105 }
1106
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001107 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1108 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1109 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1110 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1111 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1112 if (STO->getValue() == 0) { // Couldn't be this argument.
1113 I.setOperand(1, SFO);
1114 return &I;
1115 } else if (SFO->getValue() == 0) {
1116 I.setOperand(1, STO);
1117 return &I;
1118 }
1119
1120 if (!(STO->getValue() & (STO->getValue()-1)) &&
1121 !(SFO->getValue() & (SFO->getValue()-1))) {
1122 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1123 SubOne(STO), SI->getName()+".t"), I);
1124 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1125 SubOne(SFO), SI->getName()+".f"), I);
1126 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1127 }
1128 }
1129
Chris Lattner3082c5a2003-02-18 19:28:33 +00001130 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001131 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001132 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001133 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1134
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001135 return 0;
1136}
1137
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001138// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001139static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001140 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1141 // Calculate -1 casted to the right type...
1142 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1143 uint64_t Val = ~0ULL; // All ones
1144 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1145 return CU->getValue() == Val-1;
1146 }
1147
1148 const ConstantSInt *CS = cast<ConstantSInt>(C);
1149
1150 // Calculate 0111111111..11111
1151 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1152 int64_t Val = INT64_MAX; // All ones
1153 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1154 return CS->getValue() == Val-1;
1155}
1156
1157// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001158static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001159 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1160 return CU->getValue() == 1;
1161
1162 const ConstantSInt *CS = cast<ConstantSInt>(C);
1163
1164 // Calculate 1111111111000000000000
1165 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1166 int64_t Val = -1; // All ones
1167 Val <<= TypeBits-1; // Shift over to the right spot
1168 return CS->getValue() == Val+1;
1169}
1170
Chris Lattner35167c32004-06-09 07:59:58 +00001171// isOneBitSet - Return true if there is exactly one bit set in the specified
1172// constant.
1173static bool isOneBitSet(const ConstantInt *CI) {
1174 uint64_t V = CI->getRawValue();
1175 return V && (V & (V-1)) == 0;
1176}
1177
Chris Lattner8fc5af42004-09-23 21:46:38 +00001178#if 0 // Currently unused
1179// isLowOnes - Return true if the constant is of the form 0+1+.
1180static bool isLowOnes(const ConstantInt *CI) {
1181 uint64_t V = CI->getRawValue();
1182
1183 // There won't be bits set in parts that the type doesn't contain.
1184 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1185
1186 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1187 return U && V && (U & V) == 0;
1188}
1189#endif
1190
1191// isHighOnes - Return true if the constant is of the form 1+0+.
1192// This is the same as lowones(~X).
1193static bool isHighOnes(const ConstantInt *CI) {
1194 uint64_t V = ~CI->getRawValue();
1195
1196 // There won't be bits set in parts that the type doesn't contain.
1197 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1198
1199 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1200 return U && V && (U & V) == 0;
1201}
1202
1203
Chris Lattner3ac7c262003-08-13 20:16:26 +00001204/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1205/// are carefully arranged to allow folding of expressions such as:
1206///
1207/// (A < B) | (A > B) --> (A != B)
1208///
1209/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1210/// represents that the comparison is true if A == B, and bit value '1' is true
1211/// if A < B.
1212///
1213static unsigned getSetCondCode(const SetCondInst *SCI) {
1214 switch (SCI->getOpcode()) {
1215 // False -> 0
1216 case Instruction::SetGT: return 1;
1217 case Instruction::SetEQ: return 2;
1218 case Instruction::SetGE: return 3;
1219 case Instruction::SetLT: return 4;
1220 case Instruction::SetNE: return 5;
1221 case Instruction::SetLE: return 6;
1222 // True -> 7
1223 default:
1224 assert(0 && "Invalid SetCC opcode!");
1225 return 0;
1226 }
1227}
1228
1229/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1230/// opcode and two operands into either a constant true or false, or a brand new
1231/// SetCC instruction.
1232static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1233 switch (Opcode) {
1234 case 0: return ConstantBool::False;
1235 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1236 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1237 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1238 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1239 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1240 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1241 case 7: return ConstantBool::True;
1242 default: assert(0 && "Illegal SetCCCode!"); return 0;
1243 }
1244}
1245
1246// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1247struct FoldSetCCLogical {
1248 InstCombiner &IC;
1249 Value *LHS, *RHS;
1250 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1251 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1252 bool shouldApply(Value *V) const {
1253 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1254 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1255 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1256 return false;
1257 }
1258 Instruction *apply(BinaryOperator &Log) const {
1259 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1260 if (SCI->getOperand(0) != LHS) {
1261 assert(SCI->getOperand(1) == LHS);
1262 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1263 }
1264
1265 unsigned LHSCode = getSetCondCode(SCI);
1266 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1267 unsigned Code;
1268 switch (Log.getOpcode()) {
1269 case Instruction::And: Code = LHSCode & RHSCode; break;
1270 case Instruction::Or: Code = LHSCode | RHSCode; break;
1271 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001272 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001273 }
1274
1275 Value *RV = getSetCCValue(Code, LHS, RHS);
1276 if (Instruction *I = dyn_cast<Instruction>(RV))
1277 return I;
1278 // Otherwise, it's a constant boolean value...
1279 return IC.ReplaceInstUsesWith(Log, RV);
1280 }
1281};
1282
1283
Chris Lattner86102b82005-01-01 16:22:27 +00001284/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1285/// this predicate to simplify operations downstream. V and Mask are known to
1286/// be the same type.
1287static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1288 if (isa<UndefValue>(V) || Mask->isNullValue())
1289 return true;
1290 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1291 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
1292
1293 if (Instruction *I = dyn_cast<Instruction>(V)) {
1294 switch (I->getOpcode()) {
1295 case Instruction::And:
1296 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1297 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1298 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1299 return true;
1300 break;
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001301 case Instruction::Or:
1302 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
1303 return MaskedValueIsZero(I->getOperand(1), Mask) &&
1304 MaskedValueIsZero(I->getOperand(0), Mask);
1305 case Instruction::Select:
1306 // If the T and F values are MaskedValueIsZero, the result is also zero.
1307 return MaskedValueIsZero(I->getOperand(2), Mask) &&
1308 MaskedValueIsZero(I->getOperand(1), Mask);
Chris Lattner86102b82005-01-01 16:22:27 +00001309 case Instruction::Cast: {
1310 const Type *SrcTy = I->getOperand(0)->getType();
1311 if (SrcTy->isIntegral()) {
1312 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1313 if (SrcTy->isUnsigned() && // Only handle zero ext.
1314 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1315 return true;
1316
1317 // If this is a noop cast, recurse.
1318 if (SrcTy != Type::BoolTy)
1319 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() ==I->getType()) ||
1320 SrcTy->getSignedVersion() == I->getType()) {
1321 Constant *NewMask =
1322 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1323 return MaskedValueIsZero(I->getOperand(0),
1324 cast<ConstantIntegral>(NewMask));
1325 }
1326 }
1327 break;
1328 }
1329 case Instruction::Shl:
1330 // (shl X, C1) & C2 == 0 iff (-1 << C1) & C2 == 0
1331 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1332 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1333 C1 = ConstantExpr::getShl(C1, SA);
1334 C1 = ConstantExpr::getAnd(C1, Mask);
1335 if (C1->isNullValue())
1336 return true;
1337 }
1338 break;
1339 case Instruction::Shr:
1340 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1341 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1342 if (I->getType()->isUnsigned()) {
1343 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1344 C1 = ConstantExpr::getShr(C1, SA);
1345 C1 = ConstantExpr::getAnd(C1, Mask);
1346 if (C1->isNullValue())
1347 return true;
1348 }
1349 break;
1350 }
1351 }
1352
1353 return false;
1354}
1355
Chris Lattnerba1cb382003-09-19 17:17:26 +00001356// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1357// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1358// guaranteed to be either a shift instruction or a binary operator.
1359Instruction *InstCombiner::OptAndOp(Instruction *Op,
1360 ConstantIntegral *OpRHS,
1361 ConstantIntegral *AndRHS,
1362 BinaryOperator &TheAnd) {
1363 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001364 Constant *Together = 0;
1365 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001366 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001367
Chris Lattnerba1cb382003-09-19 17:17:26 +00001368 switch (Op->getOpcode()) {
1369 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001370 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001371 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1372 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001373 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001374 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001375 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001376 }
1377 break;
1378 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001379 if (Together == AndRHS) // (X | C) & C --> C
1380 return ReplaceInstUsesWith(TheAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001381
Chris Lattner86102b82005-01-01 16:22:27 +00001382 if (Op->hasOneUse() && Together != OpRHS) {
1383 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1384 std::string Op0Name = Op->getName(); Op->setName("");
1385 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1386 InsertNewInstBefore(Or, TheAnd);
1387 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001388 }
1389 break;
1390 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001391 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001392 // Adding a one to a single bit bit-field should be turned into an XOR
1393 // of the bit. First thing to check is to see if this AND is with a
1394 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001395 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001396
1397 // Clear bits that are not part of the constant.
1398 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1399
1400 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001401 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001402 // Ok, at this point, we know that we are masking the result of the
1403 // ADD down to exactly one bit. If the constant we are adding has
1404 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001405 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001406
1407 // Check to see if any bits below the one bit set in AndRHSV are set.
1408 if ((AddRHS & (AndRHSV-1)) == 0) {
1409 // If not, the only thing that can effect the output of the AND is
1410 // the bit specified by AndRHSV. If that bit is set, the effect of
1411 // the XOR is to toggle the bit. If it is clear, then the ADD has
1412 // no effect.
1413 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1414 TheAnd.setOperand(0, X);
1415 return &TheAnd;
1416 } else {
1417 std::string Name = Op->getName(); Op->setName("");
1418 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001419 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001420 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001421 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001422 }
1423 }
1424 }
1425 }
1426 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001427
1428 case Instruction::Shl: {
1429 // We know that the AND will not produce any of the bits shifted in, so if
1430 // the anded constant includes them, clear them now!
1431 //
1432 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001433 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1434 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1435
1436 if (CI == ShlMask) { // Masking out bits that the shift already masks
1437 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1438 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001439 TheAnd.setOperand(1, CI);
1440 return &TheAnd;
1441 }
1442 break;
1443 }
1444 case Instruction::Shr:
1445 // We know that the AND will not produce any of the bits shifted in, so if
1446 // the anded constant includes them, clear them now! This only applies to
1447 // unsigned shifts, because a signed shr may bring in set bits!
1448 //
1449 if (AndRHS->getType()->isUnsigned()) {
1450 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001451 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1452 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1453
1454 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1455 return ReplaceInstUsesWith(TheAnd, Op);
1456 } else if (CI != AndRHS) {
1457 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001458 return &TheAnd;
1459 }
Chris Lattner7e794272004-09-24 15:21:34 +00001460 } else { // Signed shr.
1461 // See if this is shifting in some sign extension, then masking it out
1462 // with an and.
1463 if (Op->hasOneUse()) {
1464 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1465 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1466 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001467 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001468 // Make the argument unsigned.
1469 Value *ShVal = Op->getOperand(0);
1470 ShVal = InsertCastBefore(ShVal,
1471 ShVal->getType()->getUnsignedVersion(),
1472 TheAnd);
1473 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1474 OpRHS, Op->getName()),
1475 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001476 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1477 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1478 TheAnd.getName()),
1479 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001480 return new CastInst(ShVal, Op->getType());
1481 }
1482 }
Chris Lattner2da29172003-09-19 19:05:02 +00001483 }
1484 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001485 }
1486 return 0;
1487}
1488
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001489
Chris Lattner6862fbd2004-09-29 17:40:11 +00001490/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1491/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1492/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1493/// insert new instructions.
1494Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1495 bool Inside, Instruction &IB) {
1496 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1497 "Lo is not <= Hi in range emission code!");
1498 if (Inside) {
1499 if (Lo == Hi) // Trivially false.
1500 return new SetCondInst(Instruction::SetNE, V, V);
1501 if (cast<ConstantIntegral>(Lo)->isMinValue())
1502 return new SetCondInst(Instruction::SetLT, V, Hi);
1503
1504 Constant *AddCST = ConstantExpr::getNeg(Lo);
1505 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1506 InsertNewInstBefore(Add, IB);
1507 // Convert to unsigned for the comparison.
1508 const Type *UnsType = Add->getType()->getUnsignedVersion();
1509 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1510 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1511 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1512 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1513 }
1514
1515 if (Lo == Hi) // Trivially true.
1516 return new SetCondInst(Instruction::SetEQ, V, V);
1517
1518 Hi = SubOne(cast<ConstantInt>(Hi));
1519 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1520 return new SetCondInst(Instruction::SetGT, V, Hi);
1521
1522 // Emit X-Lo > Hi-Lo-1
1523 Constant *AddCST = ConstantExpr::getNeg(Lo);
1524 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1525 InsertNewInstBefore(Add, IB);
1526 // Convert to unsigned for the comparison.
1527 const Type *UnsType = Add->getType()->getUnsignedVersion();
1528 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1529 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1530 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1531 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1532}
1533
1534
Chris Lattner113f4f42002-06-25 16:13:24 +00001535Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001536 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001538
Chris Lattner81a7a232004-10-16 18:11:37 +00001539 if (isa<UndefValue>(Op1)) // X & undef -> 0
1540 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1541
Chris Lattner86102b82005-01-01 16:22:27 +00001542 // and X, X = X
1543 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001544 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001545
Chris Lattner86102b82005-01-01 16:22:27 +00001546 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001547 // and X, -1 == X
1548 if (AndRHS->isAllOnesValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001549 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001550
Chris Lattner86102b82005-01-01 16:22:27 +00001551 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1552 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1553
1554 // If the mask is not masking out any bits, there is no reason to do the
1555 // and in the first place.
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001556 ConstantIntegral *NotAndRHS =
1557 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
1558 if (MaskedValueIsZero(Op0, NotAndRHS))
1559 return ReplaceInstUsesWith(I, Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001560
Chris Lattnerba1cb382003-09-19 17:17:26 +00001561 // Optimize a variety of ((val OP C1) & C2) combinations...
1562 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1563 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001564 Value *Op0LHS = Op0I->getOperand(0);
1565 Value *Op0RHS = Op0I->getOperand(1);
1566 switch (Op0I->getOpcode()) {
1567 case Instruction::Xor:
1568 case Instruction::Or:
1569 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1570 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1571 if (MaskedValueIsZero(Op0LHS, AndRHS))
1572 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1573 if (MaskedValueIsZero(Op0RHS, AndRHS))
1574 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattner9e2c7fa2005-01-23 20:26:55 +00001575
1576 // If the mask is only needed on one incoming arm, push it up.
1577 if (Op0I->hasOneUse()) {
1578 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1579 // Not masking anything out for the LHS, move to RHS.
1580 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1581 Op0RHS->getName()+".masked");
1582 InsertNewInstBefore(NewRHS, I);
1583 return BinaryOperator::create(
1584 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
1585 }
1586 if (!isa<Constant>(NotAndRHS) &&
1587 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1588 // Not masking anything out for the RHS, move to LHS.
1589 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1590 Op0LHS->getName()+".masked");
1591 InsertNewInstBefore(NewLHS, I);
1592 return BinaryOperator::create(
1593 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1594 }
1595 }
1596
Chris Lattner86102b82005-01-01 16:22:27 +00001597 break;
1598 case Instruction::And:
1599 // (X & V) & C2 --> 0 iff (V & C2) == 0
1600 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1601 MaskedValueIsZero(Op0RHS, AndRHS))
1602 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1603 break;
1604 }
1605
Chris Lattner16464b32003-07-23 19:25:52 +00001606 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001607 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001608 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001609 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1610 const Type *SrcTy = CI->getOperand(0)->getType();
1611
1612 // If this is an integer sign or zero extension instruction.
1613 if (SrcTy->isIntegral() &&
1614 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
1615
1616 if (SrcTy->isUnsigned()) {
1617 // See if this and is clearing out bits that are known to be zero
1618 // anyway (due to the zero extension).
1619 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1620 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1621 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1622 if (Result == Mask) // The "and" isn't doing anything, remove it.
1623 return ReplaceInstUsesWith(I, CI);
1624 if (Result != AndRHS) { // Reduce the and RHS constant.
1625 I.setOperand(1, Result);
1626 return &I;
1627 }
1628
1629 } else {
1630 if (CI->hasOneUse() && SrcTy->isInteger()) {
1631 // We can only do this if all of the sign bits brought in are masked
1632 // out. Compute this by first getting 0000011111, then inverting
1633 // it.
1634 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1635 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1636 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1637 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1638 // If the and is clearing all of the sign bits, change this to a
1639 // zero extension cast. To do this, cast the cast input to
1640 // unsigned, then to the requested size.
1641 Value *CastOp = CI->getOperand(0);
1642 Instruction *NC =
1643 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1644 CI->getName()+".uns");
1645 NC = InsertNewInstBefore(NC, I);
1646 // Finally, insert a replacement for CI.
1647 NC = new CastInst(NC, CI->getType(), CI->getName());
1648 CI->setName("");
1649 NC = InsertNewInstBefore(NC, I);
1650 WorkList.push_back(CI); // Delete CI later.
1651 I.setOperand(0, NC);
1652 return &I; // The AND operand was modified.
1653 }
1654 }
1655 }
1656 }
Chris Lattner33217db2003-07-23 19:36:21 +00001657 }
Chris Lattner183b3362004-04-09 19:05:30 +00001658
1659 // Try to fold constant and into select arguments.
1660 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001661 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001662 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001663 if (isa<PHINode>(Op0))
1664 if (Instruction *NV = FoldOpIntoPhi(I))
1665 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001666 }
1667
Chris Lattnerbb74e222003-03-10 23:06:50 +00001668 Value *Op0NotVal = dyn_castNotVal(Op0);
1669 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001670
Chris Lattner023a4832004-06-18 06:07:51 +00001671 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1672 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1673
Misha Brukman9c003d82004-07-30 12:50:08 +00001674 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001675 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001676 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1677 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001678 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001679 return BinaryOperator::createNot(Or);
1680 }
1681
Chris Lattner623826c2004-09-28 21:48:02 +00001682 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1683 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001684 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1685 return R;
1686
Chris Lattner623826c2004-09-28 21:48:02 +00001687 Value *LHSVal, *RHSVal;
1688 ConstantInt *LHSCst, *RHSCst;
1689 Instruction::BinaryOps LHSCC, RHSCC;
1690 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1691 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1692 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1693 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1694 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1695 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1696 // Ensure that the larger constant is on the RHS.
1697 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1698 SetCondInst *LHS = cast<SetCondInst>(Op0);
1699 if (cast<ConstantBool>(Cmp)->getValue()) {
1700 std::swap(LHS, RHS);
1701 std::swap(LHSCst, RHSCst);
1702 std::swap(LHSCC, RHSCC);
1703 }
1704
1705 // At this point, we know we have have two setcc instructions
1706 // comparing a value against two constants and and'ing the result
1707 // together. Because of the above check, we know that we only have
1708 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1709 // FoldSetCCLogical check above), that the two constants are not
1710 // equal.
1711 assert(LHSCst != RHSCst && "Compares not folded above?");
1712
1713 switch (LHSCC) {
1714 default: assert(0 && "Unknown integer condition code!");
1715 case Instruction::SetEQ:
1716 switch (RHSCC) {
1717 default: assert(0 && "Unknown integer condition code!");
1718 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1719 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1720 return ReplaceInstUsesWith(I, ConstantBool::False);
1721 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1722 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1723 return ReplaceInstUsesWith(I, LHS);
1724 }
1725 case Instruction::SetNE:
1726 switch (RHSCC) {
1727 default: assert(0 && "Unknown integer condition code!");
1728 case Instruction::SetLT:
1729 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1730 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1731 break; // (X != 13 & X < 15) -> no change
1732 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1733 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1734 return ReplaceInstUsesWith(I, RHS);
1735 case Instruction::SetNE:
1736 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1737 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1738 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1739 LHSVal->getName()+".off");
1740 InsertNewInstBefore(Add, I);
1741 const Type *UnsType = Add->getType()->getUnsignedVersion();
1742 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1743 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1744 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1745 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1746 }
1747 break; // (X != 13 & X != 15) -> no change
1748 }
1749 break;
1750 case Instruction::SetLT:
1751 switch (RHSCC) {
1752 default: assert(0 && "Unknown integer condition code!");
1753 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1754 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1755 return ReplaceInstUsesWith(I, ConstantBool::False);
1756 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1757 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1758 return ReplaceInstUsesWith(I, LHS);
1759 }
1760 case Instruction::SetGT:
1761 switch (RHSCC) {
1762 default: assert(0 && "Unknown integer condition code!");
1763 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1764 return ReplaceInstUsesWith(I, LHS);
1765 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1766 return ReplaceInstUsesWith(I, RHS);
1767 case Instruction::SetNE:
1768 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1769 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1770 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001771 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1772 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001773 }
1774 }
1775 }
1776 }
1777
Chris Lattner113f4f42002-06-25 16:13:24 +00001778 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001779}
1780
Chris Lattner113f4f42002-06-25 16:13:24 +00001781Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001782 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001783 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001784
Chris Lattner81a7a232004-10-16 18:11:37 +00001785 if (isa<UndefValue>(Op1))
1786 return ReplaceInstUsesWith(I, // X | undef -> -1
1787 ConstantIntegral::getAllOnesValue(I.getType()));
1788
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001789 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001790 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1791 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001792
1793 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001794 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001795 // If X is known to only contain bits that already exist in RHS, just
1796 // replace this instruction with RHS directly.
1797 if (MaskedValueIsZero(Op0,
1798 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1799 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001800
Chris Lattnerd4252a72004-07-30 07:50:03 +00001801 ConstantInt *C1; Value *X;
1802 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1803 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1804 std::string Op0Name = Op0->getName(); Op0->setName("");
1805 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1806 InsertNewInstBefore(Or, I);
1807 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1808 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001809
Chris Lattnerd4252a72004-07-30 07:50:03 +00001810 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1811 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1812 std::string Op0Name = Op0->getName(); Op0->setName("");
1813 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1814 InsertNewInstBefore(Or, I);
1815 return BinaryOperator::createXor(Or,
1816 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001817 }
Chris Lattner183b3362004-04-09 19:05:30 +00001818
1819 // Try to fold constant and into select arguments.
1820 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001821 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001822 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001823 if (isa<PHINode>(Op0))
1824 if (Instruction *NV = FoldOpIntoPhi(I))
1825 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001826 }
1827
Chris Lattner812aab72003-08-12 19:11:07 +00001828 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001829 Value *A, *B; ConstantInt *C1, *C2;
1830 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1831 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1832 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001833
Chris Lattnerd4252a72004-07-30 07:50:03 +00001834 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1835 if (A == Op1) // ~A | A == -1
1836 return ReplaceInstUsesWith(I,
1837 ConstantIntegral::getAllOnesValue(I.getType()));
1838 } else {
1839 A = 0;
1840 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001841
Chris Lattnerd4252a72004-07-30 07:50:03 +00001842 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1843 if (Op0 == B)
1844 return ReplaceInstUsesWith(I,
1845 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001846
Misha Brukman9c003d82004-07-30 12:50:08 +00001847 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001848 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1849 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1850 I.getName()+".demorgan"), I);
1851 return BinaryOperator::createNot(And);
1852 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001853 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001854
Chris Lattner3ac7c262003-08-13 20:16:26 +00001855 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001856 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001857 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1858 return R;
1859
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001860 Value *LHSVal, *RHSVal;
1861 ConstantInt *LHSCst, *RHSCst;
1862 Instruction::BinaryOps LHSCC, RHSCC;
1863 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1864 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1865 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1866 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1867 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1868 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1869 // Ensure that the larger constant is on the RHS.
1870 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1871 SetCondInst *LHS = cast<SetCondInst>(Op0);
1872 if (cast<ConstantBool>(Cmp)->getValue()) {
1873 std::swap(LHS, RHS);
1874 std::swap(LHSCst, RHSCst);
1875 std::swap(LHSCC, RHSCC);
1876 }
1877
1878 // At this point, we know we have have two setcc instructions
1879 // comparing a value against two constants and or'ing the result
1880 // together. Because of the above check, we know that we only have
1881 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1882 // FoldSetCCLogical check above), that the two constants are not
1883 // equal.
1884 assert(LHSCst != RHSCst && "Compares not folded above?");
1885
1886 switch (LHSCC) {
1887 default: assert(0 && "Unknown integer condition code!");
1888 case Instruction::SetEQ:
1889 switch (RHSCC) {
1890 default: assert(0 && "Unknown integer condition code!");
1891 case Instruction::SetEQ:
1892 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1893 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1894 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1895 LHSVal->getName()+".off");
1896 InsertNewInstBefore(Add, I);
1897 const Type *UnsType = Add->getType()->getUnsignedVersion();
1898 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1899 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1900 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1901 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1902 }
1903 break; // (X == 13 | X == 15) -> no change
1904
1905 case Instruction::SetGT:
1906 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1907 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1908 break; // (X == 13 | X > 15) -> no change
1909 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1910 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1911 return ReplaceInstUsesWith(I, RHS);
1912 }
1913 break;
1914 case Instruction::SetNE:
1915 switch (RHSCC) {
1916 default: assert(0 && "Unknown integer condition code!");
1917 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1918 return ReplaceInstUsesWith(I, RHS);
1919 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1920 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1921 return ReplaceInstUsesWith(I, LHS);
1922 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1923 return ReplaceInstUsesWith(I, ConstantBool::True);
1924 }
1925 break;
1926 case Instruction::SetLT:
1927 switch (RHSCC) {
1928 default: assert(0 && "Unknown integer condition code!");
1929 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1930 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001931 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1932 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001933 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1934 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1935 return ReplaceInstUsesWith(I, RHS);
1936 }
1937 break;
1938 case Instruction::SetGT:
1939 switch (RHSCC) {
1940 default: assert(0 && "Unknown integer condition code!");
1941 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1942 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1943 return ReplaceInstUsesWith(I, LHS);
1944 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1945 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1946 return ReplaceInstUsesWith(I, ConstantBool::True);
1947 }
1948 }
1949 }
1950 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001951 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001952}
1953
Chris Lattnerc2076352004-02-16 01:20:27 +00001954// XorSelf - Implements: X ^ X --> 0
1955struct XorSelf {
1956 Value *RHS;
1957 XorSelf(Value *rhs) : RHS(rhs) {}
1958 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1959 Instruction *apply(BinaryOperator &Xor) const {
1960 return &Xor;
1961 }
1962};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001963
1964
Chris Lattner113f4f42002-06-25 16:13:24 +00001965Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001966 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001967 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001968
Chris Lattner81a7a232004-10-16 18:11:37 +00001969 if (isa<UndefValue>(Op1))
1970 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1971
Chris Lattnerc2076352004-02-16 01:20:27 +00001972 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1973 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1974 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001975 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001976 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001977
Chris Lattner97638592003-07-23 21:37:07 +00001978 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001979 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001980 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001981 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001982
Chris Lattner97638592003-07-23 21:37:07 +00001983 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001984 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001985 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001986 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001987 return new SetCondInst(SCI->getInverseCondition(),
1988 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001989
Chris Lattner8f2f5982003-11-05 01:06:05 +00001990 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001991 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1992 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001993 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1994 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001995 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001996 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001997 }
Chris Lattner023a4832004-06-18 06:07:51 +00001998
1999 // ~(~X & Y) --> (X | ~Y)
2000 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2001 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2002 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2003 Instruction *NotY =
2004 BinaryOperator::createNot(Op0I->getOperand(1),
2005 Op0I->getOperand(1)->getName()+".not");
2006 InsertNewInstBefore(NotY, I);
2007 return BinaryOperator::createOr(Op0NotVal, NotY);
2008 }
2009 }
Chris Lattner97638592003-07-23 21:37:07 +00002010
2011 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00002012 switch (Op0I->getOpcode()) {
2013 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00002014 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002015 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002016 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2017 return BinaryOperator::createSub(
2018 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002019 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00002020 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002021 }
Chris Lattnere5806662003-11-04 23:50:51 +00002022 break;
2023 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00002024 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002025 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2026 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00002027 break;
2028 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00002029 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002030 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002031 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00002032 break;
2033 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00002034 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00002035 }
Chris Lattner183b3362004-04-09 19:05:30 +00002036
2037 // Try to fold constant and into select arguments.
2038 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00002039 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002040 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002041 if (isa<PHINode>(Op0))
2042 if (Instruction *NV = FoldOpIntoPhi(I))
2043 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002044 }
2045
Chris Lattnerbb74e222003-03-10 23:06:50 +00002046 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002047 if (X == Op1)
2048 return ReplaceInstUsesWith(I,
2049 ConstantIntegral::getAllOnesValue(I.getType()));
2050
Chris Lattnerbb74e222003-03-10 23:06:50 +00002051 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002052 if (X == Op0)
2053 return ReplaceInstUsesWith(I,
2054 ConstantIntegral::getAllOnesValue(I.getType()));
2055
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002056 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002057 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002058 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2059 cast<BinaryOperator>(Op1I)->swapOperands();
2060 I.swapOperands();
2061 std::swap(Op0, Op1);
2062 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2063 I.swapOperands();
2064 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00002065 }
2066 } else if (Op1I->getOpcode() == Instruction::Xor) {
2067 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2068 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2069 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2070 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2071 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002072
2073 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002074 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002075 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2076 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002077 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002078 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2079 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002080 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002081 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002082 } else if (Op0I->getOpcode() == Instruction::Xor) {
2083 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2084 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2085 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2086 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002087 }
2088
Chris Lattner7aa2d472004-08-01 19:42:59 +00002089 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002090 Value *A, *B; ConstantInt *C1, *C2;
2091 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2092 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002093 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002094 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002095
Chris Lattner3ac7c262003-08-13 20:16:26 +00002096 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2097 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2098 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2099 return R;
2100
Chris Lattner113f4f42002-06-25 16:13:24 +00002101 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002102}
2103
Chris Lattner6862fbd2004-09-29 17:40:11 +00002104/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2105/// overflowed for this type.
2106static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2107 ConstantInt *In2) {
2108 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2109 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2110}
2111
2112static bool isPositive(ConstantInt *C) {
2113 return cast<ConstantSInt>(C)->getValue() >= 0;
2114}
2115
2116/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2117/// overflowed for this type.
2118static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2119 ConstantInt *In2) {
2120 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2121
2122 if (In1->getType()->isUnsigned())
2123 return cast<ConstantUInt>(Result)->getValue() <
2124 cast<ConstantUInt>(In1)->getValue();
2125 if (isPositive(In1) != isPositive(In2))
2126 return false;
2127 if (isPositive(In1))
2128 return cast<ConstantSInt>(Result)->getValue() <
2129 cast<ConstantSInt>(In1)->getValue();
2130 return cast<ConstantSInt>(Result)->getValue() >
2131 cast<ConstantSInt>(In1)->getValue();
2132}
2133
Chris Lattner0798af32005-01-13 20:14:25 +00002134/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2135/// code necessary to compute the offset from the base pointer (without adding
2136/// in the base pointer). Return the result as a signed integer of intptr size.
2137static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2138 TargetData &TD = IC.getTargetData();
2139 gep_type_iterator GTI = gep_type_begin(GEP);
2140 const Type *UIntPtrTy = TD.getIntPtrType();
2141 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2142 Value *Result = Constant::getNullValue(SIntPtrTy);
2143
2144 // Build a mask for high order bits.
2145 uint64_t PtrSizeMask = ~0ULL;
2146 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2147
Chris Lattner0798af32005-01-13 20:14:25 +00002148 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2149 Value *Op = GEP->getOperand(i);
Chris Lattnerd35d2102005-01-13 23:26:48 +00002150 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner0798af32005-01-13 20:14:25 +00002151 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2152 SIntPtrTy);
2153 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2154 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002155 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002156 Scale = ConstantExpr::getMul(OpC, Scale);
2157 if (Constant *RC = dyn_cast<Constant>(Result))
2158 Result = ConstantExpr::getAdd(RC, Scale);
2159 else {
2160 // Emit an add instruction.
2161 Result = IC.InsertNewInstBefore(
2162 BinaryOperator::createAdd(Result, Scale,
2163 GEP->getName()+".offs"), I);
2164 }
2165 }
2166 } else {
Chris Lattner7aa41cf2005-01-14 17:17:59 +00002167 // Convert to correct type.
2168 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2169 Op->getName()+".c"), I);
2170 if (Size != 1)
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002171 // We'll let instcombine(mul) convert this to a shl if possible.
2172 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2173 GEP->getName()+".idx"), I);
Chris Lattner0798af32005-01-13 20:14:25 +00002174
2175 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002176 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002177 GEP->getName()+".offs"), I);
2178 }
2179 }
2180 return Result;
2181}
2182
2183/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2184/// else. At this point we know that the GEP is on the LHS of the comparison.
2185Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2186 Instruction::BinaryOps Cond,
2187 Instruction &I) {
2188 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002189
2190 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2191 if (isa<PointerType>(CI->getOperand(0)->getType()))
2192 RHS = CI->getOperand(0);
2193
Chris Lattner0798af32005-01-13 20:14:25 +00002194 Value *PtrBase = GEPLHS->getOperand(0);
2195 if (PtrBase == RHS) {
2196 // As an optimization, we don't actually have to compute the actual value of
2197 // OFFSET if this is a seteq or setne comparison, just return whether each
2198 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002199 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2200 Instruction *InVal = 0;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002201 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2202 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattner81e84172005-01-13 22:25:21 +00002203 bool EmitIt = true;
2204 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2205 if (isa<UndefValue>(C)) // undef index -> undef.
2206 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2207 if (C->isNullValue())
2208 EmitIt = false;
Chris Lattnercd517ff2005-01-28 19:32:01 +00002209 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2210 EmitIt = false; // This is indexing into a zero sized array?
2211 } else if (isa<ConstantInt>(C))
Chris Lattner81e84172005-01-13 22:25:21 +00002212 return ReplaceInstUsesWith(I, // No comparison is needed here.
2213 ConstantBool::get(Cond == Instruction::SetNE));
2214 }
2215
2216 if (EmitIt) {
2217 Instruction *Comp =
2218 new SetCondInst(Cond, GEPLHS->getOperand(i),
2219 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2220 if (InVal == 0)
2221 InVal = Comp;
2222 else {
2223 InVal = InsertNewInstBefore(InVal, I);
2224 InsertNewInstBefore(Comp, I);
2225 if (Cond == Instruction::SetNE) // True if any are unequal
2226 InVal = BinaryOperator::createOr(InVal, Comp);
2227 else // True if all are equal
2228 InVal = BinaryOperator::createAnd(InVal, Comp);
2229 }
2230 }
2231 }
2232
2233 if (InVal)
2234 return InVal;
2235 else
2236 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2237 ConstantBool::get(Cond == Instruction::SetEQ));
2238 }
Chris Lattner0798af32005-01-13 20:14:25 +00002239
2240 // Only lower this if the setcc is the only user of the GEP or if we expect
2241 // the result to fold to a constant!
2242 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2243 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2244 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2245 return new SetCondInst(Cond, Offset,
2246 Constant::getNullValue(Offset->getType()));
2247 }
2248 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2249 if (PtrBase != GEPRHS->getOperand(0))
2250 return 0;
2251
Chris Lattner81e84172005-01-13 22:25:21 +00002252 // If one of the GEPs has all zero indices, recurse.
2253 bool AllZeros = true;
2254 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2255 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2256 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2257 AllZeros = false;
2258 break;
2259 }
2260 if (AllZeros)
2261 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2262 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4fa89822005-01-14 00:20:05 +00002263
2264 // If the other GEP has all zero indices, recurse.
Chris Lattner81e84172005-01-13 22:25:21 +00002265 AllZeros = true;
2266 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2267 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2268 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2269 AllZeros = false;
2270 break;
2271 }
2272 if (AllZeros)
2273 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2274
Chris Lattner4fa89822005-01-14 00:20:05 +00002275 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2276 // If the GEPs only differ by one index, compare it.
2277 unsigned NumDifferences = 0; // Keep track of # differences.
2278 unsigned DiffOperand = 0; // The operand that differs.
2279 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2280 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002281 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSize() !=
2282 GEPRHS->getOperand(i)->getType()->getPrimitiveSize()) {
2283 // Irreconcilable differences.
Chris Lattner4fa89822005-01-14 00:20:05 +00002284 NumDifferences = 2;
2285 break;
2286 } else {
2287 if (NumDifferences++) break;
2288 DiffOperand = i;
2289 }
2290 }
2291
2292 if (NumDifferences == 0) // SAME GEP?
2293 return ReplaceInstUsesWith(I, // No comparison is needed here.
2294 ConstantBool::get(Cond == Instruction::SetEQ));
2295 else if (NumDifferences == 1) {
Chris Lattnerfc4429e2005-01-21 23:06:49 +00002296 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2297 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2298 if (LHSV->getType() != RHSV->getType())
2299 LHSV = InsertNewInstBefore(new CastInst(LHSV, RHSV->getType(),
2300 LHSV->getName()+".c"), I);
2301 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4fa89822005-01-14 00:20:05 +00002302 }
2303 }
2304
Chris Lattner0798af32005-01-13 20:14:25 +00002305 // Only lower this if the setcc is the only user of the GEP or if we expect
2306 // the result to fold to a constant!
2307 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2308 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2309 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2310 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2311 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2312 return new SetCondInst(Cond, L, R);
2313 }
2314 }
2315 return 0;
2316}
2317
2318
Chris Lattner113f4f42002-06-25 16:13:24 +00002319Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002320 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002321 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2322 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002323
2324 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002325 if (Op0 == Op1)
2326 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002327
Chris Lattner81a7a232004-10-16 18:11:37 +00002328 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2329 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2330
Chris Lattner15ff1e12004-11-14 07:33:16 +00002331 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2332 // addresses never equal each other! We already know that Op0 != Op1.
2333 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2334 isa<ConstantPointerNull>(Op0)) &&
2335 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2336 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002337 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2338
2339 // setcc's with boolean values can always be turned into bitwise operations
2340 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002341 switch (I.getOpcode()) {
2342 default: assert(0 && "Invalid setcc instruction!");
2343 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002344 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002345 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002346 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002347 }
Chris Lattner4456da62004-08-11 00:50:51 +00002348 case Instruction::SetNE:
2349 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002350
Chris Lattner4456da62004-08-11 00:50:51 +00002351 case Instruction::SetGT:
2352 std::swap(Op0, Op1); // Change setgt -> setlt
2353 // FALL THROUGH
2354 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2355 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2356 InsertNewInstBefore(Not, I);
2357 return BinaryOperator::createAnd(Not, Op1);
2358 }
2359 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002360 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002361 // FALL THROUGH
2362 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2363 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2364 InsertNewInstBefore(Not, I);
2365 return BinaryOperator::createOr(Not, Op1);
2366 }
2367 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002368 }
2369
Chris Lattner2dd01742004-06-09 04:24:29 +00002370 // See if we are doing a comparison between a constant and an instruction that
2371 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002372 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002373 // Check to see if we are comparing against the minimum or maximum value...
2374 if (CI->isMinValue()) {
2375 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2376 return ReplaceInstUsesWith(I, ConstantBool::False);
2377 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2378 return ReplaceInstUsesWith(I, ConstantBool::True);
2379 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2380 return BinaryOperator::createSetEQ(Op0, Op1);
2381 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2382 return BinaryOperator::createSetNE(Op0, Op1);
2383
2384 } else if (CI->isMaxValue()) {
2385 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2386 return ReplaceInstUsesWith(I, ConstantBool::False);
2387 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2388 return ReplaceInstUsesWith(I, ConstantBool::True);
2389 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2390 return BinaryOperator::createSetEQ(Op0, Op1);
2391 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2392 return BinaryOperator::createSetNE(Op0, Op1);
2393
2394 // Comparing against a value really close to min or max?
2395 } else if (isMinValuePlusOne(CI)) {
2396 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2397 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2398 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2399 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2400
2401 } else if (isMaxValueMinusOne(CI)) {
2402 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2403 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2404 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2405 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2406 }
2407
2408 // If we still have a setle or setge instruction, turn it into the
2409 // appropriate setlt or setgt instruction. Since the border cases have
2410 // already been handled above, this requires little checking.
2411 //
2412 if (I.getOpcode() == Instruction::SetLE)
2413 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2414 if (I.getOpcode() == Instruction::SetGE)
2415 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2416
Chris Lattnere1e10e12004-05-25 06:32:08 +00002417 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002418 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002419 case Instruction::PHI:
2420 if (Instruction *NV = FoldOpIntoPhi(I))
2421 return NV;
2422 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002423 case Instruction::And:
2424 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2425 LHSI->getOperand(0)->hasOneUse()) {
2426 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2427 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2428 // happens a LOT in code produced by the C front-end, for bitfield
2429 // access.
2430 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2431 ConstantUInt *ShAmt;
2432 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2433 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2434 const Type *Ty = LHSI->getType();
2435
2436 // We can fold this as long as we can't shift unknown bits
2437 // into the mask. This can only happen with signed shift
2438 // rights, as they sign-extend.
2439 if (ShAmt) {
2440 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002441 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002442 if (!CanFold) {
2443 // To test for the bad case of the signed shr, see if any
2444 // of the bits shifted in could be tested after the mask.
2445 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00002446 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002447 Constant *ShVal =
2448 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2449 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2450 CanFold = true;
2451 }
2452
2453 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002454 Constant *NewCst;
2455 if (Shift->getOpcode() == Instruction::Shl)
2456 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2457 else
2458 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002459
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002460 // Check to see if we are shifting out any of the bits being
2461 // compared.
2462 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2463 // If we shifted bits out, the fold is not going to work out.
2464 // As a special case, check to see if this means that the
2465 // result is always true or false now.
2466 if (I.getOpcode() == Instruction::SetEQ)
2467 return ReplaceInstUsesWith(I, ConstantBool::False);
2468 if (I.getOpcode() == Instruction::SetNE)
2469 return ReplaceInstUsesWith(I, ConstantBool::True);
2470 } else {
2471 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002472 Constant *NewAndCST;
2473 if (Shift->getOpcode() == Instruction::Shl)
2474 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2475 else
2476 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2477 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002478 LHSI->setOperand(0, Shift->getOperand(0));
2479 WorkList.push_back(Shift); // Shift is dead.
2480 AddUsesToWorkList(I);
2481 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002482 }
2483 }
Chris Lattner35167c32004-06-09 07:59:58 +00002484 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002485 }
2486 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002487
Reid Spencer279fa252004-11-28 21:31:15 +00002488 // (setcc (cast X to larger), CI)
Chris Lattner03f06f12005-01-17 03:20:02 +00002489 case Instruction::Cast:
2490 if (Instruction *R =
2491 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI))
2492 return R;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002493 break;
Reid Spencer279fa252004-11-28 21:31:15 +00002494
Chris Lattner272d5ca2004-09-28 18:22:15 +00002495 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2496 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2497 switch (I.getOpcode()) {
2498 default: break;
2499 case Instruction::SetEQ:
2500 case Instruction::SetNE: {
2501 // If we are comparing against bits always shifted out, the
2502 // comparison cannot succeed.
2503 Constant *Comp =
2504 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2505 if (Comp != CI) {// Comparing against a bit that we know is zero.
2506 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2507 Constant *Cst = ConstantBool::get(IsSetNE);
2508 return ReplaceInstUsesWith(I, Cst);
2509 }
2510
2511 if (LHSI->hasOneUse()) {
2512 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002513 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002514 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2515 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2516
2517 Constant *Mask;
2518 if (CI->getType()->isUnsigned()) {
2519 Mask = ConstantUInt::get(CI->getType(), Val);
2520 } else if (ShAmtVal != 0) {
2521 Mask = ConstantSInt::get(CI->getType(), Val);
2522 } else {
2523 Mask = ConstantInt::getAllOnesValue(CI->getType());
2524 }
2525
2526 Instruction *AndI =
2527 BinaryOperator::createAnd(LHSI->getOperand(0),
2528 Mask, LHSI->getName()+".mask");
2529 Value *And = InsertNewInstBefore(AndI, I);
2530 return new SetCondInst(I.getOpcode(), And,
2531 ConstantExpr::getUShr(CI, ShAmt));
2532 }
2533 }
2534 }
2535 }
2536 break;
2537
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002538 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002539 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002540 switch (I.getOpcode()) {
2541 default: break;
2542 case Instruction::SetEQ:
2543 case Instruction::SetNE: {
2544 // If we are comparing against bits always shifted out, the
2545 // comparison cannot succeed.
2546 Constant *Comp =
2547 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2548
2549 if (Comp != CI) {// Comparing against a bit that we know is zero.
2550 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2551 Constant *Cst = ConstantBool::get(IsSetNE);
2552 return ReplaceInstUsesWith(I, Cst);
2553 }
2554
2555 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002556 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002557
Chris Lattner1023b872004-09-27 16:18:50 +00002558 // Otherwise strength reduce the shift into an and.
2559 uint64_t Val = ~0ULL; // All ones.
2560 Val <<= ShAmtVal; // Shift over to the right spot.
2561
2562 Constant *Mask;
2563 if (CI->getType()->isUnsigned()) {
2564 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2565 Val &= (1ULL << TypeBits)-1;
2566 Mask = ConstantUInt::get(CI->getType(), Val);
2567 } else {
2568 Mask = ConstantSInt::get(CI->getType(), Val);
2569 }
2570
2571 Instruction *AndI =
2572 BinaryOperator::createAnd(LHSI->getOperand(0),
2573 Mask, LHSI->getName()+".mask");
2574 Value *And = InsertNewInstBefore(AndI, I);
2575 return new SetCondInst(I.getOpcode(), And,
2576 ConstantExpr::getShl(CI, ShAmt));
2577 }
2578 break;
2579 }
2580 }
2581 }
2582 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002583
Chris Lattner6862fbd2004-09-29 17:40:11 +00002584 case Instruction::Div:
2585 // Fold: (div X, C1) op C2 -> range check
2586 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2587 // Fold this div into the comparison, producing a range check.
2588 // Determine, based on the divide type, what the range is being
2589 // checked. If there is an overflow on the low or high side, remember
2590 // it, otherwise compute the range [low, hi) bounding the new value.
2591 bool LoOverflow = false, HiOverflow = 0;
2592 ConstantInt *LoBound = 0, *HiBound = 0;
2593
2594 ConstantInt *Prod;
2595 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2596
Chris Lattnera92af962004-10-11 19:40:04 +00002597 Instruction::BinaryOps Opcode = I.getOpcode();
2598
Chris Lattner6862fbd2004-09-29 17:40:11 +00002599 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2600 } else if (LHSI->getType()->isUnsigned()) { // udiv
2601 LoBound = Prod;
2602 LoOverflow = ProdOV;
2603 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2604 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2605 if (CI->isNullValue()) { // (X / pos) op 0
2606 // Can't overflow.
2607 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2608 HiBound = DivRHS;
2609 } else if (isPositive(CI)) { // (X / pos) op pos
2610 LoBound = Prod;
2611 LoOverflow = ProdOV;
2612 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2613 } else { // (X / pos) op neg
2614 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2615 LoOverflow = AddWithOverflow(LoBound, Prod,
2616 cast<ConstantInt>(DivRHSH));
2617 HiBound = Prod;
2618 HiOverflow = ProdOV;
2619 }
2620 } else { // Divisor is < 0.
2621 if (CI->isNullValue()) { // (X / neg) op 0
2622 LoBound = AddOne(DivRHS);
2623 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2624 } else if (isPositive(CI)) { // (X / neg) op pos
2625 HiOverflow = LoOverflow = ProdOV;
2626 if (!LoOverflow)
2627 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2628 HiBound = AddOne(Prod);
2629 } else { // (X / neg) op neg
2630 LoBound = Prod;
2631 LoOverflow = HiOverflow = ProdOV;
2632 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2633 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002634
Chris Lattnera92af962004-10-11 19:40:04 +00002635 // Dividing by a negate swaps the condition.
2636 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002637 }
2638
2639 if (LoBound) {
2640 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002641 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002642 default: assert(0 && "Unhandled setcc opcode!");
2643 case Instruction::SetEQ:
2644 if (LoOverflow && HiOverflow)
2645 return ReplaceInstUsesWith(I, ConstantBool::False);
2646 else if (HiOverflow)
2647 return new SetCondInst(Instruction::SetGE, X, LoBound);
2648 else if (LoOverflow)
2649 return new SetCondInst(Instruction::SetLT, X, HiBound);
2650 else
2651 return InsertRangeTest(X, LoBound, HiBound, true, I);
2652 case Instruction::SetNE:
2653 if (LoOverflow && HiOverflow)
2654 return ReplaceInstUsesWith(I, ConstantBool::True);
2655 else if (HiOverflow)
2656 return new SetCondInst(Instruction::SetLT, X, LoBound);
2657 else if (LoOverflow)
2658 return new SetCondInst(Instruction::SetGE, X, HiBound);
2659 else
2660 return InsertRangeTest(X, LoBound, HiBound, false, I);
2661 case Instruction::SetLT:
2662 if (LoOverflow)
2663 return ReplaceInstUsesWith(I, ConstantBool::False);
2664 return new SetCondInst(Instruction::SetLT, X, LoBound);
2665 case Instruction::SetGT:
2666 if (HiOverflow)
2667 return ReplaceInstUsesWith(I, ConstantBool::False);
2668 return new SetCondInst(Instruction::SetGE, X, HiBound);
2669 }
2670 }
2671 }
2672 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002673 case Instruction::Select:
2674 // If either operand of the select is a constant, we can fold the
2675 // comparison into the select arms, which will cause one to be
2676 // constant folded and the select turned into a bitwise or.
2677 Value *Op1 = 0, *Op2 = 0;
2678 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002679 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002680 // Fold the known value into the constant operand.
2681 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2682 // Insert a new SetCC of the other select operand.
2683 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002684 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002685 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002686 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002687 // Fold the known value into the constant operand.
2688 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2689 // Insert a new SetCC of the other select operand.
2690 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002691 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002692 I.getName()), I);
2693 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002694 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002695
2696 if (Op1)
2697 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2698 break;
2699 }
2700
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002701 // Simplify seteq and setne instructions...
2702 if (I.getOpcode() == Instruction::SetEQ ||
2703 I.getOpcode() == Instruction::SetNE) {
2704 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2705
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002706 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002707 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002708 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2709 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002710 case Instruction::Rem:
2711 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2712 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2713 BO->hasOneUse() &&
2714 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2715 if (unsigned L2 =
2716 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2717 const Type *UTy = BO->getType()->getUnsignedVersion();
2718 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2719 UTy, "tmp"), I);
2720 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2721 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2722 RHSCst, BO->getName()), I);
2723 return BinaryOperator::create(I.getOpcode(), NewRem,
2724 Constant::getNullValue(UTy));
2725 }
2726 break;
2727
Chris Lattnerc992add2003-08-13 05:33:12 +00002728 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002729 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2730 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002731 if (BO->hasOneUse())
2732 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2733 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002734 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002735 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2736 // efficiently invertible, or if the add has just this one use.
2737 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002738
Chris Lattnerc992add2003-08-13 05:33:12 +00002739 if (Value *NegVal = dyn_castNegVal(BOp1))
2740 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2741 else if (Value *NegVal = dyn_castNegVal(BOp0))
2742 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002743 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002744 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2745 BO->setName("");
2746 InsertNewInstBefore(Neg, I);
2747 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2748 }
2749 }
2750 break;
2751 case Instruction::Xor:
2752 // For the xor case, we can xor two constants together, eliminating
2753 // the explicit xor.
2754 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2755 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002756 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002757
2758 // FALLTHROUGH
2759 case Instruction::Sub:
2760 // Replace (([sub|xor] A, B) != 0) with (A != B)
2761 if (CI->isNullValue())
2762 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2763 BO->getOperand(1));
2764 break;
2765
2766 case Instruction::Or:
2767 // If bits are being or'd in that are not present in the constant we
2768 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002769 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002770 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002771 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002772 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002773 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002774 break;
2775
2776 case Instruction::And:
2777 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002778 // If bits are being compared against that are and'd out, then the
2779 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002780 if (!ConstantExpr::getAnd(CI,
2781 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002782 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002783
Chris Lattner35167c32004-06-09 07:59:58 +00002784 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002785 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002786 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2787 Instruction::SetNE, Op0,
2788 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002789
Chris Lattnerc992add2003-08-13 05:33:12 +00002790 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2791 // to be a signed value as appropriate.
2792 if (isSignBit(BOC)) {
2793 Value *X = BO->getOperand(0);
2794 // If 'X' is not signed, insert a cast now...
2795 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002796 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002797 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002798 }
2799 return new SetCondInst(isSetNE ? Instruction::SetLT :
2800 Instruction::SetGE, X,
2801 Constant::getNullValue(X->getType()));
2802 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002803
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002804 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002805 if (CI->isNullValue() && isHighOnes(BOC)) {
2806 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002807 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002808
2809 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002810 if (NegX->getType()->isSigned()) {
2811 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2812 X = InsertCastBefore(X, DestTy, I);
2813 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002814 }
2815
2816 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002817 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002818 }
2819
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002820 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002821 default: break;
2822 }
2823 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002824 } else { // Not a SetEQ/SetNE
2825 // If the LHS is a cast from an integral value of the same size,
2826 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2827 Value *CastOp = Cast->getOperand(0);
2828 const Type *SrcTy = CastOp->getType();
2829 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2830 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2831 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2832 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2833 "Source and destination signednesses should differ!");
2834 if (Cast->getType()->isSigned()) {
2835 // If this is a signed comparison, check for comparisons in the
2836 // vicinity of zero.
2837 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2838 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002839 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002840 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2841 else if (I.getOpcode() == Instruction::SetGT &&
2842 cast<ConstantSInt>(CI)->getValue() == -1)
2843 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002844 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002845 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2846 } else {
2847 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2848 if (I.getOpcode() == Instruction::SetLT &&
2849 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2850 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002851 return BinaryOperator::createSetGT(CastOp,
2852 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002853 else if (I.getOpcode() == Instruction::SetGT &&
2854 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2855 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002856 return BinaryOperator::createSetLT(CastOp,
2857 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002858 }
2859 }
2860 }
Chris Lattnere967b342003-06-04 05:10:11 +00002861 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002862 }
2863
Chris Lattner0798af32005-01-13 20:14:25 +00002864 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2865 if (User *GEP = dyn_castGetElementPtr(Op0))
2866 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2867 return NI;
2868 if (User *GEP = dyn_castGetElementPtr(Op1))
2869 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2870 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2871 return NI;
2872
Chris Lattner16930792003-11-03 04:25:02 +00002873 // Test to see if the operands of the setcc are casted versions of other
2874 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002875 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2876 Value *CastOp0 = CI->getOperand(0);
2877 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002878 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002879 (I.getOpcode() == Instruction::SetEQ ||
2880 I.getOpcode() == Instruction::SetNE)) {
2881 // We keep moving the cast from the left operand over to the right
2882 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002883 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002884
2885 // If operand #1 is a cast instruction, see if we can eliminate it as
2886 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002887 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2888 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002889 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002890 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002891
2892 // If Op1 is a constant, we can fold the cast into the constant.
2893 if (Op1->getType() != Op0->getType())
2894 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2895 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2896 } else {
2897 // Otherwise, cast the RHS right before the setcc
2898 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2899 InsertNewInstBefore(cast<Instruction>(Op1), I);
2900 }
2901 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2902 }
2903
Chris Lattner6444c372003-11-03 05:17:03 +00002904 // Handle the special case of: setcc (cast bool to X), <cst>
2905 // This comes up when you have code like
2906 // int X = A < B;
2907 // if (X) ...
2908 // For generality, we handle any zero-extension of any operand comparison
2909 // with a constant.
2910 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2911 const Type *SrcTy = CastOp0->getType();
2912 const Type *DestTy = Op0->getType();
2913 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2914 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2915 // Ok, we have an expansion of operand 0 into a new type. Get the
2916 // constant value, masink off bits which are not set in the RHS. These
2917 // could be set if the destination value is signed.
2918 uint64_t ConstVal = ConstantRHS->getRawValue();
2919 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2920
2921 // If the constant we are comparing it with has high bits set, which
2922 // don't exist in the original value, the values could never be equal,
2923 // because the source would be zero extended.
2924 unsigned SrcBits =
2925 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002926 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2927 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002928 switch (I.getOpcode()) {
2929 default: assert(0 && "Unknown comparison type!");
2930 case Instruction::SetEQ:
2931 return ReplaceInstUsesWith(I, ConstantBool::False);
2932 case Instruction::SetNE:
2933 return ReplaceInstUsesWith(I, ConstantBool::True);
2934 case Instruction::SetLT:
2935 case Instruction::SetLE:
2936 if (DestTy->isSigned() && HasSignBit)
2937 return ReplaceInstUsesWith(I, ConstantBool::False);
2938 return ReplaceInstUsesWith(I, ConstantBool::True);
2939 case Instruction::SetGT:
2940 case Instruction::SetGE:
2941 if (DestTy->isSigned() && HasSignBit)
2942 return ReplaceInstUsesWith(I, ConstantBool::True);
2943 return ReplaceInstUsesWith(I, ConstantBool::False);
2944 }
2945 }
2946
2947 // Otherwise, we can replace the setcc with a setcc of the smaller
2948 // operand value.
2949 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2950 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2951 }
2952 }
2953 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002954 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002955}
2956
Reid Spencer279fa252004-11-28 21:31:15 +00002957// visitSetCondInstWithCastAndConstant - this method is part of the
2958// visitSetCondInst method. It handles the situation where we have:
2959// (setcc (cast X to larger), CI)
2960// It tries to remove the cast and even the setcc if the CI value
2961// and range of the cast allow it.
2962Instruction *
2963InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2964 CastInst* LHSI,
2965 ConstantInt* CI) {
2966 const Type *SrcTy = LHSI->getOperand(0)->getType();
2967 const Type *DestTy = LHSI->getType();
Chris Lattner03f06f12005-01-17 03:20:02 +00002968 if (!SrcTy->isIntegral() || !DestTy->isIntegral())
2969 return 0;
2970
2971 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2972 unsigned DestBits = DestTy->getPrimitiveSize()*8;
2973 if (SrcTy == Type::BoolTy)
2974 SrcBits = 1;
2975 if (DestTy == Type::BoolTy)
2976 DestBits = 1;
2977 if (SrcBits < DestBits) {
2978 // There are fewer bits in the source of the cast than in the result
2979 // of the cast. Any other case doesn't matter because the constant
2980 // value won't have changed due to sign extension.
2981 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2982 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
2983 // The constant value operand of the setCC before and after a
2984 // cast to the source type of the cast instruction is the same
2985 // value, so we just replace with the same setcc opcode, but
2986 // using the source value compared to the constant casted to the
2987 // source type.
2988 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
2989 CastInst* Cst = new CastInst(LHSI->getOperand(0),
2990 SrcTy->getUnsignedVersion(),
2991 LHSI->getName());
2992 InsertNewInstBefore(Cst,I);
2993 return new SetCondInst(I.getOpcode(), Cst,
2994 ConstantExpr::getCast(CI,
2995 SrcTy->getUnsignedVersion()));
Reid Spencer279fa252004-11-28 21:31:15 +00002996 }
Chris Lattner03f06f12005-01-17 03:20:02 +00002997 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
2998 }
2999
3000 // The constant value before and after a cast to the source type
3001 // is different, so various cases are possible depending on the
3002 // opcode and the signs of the types involved in the cast.
3003 switch (I.getOpcode()) {
3004 case Instruction::SetLT: {
3005 return 0;
3006 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
3007 Max = ConstantExpr::getCast(Max, DestTy);
3008 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
3009 }
3010 case Instruction::SetGT: {
3011 return 0; // FIXME! RENABLE. This breaks for (cast sbyte to uint) > 255
3012 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
3013 Min = ConstantExpr::getCast(Min, DestTy);
3014 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
3015 }
3016 case Instruction::SetEQ:
3017 // We're looking for equality, and we know the values are not
3018 // equal so replace with constant False.
3019 return ReplaceInstUsesWith(I, ConstantBool::False);
3020 case Instruction::SetNE:
3021 // We're testing for inequality, and we know the values are not
3022 // equal so replace with constant True.
3023 return ReplaceInstUsesWith(I, ConstantBool::True);
3024 case Instruction::SetLE:
3025 case Instruction::SetGE:
3026 assert(0 && "SetLE and SetGE should be handled elsewhere");
3027 default:
3028 assert(0 && "unknown integer comparison");
Reid Spencer279fa252004-11-28 21:31:15 +00003029 }
3030 }
3031 return 0;
3032}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003033
3034
Chris Lattnere8d6c602003-03-10 19:16:08 +00003035Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00003036 assert(I.getOperand(1)->getType() == Type::UByteTy);
3037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003038 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003039
3040 // shl X, 0 == X and shr X, 0 == X
3041 // shl 0, X == 0 and shr 0, X == 0
3042 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00003043 Op0 == Constant::getNullValue(Op0->getType()))
3044 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003045
Chris Lattner81a7a232004-10-16 18:11:37 +00003046 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3047 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00003048 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00003049 else // undef << X -> 0 AND undef >>u X -> 0
3050 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3051 }
3052 if (isa<UndefValue>(Op1)) {
3053 if (isLeftShift || I.getType()->isUnsigned())
3054 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3055 else
3056 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3057 }
3058
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003059 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3060 if (!isLeftShift)
3061 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3062 if (CSI->isAllOnesValue())
3063 return ReplaceInstUsesWith(I, CSI);
3064
Chris Lattner183b3362004-04-09 19:05:30 +00003065 // Try to fold constant and into select arguments.
3066 if (isa<Constant>(Op0))
3067 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00003068 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003069 return R;
3070
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003071 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003072 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3073 // of a signed value.
3074 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00003075 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003076 if (CUI->getValue() >= TypeBits) {
3077 if (!Op0->getType()->isSigned() || isLeftShift)
3078 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3079 else {
3080 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3081 return &I;
3082 }
3083 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003084
Chris Lattnerede3fe02003-08-13 04:18:28 +00003085 // ((X*C1) << C2) == (X * (C1 << C2))
3086 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3087 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3088 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003089 return BinaryOperator::createMul(BO->getOperand(0),
3090 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00003091
Chris Lattner183b3362004-04-09 19:05:30 +00003092 // Try to fold constant and into select arguments.
3093 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003094 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003095 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003096 if (isa<PHINode>(Op0))
3097 if (Instruction *NV = FoldOpIntoPhi(I))
3098 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003099
Chris Lattner86102b82005-01-01 16:22:27 +00003100 if (Op0->hasOneUse()) {
3101 // If this is a SHL of a sign-extending cast, see if we can turn the input
3102 // into a zero extending cast (a simple strength reduction).
3103 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3104 const Type *SrcTy = CI->getOperand(0)->getType();
3105 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3106 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
3107 // We can change it to a zero extension if we are shifting out all of
3108 // the sign extended bits. To check this, form a mask of all of the
3109 // sign extend bits, then shift them left and see if we have anything
3110 // left.
3111 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3112 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3113 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3114 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3115 // If the shift is nuking all of the sign bits, change this to a
3116 // zero extension cast. To do this, cast the cast input to
3117 // unsigned, then to the requested size.
3118 Value *CastOp = CI->getOperand(0);
3119 Instruction *NC =
3120 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3121 CI->getName()+".uns");
3122 NC = InsertNewInstBefore(NC, I);
3123 // Finally, insert a replacement for CI.
3124 NC = new CastInst(NC, CI->getType(), CI->getName());
3125 CI->setName("");
3126 NC = InsertNewInstBefore(NC, I);
3127 WorkList.push_back(CI); // Delete CI later.
3128 I.setOperand(0, NC);
3129 return &I; // The SHL operand was modified.
3130 }
3131 }
3132 }
3133
3134 // If the operand is an bitwise operator with a constant RHS, and the
3135 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003136 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3137 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3138 bool isValid = true; // Valid only for And, Or, Xor
3139 bool highBitSet = false; // Transform if high bit of constant set?
3140
3141 switch (Op0BO->getOpcode()) {
3142 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003143 case Instruction::Add:
3144 isValid = isLeftShift;
3145 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003146 case Instruction::Or:
3147 case Instruction::Xor:
3148 highBitSet = false;
3149 break;
3150 case Instruction::And:
3151 highBitSet = true;
3152 break;
3153 }
3154
3155 // If this is a signed shift right, and the high bit is modified
3156 // by the logical operation, do not perform the transformation.
3157 // The highBitSet boolean indicates the value of the high bit of
3158 // the constant which would cause it to be modified for this
3159 // operation.
3160 //
3161 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3162 uint64_t Val = Op0C->getRawValue();
3163 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3164 }
3165
3166 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003167 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003168
3169 Instruction *NewShift =
3170 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3171 Op0BO->getName());
3172 Op0BO->setName("");
3173 InsertNewInstBefore(NewShift, I);
3174
3175 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3176 NewRHS);
3177 }
3178 }
Chris Lattner86102b82005-01-01 16:22:27 +00003179 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003180
Chris Lattner3204d4e2003-07-24 17:52:58 +00003181 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003182 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003183 if (ConstantUInt *ShiftAmt1C =
3184 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003185 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3186 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003187
3188 // Check for (A << c1) << c2 and (A >> c1) >> c2
3189 if (I.getOpcode() == Op0SI->getOpcode()) {
3190 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003191 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
3192 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00003193 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3194 ConstantUInt::get(Type::UByteTy, Amt));
3195 }
3196
Chris Lattnerab780df2003-07-24 18:38:56 +00003197 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3198 // signed types, we can only support the (A >> c1) << c2 configuration,
3199 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003200 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003201 // Calculate bitmask for what gets shifted off the edge...
3202 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003203 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003204 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003205 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003206 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00003207
3208 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003209 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3210 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003211 InsertNewInstBefore(Mask, I);
3212
3213 // Figure out what flavor of shift we should use...
3214 if (ShiftAmt1 == ShiftAmt2)
3215 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3216 else if (ShiftAmt1 < ShiftAmt2) {
3217 return new ShiftInst(I.getOpcode(), Mask,
3218 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3219 } else {
3220 return new ShiftInst(Op0SI->getOpcode(), Mask,
3221 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3222 }
3223 }
3224 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003225 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003226
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003227 return 0;
3228}
3229
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003230enum CastType {
3231 Noop = 0,
3232 Truncate = 1,
3233 Signext = 2,
3234 Zeroext = 3
3235};
3236
3237/// getCastType - In the future, we will split the cast instruction into these
3238/// various types. Until then, we have to do the analysis here.
3239static CastType getCastType(const Type *Src, const Type *Dest) {
3240 assert(Src->isIntegral() && Dest->isIntegral() &&
3241 "Only works on integral types!");
3242 unsigned SrcSize = Src->getPrimitiveSize()*8;
3243 if (Src == Type::BoolTy) SrcSize = 1;
3244 unsigned DestSize = Dest->getPrimitiveSize()*8;
3245 if (Dest == Type::BoolTy) DestSize = 1;
3246
3247 if (SrcSize == DestSize) return Noop;
3248 if (SrcSize > DestSize) return Truncate;
3249 if (Src->isSigned()) return Signext;
3250 return Zeroext;
3251}
3252
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003253
Chris Lattner48a44f72002-05-02 17:06:02 +00003254// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3255// instruction.
3256//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003257static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003258 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003259
Chris Lattner650b6da2002-08-02 20:00:25 +00003260 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3261 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003262 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003263 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003264 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003265
Chris Lattner4fbad962004-07-21 04:27:24 +00003266 // If we are casting between pointer and integer types, treat pointers as
3267 // integers of the appropriate size for the code below.
3268 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3269 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3270 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003271
Chris Lattner48a44f72002-05-02 17:06:02 +00003272 // Allow free casting and conversion of sizes as long as the sign doesn't
3273 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003274 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003275 CastType FirstCast = getCastType(SrcTy, MidTy);
3276 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003277
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003278 // Capture the effect of these two casts. If the result is a legal cast,
3279 // the CastType is stored here, otherwise a special code is used.
3280 static const unsigned CastResult[] = {
3281 // First cast is noop
3282 0, 1, 2, 3,
3283 // First cast is a truncate
3284 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3285 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003286 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003287 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003288 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003289 };
3290
3291 unsigned Result = CastResult[FirstCast*4+SecondCast];
3292 switch (Result) {
3293 default: assert(0 && "Illegal table value!");
3294 case 0:
3295 case 1:
3296 case 2:
3297 case 3:
3298 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3299 // truncates, we could eliminate more casts.
3300 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3301 case 4:
3302 return false; // Not possible to eliminate this here.
3303 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003304 // Sign or zero extend followed by truncate is always ok if the result
3305 // is a truncate or noop.
3306 CastType ResultCast = getCastType(SrcTy, DstTy);
3307 if (ResultCast == Noop || ResultCast == Truncate)
3308 return true;
3309 // Otherwise we are still growing the value, we are only safe if the
3310 // result will match the sign/zeroextendness of the result.
3311 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003312 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003313 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003314 return false;
3315}
3316
Chris Lattner11ffd592004-07-20 05:21:00 +00003317static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003318 if (V->getType() == Ty || isa<Constant>(V)) return false;
3319 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003320 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3321 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003322 return false;
3323 return true;
3324}
3325
3326/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3327/// InsertBefore instruction. This is specialized a bit to avoid inserting
3328/// casts that are known to not do anything...
3329///
3330Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3331 Instruction *InsertBefore) {
3332 if (V->getType() == DestTy) return V;
3333 if (Constant *C = dyn_cast<Constant>(V))
3334 return ConstantExpr::getCast(C, DestTy);
3335
3336 CastInst *CI = new CastInst(V, DestTy, V->getName());
3337 InsertNewInstBefore(CI, *InsertBefore);
3338 return CI;
3339}
Chris Lattner48a44f72002-05-02 17:06:02 +00003340
3341// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003342//
Chris Lattner113f4f42002-06-25 16:13:24 +00003343Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003344 Value *Src = CI.getOperand(0);
3345
Chris Lattner48a44f72002-05-02 17:06:02 +00003346 // If the user is casting a value to the same type, eliminate this cast
3347 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003348 if (CI.getType() == Src->getType())
3349 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003350
Chris Lattner81a7a232004-10-16 18:11:37 +00003351 if (isa<UndefValue>(Src)) // cast undef -> undef
3352 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3353
Chris Lattner48a44f72002-05-02 17:06:02 +00003354 // If casting the result of another cast instruction, try to eliminate this
3355 // one!
3356 //
Chris Lattner86102b82005-01-01 16:22:27 +00003357 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3358 Value *A = CSrc->getOperand(0);
3359 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3360 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003361 // This instruction now refers directly to the cast's src operand. This
3362 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003363 CI.setOperand(0, CSrc->getOperand(0));
3364 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003365 }
3366
Chris Lattner650b6da2002-08-02 20:00:25 +00003367 // If this is an A->B->A cast, and we are dealing with integral types, try
3368 // to convert this into a logical 'and' instruction.
3369 //
Chris Lattner86102b82005-01-01 16:22:27 +00003370 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003371 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003372 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
3373 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()&&
3374 A->getType()->getPrimitiveSize() == CI.getType()->getPrimitiveSize()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003375 assert(CSrc->getType() != Type::ULongTy &&
3376 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00003377 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner86102b82005-01-01 16:22:27 +00003378 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3379 AndValue);
3380 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3381 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3382 if (And->getType() != CI.getType()) {
3383 And->setName(CSrc->getName()+".mask");
3384 InsertNewInstBefore(And, CI);
3385 And = new CastInst(And, CI.getType());
3386 }
3387 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003388 }
3389 }
Chris Lattner86102b82005-01-01 16:22:27 +00003390
Chris Lattner03841652004-05-25 04:29:21 +00003391 // If this is a cast to bool, turn it into the appropriate setne instruction.
3392 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003393 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003394 Constant::getNullValue(CI.getOperand(0)->getType()));
3395
Chris Lattnerd0d51602003-06-21 23:12:02 +00003396 // If casting the result of a getelementptr instruction with no offset, turn
3397 // this into a cast of the original pointer!
3398 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003399 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003400 bool AllZeroOperands = true;
3401 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3402 if (!isa<Constant>(GEP->getOperand(i)) ||
3403 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3404 AllZeroOperands = false;
3405 break;
3406 }
3407 if (AllZeroOperands) {
3408 CI.setOperand(0, GEP->getOperand(0));
3409 return &CI;
3410 }
3411 }
3412
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003413 // If we are casting a malloc or alloca to a pointer to a type of the same
3414 // size, rewrite the allocation instruction to allocate the "right" type.
3415 //
3416 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003417 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003418 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3419 // Get the type really allocated and the type casted to...
3420 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003421 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003422 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003423 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3424 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003425
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003426 // If the allocation is for an even multiple of the cast type size
3427 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
3428 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003429 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003430 std::string Name = AI->getName(); AI->setName("");
3431 AllocationInst *New;
3432 if (isa<MallocInst>(AI))
3433 New = new MallocInst(CastElTy, Amt, Name);
3434 else
3435 New = new AllocaInst(CastElTy, Amt, Name);
3436 InsertNewInstBefore(New, *AI);
3437 return ReplaceInstUsesWith(CI, New);
3438 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003439 }
3440 }
3441
Chris Lattner86102b82005-01-01 16:22:27 +00003442 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3443 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3444 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003445 if (isa<PHINode>(Src))
3446 if (Instruction *NV = FoldOpIntoPhi(CI))
3447 return NV;
3448
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003449 // If the source value is an instruction with only this use, we can attempt to
3450 // propagate the cast into the instruction. Also, only handle integral types
3451 // for now.
3452 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003453 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003454 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3455 const Type *DestTy = CI.getType();
3456 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3457 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3458
3459 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3460 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3461
3462 switch (SrcI->getOpcode()) {
3463 case Instruction::Add:
3464 case Instruction::Mul:
3465 case Instruction::And:
3466 case Instruction::Or:
3467 case Instruction::Xor:
3468 // If we are discarding information, or just changing the sign, rewrite.
3469 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3470 // Don't insert two casts if they cannot be eliminated. We allow two
3471 // casts to be inserted if the sizes are the same. This could only be
3472 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003473 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3474 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003475 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3476 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3477 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3478 ->getOpcode(), Op0c, Op1c);
3479 }
3480 }
3481 break;
3482 case Instruction::Shl:
3483 // Allow changing the sign of the source operand. Do not allow changing
3484 // the size of the shift, UNLESS the shift amount is a constant. We
3485 // mush not change variable sized shifts to a smaller size, because it
3486 // is undefined to shift more bits out than exist in the value.
3487 if (DestBitSize == SrcBitSize ||
3488 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3489 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3490 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3491 }
3492 break;
3493 }
3494 }
3495
Chris Lattner260ab202002-04-18 17:39:14 +00003496 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003497}
3498
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003499/// GetSelectFoldableOperands - We want to turn code that looks like this:
3500/// %C = or %A, %B
3501/// %D = select %cond, %C, %A
3502/// into:
3503/// %C = select %cond, %B, 0
3504/// %D = or %A, %C
3505///
3506/// Assuming that the specified instruction is an operand to the select, return
3507/// a bitmask indicating which operands of this instruction are foldable if they
3508/// equal the other incoming value of the select.
3509///
3510static unsigned GetSelectFoldableOperands(Instruction *I) {
3511 switch (I->getOpcode()) {
3512 case Instruction::Add:
3513 case Instruction::Mul:
3514 case Instruction::And:
3515 case Instruction::Or:
3516 case Instruction::Xor:
3517 return 3; // Can fold through either operand.
3518 case Instruction::Sub: // Can only fold on the amount subtracted.
3519 case Instruction::Shl: // Can only fold on the shift amount.
3520 case Instruction::Shr:
3521 return 1;
3522 default:
3523 return 0; // Cannot fold
3524 }
3525}
3526
3527/// GetSelectFoldableConstant - For the same transformation as the previous
3528/// function, return the identity constant that goes into the select.
3529static Constant *GetSelectFoldableConstant(Instruction *I) {
3530 switch (I->getOpcode()) {
3531 default: assert(0 && "This cannot happen!"); abort();
3532 case Instruction::Add:
3533 case Instruction::Sub:
3534 case Instruction::Or:
3535 case Instruction::Xor:
3536 return Constant::getNullValue(I->getType());
3537 case Instruction::Shl:
3538 case Instruction::Shr:
3539 return Constant::getNullValue(Type::UByteTy);
3540 case Instruction::And:
3541 return ConstantInt::getAllOnesValue(I->getType());
3542 case Instruction::Mul:
3543 return ConstantInt::get(I->getType(), 1);
3544 }
3545}
3546
Chris Lattner411336f2005-01-19 21:50:18 +00003547/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
3548/// have the same opcode and only one use each. Try to simplify this.
3549Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
3550 Instruction *FI) {
3551 if (TI->getNumOperands() == 1) {
3552 // If this is a non-volatile load or a cast from the same type,
3553 // merge.
3554 if (TI->getOpcode() == Instruction::Cast) {
3555 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
3556 return 0;
3557 } else {
3558 return 0; // unknown unary op.
3559 }
3560
3561 // Fold this by inserting a select from the input values.
3562 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
3563 FI->getOperand(0), SI.getName()+".v");
3564 InsertNewInstBefore(NewSI, SI);
3565 return new CastInst(NewSI, TI->getType());
3566 }
3567
3568 // Only handle binary operators here.
3569 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
3570 return 0;
3571
3572 // Figure out if the operations have any operands in common.
3573 Value *MatchOp, *OtherOpT, *OtherOpF;
3574 bool MatchIsOpZero;
3575 if (TI->getOperand(0) == FI->getOperand(0)) {
3576 MatchOp = TI->getOperand(0);
3577 OtherOpT = TI->getOperand(1);
3578 OtherOpF = FI->getOperand(1);
3579 MatchIsOpZero = true;
3580 } else if (TI->getOperand(1) == FI->getOperand(1)) {
3581 MatchOp = TI->getOperand(1);
3582 OtherOpT = TI->getOperand(0);
3583 OtherOpF = FI->getOperand(0);
3584 MatchIsOpZero = false;
3585 } else if (!TI->isCommutative()) {
3586 return 0;
3587 } else if (TI->getOperand(0) == FI->getOperand(1)) {
3588 MatchOp = TI->getOperand(0);
3589 OtherOpT = TI->getOperand(1);
3590 OtherOpF = FI->getOperand(0);
3591 MatchIsOpZero = true;
3592 } else if (TI->getOperand(1) == FI->getOperand(0)) {
3593 MatchOp = TI->getOperand(1);
3594 OtherOpT = TI->getOperand(0);
3595 OtherOpF = FI->getOperand(1);
3596 MatchIsOpZero = true;
3597 } else {
3598 return 0;
3599 }
3600
3601 // If we reach here, they do have operations in common.
3602 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
3603 OtherOpF, SI.getName()+".v");
3604 InsertNewInstBefore(NewSI, SI);
3605
3606 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
3607 if (MatchIsOpZero)
3608 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
3609 else
3610 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
3611 } else {
3612 if (MatchIsOpZero)
3613 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
3614 else
3615 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
3616 }
3617}
3618
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003619Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003620 Value *CondVal = SI.getCondition();
3621 Value *TrueVal = SI.getTrueValue();
3622 Value *FalseVal = SI.getFalseValue();
3623
3624 // select true, X, Y -> X
3625 // select false, X, Y -> Y
3626 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003627 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003628 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003629 else {
3630 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003631 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003632 }
Chris Lattner533bc492004-03-30 19:37:13 +00003633
3634 // select C, X, X -> X
3635 if (TrueVal == FalseVal)
3636 return ReplaceInstUsesWith(SI, TrueVal);
3637
Chris Lattner81a7a232004-10-16 18:11:37 +00003638 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3639 return ReplaceInstUsesWith(SI, FalseVal);
3640 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3641 return ReplaceInstUsesWith(SI, TrueVal);
3642 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3643 if (isa<Constant>(TrueVal))
3644 return ReplaceInstUsesWith(SI, TrueVal);
3645 else
3646 return ReplaceInstUsesWith(SI, FalseVal);
3647 }
3648
Chris Lattner1c631e82004-04-08 04:43:23 +00003649 if (SI.getType() == Type::BoolTy)
3650 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3651 if (C == ConstantBool::True) {
3652 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003653 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003654 } else {
3655 // Change: A = select B, false, C --> A = and !B, C
3656 Value *NotCond =
3657 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3658 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003659 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003660 }
3661 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3662 if (C == ConstantBool::False) {
3663 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003664 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003665 } else {
3666 // Change: A = select B, C, true --> A = or !B, C
3667 Value *NotCond =
3668 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3669 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003670 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003671 }
3672 }
3673
Chris Lattner183b3362004-04-09 19:05:30 +00003674 // Selecting between two integer constants?
3675 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3676 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3677 // select C, 1, 0 -> cast C to int
3678 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3679 return new CastInst(CondVal, SI.getType());
3680 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3681 // select C, 0, 1 -> cast !C to int
3682 Value *NotCond =
3683 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003684 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003685 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003686 }
Chris Lattner35167c32004-06-09 07:59:58 +00003687
3688 // If one of the constants is zero (we know they can't both be) and we
3689 // have a setcc instruction with zero, and we have an 'and' with the
3690 // non-constant value, eliminate this whole mess. This corresponds to
3691 // cases like this: ((X & 27) ? 27 : 0)
3692 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3693 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3694 if ((IC->getOpcode() == Instruction::SetEQ ||
3695 IC->getOpcode() == Instruction::SetNE) &&
3696 isa<ConstantInt>(IC->getOperand(1)) &&
3697 cast<Constant>(IC->getOperand(1))->isNullValue())
3698 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3699 if (ICA->getOpcode() == Instruction::And &&
3700 isa<ConstantInt>(ICA->getOperand(1)) &&
3701 (ICA->getOperand(1) == TrueValC ||
3702 ICA->getOperand(1) == FalseValC) &&
3703 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3704 // Okay, now we know that everything is set up, we just don't
3705 // know whether we have a setne or seteq and whether the true or
3706 // false val is the zero.
3707 bool ShouldNotVal = !TrueValC->isNullValue();
3708 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3709 Value *V = ICA;
3710 if (ShouldNotVal)
3711 V = InsertNewInstBefore(BinaryOperator::create(
3712 Instruction::Xor, V, ICA->getOperand(1)), SI);
3713 return ReplaceInstUsesWith(SI, V);
3714 }
Chris Lattner533bc492004-03-30 19:37:13 +00003715 }
Chris Lattner623fba12004-04-10 22:21:27 +00003716
3717 // See if we are selecting two values based on a comparison of the two values.
3718 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3719 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3720 // Transform (X == Y) ? X : Y -> Y
3721 if (SCI->getOpcode() == Instruction::SetEQ)
3722 return ReplaceInstUsesWith(SI, FalseVal);
3723 // Transform (X != Y) ? X : Y -> X
3724 if (SCI->getOpcode() == Instruction::SetNE)
3725 return ReplaceInstUsesWith(SI, TrueVal);
3726 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3727
3728 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3729 // Transform (X == Y) ? Y : X -> X
3730 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003731 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003732 // Transform (X != Y) ? Y : X -> Y
3733 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003734 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003735 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3736 }
3737 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003738
Chris Lattnera04c9042005-01-13 22:52:24 +00003739 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3740 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3741 if (TI->hasOneUse() && FI->hasOneUse()) {
3742 bool isInverse = false;
3743 Instruction *AddOp = 0, *SubOp = 0;
3744
Chris Lattner411336f2005-01-19 21:50:18 +00003745 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
3746 if (TI->getOpcode() == FI->getOpcode())
3747 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
3748 return IV;
3749
3750 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
3751 // even legal for FP.
Chris Lattnera04c9042005-01-13 22:52:24 +00003752 if (TI->getOpcode() == Instruction::Sub &&
3753 FI->getOpcode() == Instruction::Add) {
3754 AddOp = FI; SubOp = TI;
3755 } else if (FI->getOpcode() == Instruction::Sub &&
3756 TI->getOpcode() == Instruction::Add) {
3757 AddOp = TI; SubOp = FI;
3758 }
3759
3760 if (AddOp) {
3761 Value *OtherAddOp = 0;
3762 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3763 OtherAddOp = AddOp->getOperand(1);
3764 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3765 OtherAddOp = AddOp->getOperand(0);
3766 }
3767
3768 if (OtherAddOp) {
3769 // So at this point we know we have:
3770 // select C, (add X, Y), (sub X, ?)
3771 // We can do the transform profitably if either 'Y' = '?' or '?' is
3772 // a constant.
3773 if (SubOp->getOperand(1) == AddOp ||
3774 isa<Constant>(SubOp->getOperand(1))) {
3775 Value *NegVal;
3776 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3777 NegVal = ConstantExpr::getNeg(C);
3778 } else {
3779 NegVal = InsertNewInstBefore(
3780 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3781 }
3782
Chris Lattner51726c42005-01-14 17:35:12 +00003783 Value *NewTrueOp = OtherAddOp;
Chris Lattnera04c9042005-01-13 22:52:24 +00003784 Value *NewFalseOp = NegVal;
3785 if (AddOp != TI)
3786 std::swap(NewTrueOp, NewFalseOp);
3787 Instruction *NewSel =
3788 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
3789
3790 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner51726c42005-01-14 17:35:12 +00003791 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattnera04c9042005-01-13 22:52:24 +00003792 }
3793 }
3794 }
3795 }
3796
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003797 // See if we can fold the select into one of our operands.
3798 if (SI.getType()->isInteger()) {
3799 // See the comment above GetSelectFoldableOperands for a description of the
3800 // transformation we are doing here.
3801 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3802 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3803 !isa<Constant>(FalseVal))
3804 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3805 unsigned OpToFold = 0;
3806 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3807 OpToFold = 1;
3808 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3809 OpToFold = 2;
3810 }
3811
3812 if (OpToFold) {
3813 Constant *C = GetSelectFoldableConstant(TVI);
3814 std::string Name = TVI->getName(); TVI->setName("");
3815 Instruction *NewSel =
3816 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3817 Name);
3818 InsertNewInstBefore(NewSel, SI);
3819 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3820 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3821 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3822 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3823 else {
3824 assert(0 && "Unknown instruction!!");
3825 }
3826 }
3827 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003828
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003829 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3830 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3831 !isa<Constant>(TrueVal))
3832 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3833 unsigned OpToFold = 0;
3834 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3835 OpToFold = 1;
3836 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3837 OpToFold = 2;
3838 }
3839
3840 if (OpToFold) {
3841 Constant *C = GetSelectFoldableConstant(FVI);
3842 std::string Name = FVI->getName(); FVI->setName("");
3843 Instruction *NewSel =
3844 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3845 Name);
3846 InsertNewInstBefore(NewSel, SI);
3847 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3848 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3849 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3850 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3851 else {
3852 assert(0 && "Unknown instruction!!");
3853 }
3854 }
3855 }
3856 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003857 return 0;
3858}
3859
3860
Chris Lattner970c33a2003-06-19 17:00:31 +00003861// CallInst simplification
3862//
3863Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003864 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3865 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003866 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3867 bool Changed = false;
3868
3869 // memmove/cpy/set of zero bytes is a noop.
3870 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3871 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3872
3873 // FIXME: Increase alignment here.
3874
3875 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3876 if (CI->getRawValue() == 1) {
3877 // Replace the instruction with just byte operations. We would
3878 // transform other cases to loads/stores, but we don't know if
3879 // alignment is sufficient.
3880 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003881 }
3882
Chris Lattner00648e12004-10-12 04:52:52 +00003883 // If we have a memmove and the source operation is a constant global,
3884 // then the source and dest pointers can't alias, so we can change this
3885 // into a call to memcpy.
3886 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3887 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3888 if (GVSrc->isConstant()) {
3889 Module *M = CI.getParent()->getParent()->getParent();
3890 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3891 CI.getCalledFunction()->getFunctionType());
3892 CI.setOperand(0, MemCpy);
3893 Changed = true;
3894 }
3895
3896 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003897 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3898 // If this stoppoint is at the same source location as the previous
3899 // stoppoint in the chain, it is not needed.
3900 if (DbgStopPointInst *PrevSPI =
3901 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3902 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3903 SPI->getColNo() == PrevSPI->getColNo()) {
3904 SPI->replaceAllUsesWith(PrevSPI);
3905 return EraseInstFromFunction(CI);
3906 }
Chris Lattner00648e12004-10-12 04:52:52 +00003907 }
3908
Chris Lattneraec3d942003-10-07 22:32:43 +00003909 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003910}
3911
3912// InvokeInst simplification
3913//
3914Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003915 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003916}
3917
Chris Lattneraec3d942003-10-07 22:32:43 +00003918// visitCallSite - Improvements for call and invoke instructions.
3919//
3920Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003921 bool Changed = false;
3922
3923 // If the callee is a constexpr cast of a function, attempt to move the cast
3924 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003925 if (transformConstExprCastCall(CS)) return 0;
3926
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003927 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003928
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003929 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3930 // This instruction is not reachable, just remove it. We insert a store to
3931 // undef so that we know that this code is not reachable, despite the fact
3932 // that we can't modify the CFG here.
3933 new StoreInst(ConstantBool::True,
3934 UndefValue::get(PointerType::get(Type::BoolTy)),
3935 CS.getInstruction());
3936
3937 if (!CS.getInstruction()->use_empty())
3938 CS.getInstruction()->
3939 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3940
3941 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3942 // Don't break the CFG, insert a dummy cond branch.
3943 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3944 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003945 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003946 return EraseInstFromFunction(*CS.getInstruction());
3947 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003948
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003949 const PointerType *PTy = cast<PointerType>(Callee->getType());
3950 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3951 if (FTy->isVarArg()) {
3952 // See if we can optimize any arguments passed through the varargs area of
3953 // the call.
3954 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3955 E = CS.arg_end(); I != E; ++I)
3956 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3957 // If this cast does not effect the value passed through the varargs
3958 // area, we can eliminate the use of the cast.
3959 Value *Op = CI->getOperand(0);
3960 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3961 *I = Op;
3962 Changed = true;
3963 }
3964 }
3965 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003966
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003967 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003968}
3969
Chris Lattner970c33a2003-06-19 17:00:31 +00003970// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3971// attempt to move the cast to the arguments of the call/invoke.
3972//
3973bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3974 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3975 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003976 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003977 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003978 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003979 Instruction *Caller = CS.getInstruction();
3980
3981 // Okay, this is a cast from a function to a different type. Unless doing so
3982 // would cause a type conversion of one of our arguments, change this call to
3983 // be a direct call with arguments casted to the appropriate types.
3984 //
3985 const FunctionType *FT = Callee->getFunctionType();
3986 const Type *OldRetTy = Caller->getType();
3987
Chris Lattner1f7942f2004-01-14 06:06:08 +00003988 // Check to see if we are changing the return type...
3989 if (OldRetTy != FT->getReturnType()) {
3990 if (Callee->isExternal() &&
3991 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3992 !Caller->use_empty())
3993 return false; // Cannot transform this return value...
3994
3995 // If the callsite is an invoke instruction, and the return value is used by
3996 // a PHI node in a successor, we cannot change the return type of the call
3997 // because there is no place to put the cast instruction (without breaking
3998 // the critical edge). Bail out in this case.
3999 if (!Caller->use_empty())
4000 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4001 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4002 UI != E; ++UI)
4003 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4004 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004005 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00004006 return false;
4007 }
Chris Lattner970c33a2003-06-19 17:00:31 +00004008
4009 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4010 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4011
4012 CallSite::arg_iterator AI = CS.arg_begin();
4013 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4014 const Type *ParamTy = FT->getParamType(i);
4015 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
4016 if (Callee->isExternal() && !isConvertible) return false;
4017 }
4018
4019 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4020 Callee->isExternal())
4021 return false; // Do not delete arguments unless we have a function body...
4022
4023 // Okay, we decided that this is a safe thing to do: go ahead and start
4024 // inserting cast instructions as necessary...
4025 std::vector<Value*> Args;
4026 Args.reserve(NumActualArgs);
4027
4028 AI = CS.arg_begin();
4029 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4030 const Type *ParamTy = FT->getParamType(i);
4031 if ((*AI)->getType() == ParamTy) {
4032 Args.push_back(*AI);
4033 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00004034 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4035 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00004036 }
4037 }
4038
4039 // If the function takes more arguments than the call was taking, add them
4040 // now...
4041 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4042 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4043
4044 // If we are removing arguments to the function, emit an obnoxious warning...
4045 if (FT->getNumParams() < NumActualArgs)
4046 if (!FT->isVarArg()) {
4047 std::cerr << "WARNING: While resolving call to function '"
4048 << Callee->getName() << "' arguments were dropped!\n";
4049 } else {
4050 // Add all of the arguments in their promoted form to the arg list...
4051 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4052 const Type *PTy = getPromotedType((*AI)->getType());
4053 if (PTy != (*AI)->getType()) {
4054 // Must promote to pass through va_arg area!
4055 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4056 InsertNewInstBefore(Cast, *Caller);
4057 Args.push_back(Cast);
4058 } else {
4059 Args.push_back(*AI);
4060 }
4061 }
4062 }
4063
4064 if (FT->getReturnType() == Type::VoidTy)
4065 Caller->setName(""); // Void type should not have a name...
4066
4067 Instruction *NC;
4068 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00004069 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00004070 Args, Caller->getName(), Caller);
4071 } else {
4072 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4073 }
4074
4075 // Insert a cast of the return type as necessary...
4076 Value *NV = NC;
4077 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4078 if (NV->getType() != Type::VoidTy) {
4079 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00004080
4081 // If this is an invoke instruction, we should insert it after the first
4082 // non-phi, instruction in the normal successor block.
4083 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4084 BasicBlock::iterator I = II->getNormalDest()->begin();
4085 while (isa<PHINode>(I)) ++I;
4086 InsertNewInstBefore(NC, *I);
4087 } else {
4088 // Otherwise, it's a call, just insert cast right after the call instr
4089 InsertNewInstBefore(NC, *Caller);
4090 }
Chris Lattner51ea1272004-02-28 05:22:00 +00004091 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00004092 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00004093 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00004094 }
4095 }
4096
4097 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4098 Caller->replaceAllUsesWith(NV);
4099 Caller->getParent()->getInstList().erase(Caller);
4100 removeFromWorkList(Caller);
4101 return true;
4102}
4103
4104
Chris Lattner7515cab2004-11-14 19:13:23 +00004105// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4106// operator and they all are only used by the PHI, PHI together their
4107// inputs, and do the operation once, to the result of the PHI.
4108Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4109 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4110
4111 // Scan the instruction, looking for input operations that can be folded away.
4112 // If all input operands to the phi are the same instruction (e.g. a cast from
4113 // the same type or "+42") we can pull the operation through the PHI, reducing
4114 // code size and simplifying code.
4115 Constant *ConstantOp = 0;
4116 const Type *CastSrcTy = 0;
4117 if (isa<CastInst>(FirstInst)) {
4118 CastSrcTy = FirstInst->getOperand(0)->getType();
4119 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4120 // Can fold binop or shift if the RHS is a constant.
4121 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4122 if (ConstantOp == 0) return 0;
4123 } else {
4124 return 0; // Cannot fold this operation.
4125 }
4126
4127 // Check to see if all arguments are the same operation.
4128 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4129 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4130 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4131 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4132 return 0;
4133 if (CastSrcTy) {
4134 if (I->getOperand(0)->getType() != CastSrcTy)
4135 return 0; // Cast operation must match.
4136 } else if (I->getOperand(1) != ConstantOp) {
4137 return 0;
4138 }
4139 }
4140
4141 // Okay, they are all the same operation. Create a new PHI node of the
4142 // correct type, and PHI together all of the LHS's of the instructions.
4143 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4144 PN.getName()+".in");
Chris Lattnerd8e20182005-01-29 00:39:08 +00004145 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattner46dd5a62004-11-14 19:29:34 +00004146
4147 Value *InVal = FirstInst->getOperand(0);
4148 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00004149
4150 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00004151 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4152 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4153 if (NewInVal != InVal)
4154 InVal = 0;
4155 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4156 }
4157
4158 Value *PhiVal;
4159 if (InVal) {
4160 // The new PHI unions all of the same values together. This is really
4161 // common, so we handle it intelligently here for compile-time speed.
4162 PhiVal = InVal;
4163 delete NewPN;
4164 } else {
4165 InsertNewInstBefore(NewPN, PN);
4166 PhiVal = NewPN;
4167 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004168
4169 // Insert and return the new operation.
4170 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004171 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004172 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004173 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004174 else
4175 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004176 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004177}
Chris Lattner48a44f72002-05-02 17:06:02 +00004178
Chris Lattner71536432005-01-17 05:10:15 +00004179/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4180/// that is dead.
4181static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4182 if (PN->use_empty()) return true;
4183 if (!PN->hasOneUse()) return false;
4184
4185 // Remember this node, and if we find the cycle, return.
4186 if (!PotentiallyDeadPHIs.insert(PN).second)
4187 return true;
4188
4189 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4190 return DeadPHICycle(PU, PotentiallyDeadPHIs);
4191
4192 return false;
4193}
4194
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004195// PHINode simplification
4196//
Chris Lattner113f4f42002-06-25 16:13:24 +00004197Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00004198 if (Value *V = hasConstantValue(&PN)) {
4199 // If V is an instruction, we have to be certain that it dominates PN.
4200 // However, because we don't have dom info, we can't do a perfect job.
4201 if (Instruction *I = dyn_cast<Instruction>(V)) {
4202 // We know that the instruction dominates the PHI if there are no undef
4203 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00004204 if (I->getParent() != &I->getParent()->getParent()->front() ||
4205 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00004206 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4207 if (isa<UndefValue>(PN.getIncomingValue(i))) {
4208 V = 0;
4209 break;
4210 }
Chris Lattnere29d6342004-10-17 21:22:38 +00004211 }
4212
4213 if (V)
4214 return ReplaceInstUsesWith(PN, V);
4215 }
Chris Lattner4db2d222004-02-16 05:07:08 +00004216
4217 // If the only user of this instruction is a cast instruction, and all of the
4218 // incoming values are constants, change this PHI to merge together the casted
4219 // constants.
4220 if (PN.hasOneUse())
4221 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4222 if (CI->getType() != PN.getType()) { // noop casts will be folded
4223 bool AllConstant = true;
4224 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4225 if (!isa<Constant>(PN.getIncomingValue(i))) {
4226 AllConstant = false;
4227 break;
4228 }
4229 if (AllConstant) {
4230 // Make a new PHI with all casted values.
4231 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4232 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4233 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4234 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4235 PN.getIncomingBlock(i));
4236 }
4237
4238 // Update the cast instruction.
4239 CI->setOperand(0, New);
4240 WorkList.push_back(CI); // revisit the cast instruction to fold.
4241 WorkList.push_back(New); // Make sure to revisit the new Phi
4242 return &PN; // PN is now dead!
4243 }
4244 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004245
4246 // If all PHI operands are the same operation, pull them through the PHI,
4247 // reducing code size.
4248 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4249 PN.getIncomingValue(0)->hasOneUse())
4250 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4251 return Result;
4252
Chris Lattner71536432005-01-17 05:10:15 +00004253 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4254 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4255 // PHI)... break the cycle.
4256 if (PN.hasOneUse())
4257 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4258 std::set<PHINode*> PotentiallyDeadPHIs;
4259 PotentiallyDeadPHIs.insert(&PN);
4260 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4261 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4262 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004263
Chris Lattner91daeb52003-12-19 05:58:40 +00004264 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004265}
4266
Chris Lattner69193f92004-04-05 01:30:19 +00004267static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4268 Instruction *InsertPoint,
4269 InstCombiner *IC) {
4270 unsigned PS = IC->getTargetData().getPointerSize();
4271 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004272 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4273 // We must insert a cast to ensure we sign-extend.
4274 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4275 V->getName()), *InsertPoint);
4276 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4277 *InsertPoint);
4278}
4279
Chris Lattner48a44f72002-05-02 17:06:02 +00004280
Chris Lattner113f4f42002-06-25 16:13:24 +00004281Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004282 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004283 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004284 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004285 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004286 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004287
Chris Lattner81a7a232004-10-16 18:11:37 +00004288 if (isa<UndefValue>(GEP.getOperand(0)))
4289 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4290
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004291 bool HasZeroPointerIndex = false;
4292 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4293 HasZeroPointerIndex = C->isNullValue();
4294
4295 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004296 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004297
Chris Lattner69193f92004-04-05 01:30:19 +00004298 // Eliminate unneeded casts for indices.
4299 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004300 gep_type_iterator GTI = gep_type_begin(GEP);
4301 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4302 if (isa<SequentialType>(*GTI)) {
4303 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4304 Value *Src = CI->getOperand(0);
4305 const Type *SrcTy = Src->getType();
4306 const Type *DestTy = CI->getType();
4307 if (Src->getType()->isInteger()) {
4308 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
4309 // We can always eliminate a cast from ulong or long to the other.
4310 // We can always eliminate a cast from uint to int or the other on
4311 // 32-bit pointer platforms.
4312 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
4313 MadeChange = true;
4314 GEP.setOperand(i, Src);
4315 }
4316 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4317 SrcTy->getPrimitiveSize() == 4) {
4318 // We can always eliminate a cast from int to [u]long. We can
4319 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4320 // pointer target.
4321 if (SrcTy->isSigned() ||
4322 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
4323 MadeChange = true;
4324 GEP.setOperand(i, Src);
4325 }
Chris Lattner69193f92004-04-05 01:30:19 +00004326 }
4327 }
4328 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004329 // If we are using a wider index than needed for this platform, shrink it
4330 // to what we need. If the incoming value needs a cast instruction,
4331 // insert it. This explicit cast can make subsequent optimizations more
4332 // obvious.
4333 Value *Op = GEP.getOperand(i);
4334 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004335 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004336 GEP.setOperand(i, ConstantExpr::getCast(C,
4337 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004338 MadeChange = true;
4339 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004340 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4341 Op->getName()), GEP);
4342 GEP.setOperand(i, Op);
4343 MadeChange = true;
4344 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004345
4346 // If this is a constant idx, make sure to canonicalize it to be a signed
4347 // operand, otherwise CSE and other optimizations are pessimized.
4348 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4349 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4350 CUI->getType()->getSignedVersion()));
4351 MadeChange = true;
4352 }
Chris Lattner69193f92004-04-05 01:30:19 +00004353 }
4354 if (MadeChange) return &GEP;
4355
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004356 // Combine Indices - If the source pointer to this getelementptr instruction
4357 // is a getelementptr instruction, combine the indices of the two
4358 // getelementptr instructions into a single instruction.
4359 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004360 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004361 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004362 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004363
4364 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004365 // Note that if our source is a gep chain itself that we wait for that
4366 // chain to be resolved before we perform this transformation. This
4367 // avoids us creating a TON of code in some cases.
4368 //
4369 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4370 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4371 return 0; // Wait until our source is folded to completion.
4372
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004373 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004374
4375 // Find out whether the last index in the source GEP is a sequential idx.
4376 bool EndsWithSequential = false;
4377 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4378 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004379 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00004380
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004381 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004382 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004383 // Replace: gep (gep %P, long B), long A, ...
4384 // With: T = long A+B; gep %P, T, ...
4385 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004386 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004387 if (SO1 == Constant::getNullValue(SO1->getType())) {
4388 Sum = GO1;
4389 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4390 Sum = SO1;
4391 } else {
4392 // If they aren't the same type, convert both to an integer of the
4393 // target's pointer size.
4394 if (SO1->getType() != GO1->getType()) {
4395 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4396 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4397 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4398 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4399 } else {
4400 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004401 if (SO1->getType()->getPrimitiveSize() == PS) {
4402 // Convert GO1 to SO1's type.
4403 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4404
4405 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4406 // Convert SO1 to GO1's type.
4407 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4408 } else {
4409 const Type *PT = TD->getIntPtrType();
4410 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4411 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4412 }
4413 }
4414 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004415 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4416 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4417 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004418 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4419 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004420 }
Chris Lattner69193f92004-04-05 01:30:19 +00004421 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004422
4423 // Recycle the GEP we already have if possible.
4424 if (SrcGEPOperands.size() == 2) {
4425 GEP.setOperand(0, SrcGEPOperands[0]);
4426 GEP.setOperand(1, Sum);
4427 return &GEP;
4428 } else {
4429 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4430 SrcGEPOperands.end()-1);
4431 Indices.push_back(Sum);
4432 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4433 }
Chris Lattner69193f92004-04-05 01:30:19 +00004434 } else if (isa<Constant>(*GEP.idx_begin()) &&
4435 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00004436 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004437 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004438 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4439 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004440 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4441 }
4442
4443 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004444 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004445
Chris Lattner5f667a62004-05-07 22:09:22 +00004446 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004447 // GEP of global variable. If all of the indices for this GEP are
4448 // constants, we can promote this to a constexpr instead of an instruction.
4449
4450 // Scan for nonconstants...
4451 std::vector<Constant*> Indices;
4452 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4453 for (; I != E && isa<Constant>(*I); ++I)
4454 Indices.push_back(cast<Constant>(*I));
4455
4456 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004457 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004458
4459 // Replace all uses of the GEP with the new constexpr...
4460 return ReplaceInstUsesWith(GEP, CE);
4461 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004462 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004463 if (CE->getOpcode() == Instruction::Cast) {
4464 if (HasZeroPointerIndex) {
4465 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4466 // into : GEP [10 x ubyte]* X, long 0, ...
4467 //
4468 // This occurs when the program declares an array extern like "int X[];"
4469 //
4470 Constant *X = CE->getOperand(0);
4471 const PointerType *CPTy = cast<PointerType>(CE->getType());
4472 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4473 if (const ArrayType *XATy =
4474 dyn_cast<ArrayType>(XTy->getElementType()))
4475 if (const ArrayType *CATy =
4476 dyn_cast<ArrayType>(CPTy->getElementType()))
4477 if (CATy->getElementType() == XATy->getElementType()) {
4478 // At this point, we know that the cast source type is a pointer
4479 // to an array of the same type as the destination pointer
4480 // array. Because the array type is never stepped over (there
4481 // is a leading zero) we can fold the cast into this GEP.
4482 GEP.setOperand(0, X);
4483 return &GEP;
4484 }
Chris Lattner0798af32005-01-13 20:14:25 +00004485 } else if (GEP.getNumOperands() == 2 &&
4486 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004487 // Transform things like:
4488 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4489 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4490 Constant *X = CE->getOperand(0);
4491 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4492 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4493 if (isa<ArrayType>(SrcElTy) &&
4494 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4495 TD->getTypeSize(ResElTy)) {
4496 Value *V = InsertNewInstBefore(
4497 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4498 GEP.getOperand(1), GEP.getName()), GEP);
4499 return new CastInst(V, GEP.getType());
4500 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004501 }
4502 }
Chris Lattnerca081252001-12-14 16:52:21 +00004503 }
4504
Chris Lattnerca081252001-12-14 16:52:21 +00004505 return 0;
4506}
4507
Chris Lattner1085bdf2002-11-04 16:18:53 +00004508Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4509 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4510 if (AI.isArrayAllocation()) // Check C != 1
4511 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4512 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004513 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004514
4515 // Create and insert the replacement instruction...
4516 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004517 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004518 else {
4519 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004520 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004521 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004522
4523 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00004524
4525 // Scan to the end of the allocation instructions, to skip over a block of
4526 // allocas if possible...
4527 //
4528 BasicBlock::iterator It = New;
4529 while (isa<AllocationInst>(*It)) ++It;
4530
4531 // Now that I is pointing to the first non-allocation-inst in the block,
4532 // insert our getelementptr instruction...
4533 //
Chris Lattner69193f92004-04-05 01:30:19 +00004534 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004535 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
4536
4537 // Now make everything use the getelementptr instead of the original
4538 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004539 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004540 } else if (isa<UndefValue>(AI.getArraySize())) {
4541 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004542 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004543
4544 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4545 // Note that we only do this for alloca's, because malloc should allocate and
4546 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00004547 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
4548 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004549 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4550
Chris Lattner1085bdf2002-11-04 16:18:53 +00004551 return 0;
4552}
4553
Chris Lattner8427bff2003-12-07 01:24:23 +00004554Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4555 Value *Op = FI.getOperand(0);
4556
4557 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4558 if (CastInst *CI = dyn_cast<CastInst>(Op))
4559 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4560 FI.setOperand(0, CI->getOperand(0));
4561 return &FI;
4562 }
4563
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004564 // free undef -> unreachable.
4565 if (isa<UndefValue>(Op)) {
4566 // Insert a new store to null because we cannot modify the CFG here.
4567 new StoreInst(ConstantBool::True,
4568 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4569 return EraseInstFromFunction(FI);
4570 }
4571
Chris Lattnerf3a36602004-02-28 04:57:37 +00004572 // If we have 'free null' delete the instruction. This can happen in stl code
4573 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004574 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004575 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004576
Chris Lattner8427bff2003-12-07 01:24:23 +00004577 return 0;
4578}
4579
4580
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004581/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4582/// constantexpr, return the constant value being addressed by the constant
4583/// expression, or null if something is funny.
4584///
4585static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004586 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004587 return 0; // Do not allow stepping over the value!
4588
4589 // Loop over all of the operands, tracking down which value we are
4590 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004591 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4592 for (++I; I != E; ++I)
4593 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4594 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4595 assert(CU->getValue() < STy->getNumElements() &&
4596 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004597 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00004598 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004599 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00004600 } else if (isa<ConstantAggregateZero>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004601 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00004602 } else if (isa<UndefValue>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004603 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004604 } else {
4605 return 0;
4606 }
4607 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4608 const ArrayType *ATy = cast<ArrayType>(*I);
4609 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4610 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004611 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004612 else if (isa<ConstantAggregateZero>(C))
4613 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004614 else if (isa<UndefValue>(C))
4615 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004616 else
4617 return 0;
4618 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004619 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004620 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004621 return C;
4622}
4623
Chris Lattner35e24772004-07-13 01:49:43 +00004624static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4625 User *CI = cast<User>(LI.getOperand(0));
4626
4627 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4628 if (const PointerType *SrcTy =
4629 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
4630 const Type *SrcPTy = SrcTy->getElementType();
4631 if (SrcPTy->isSized() && DestPTy->isSized() &&
4632 IC.getTargetData().getTypeSize(SrcPTy) ==
4633 IC.getTargetData().getTypeSize(DestPTy) &&
4634 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
4635 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
4636 // Okay, we are casting from one integer or pointer type to another of
4637 // the same size. Instead of casting the pointer before the load, cast
4638 // the result of the loaded value.
4639 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004640 CI->getName(),
4641 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00004642 // Now cast the result of the load.
4643 return new CastInst(NewLoad, LI.getType());
4644 }
4645 }
4646 return 0;
4647}
4648
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004649/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004650/// from this value cannot trap. If it is not obviously safe to load from the
4651/// specified pointer, we do a quick local scan of the basic block containing
4652/// ScanFrom, to determine if the address is already accessed.
4653static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4654 // If it is an alloca or global variable, it is always safe to load from.
4655 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4656
4657 // Otherwise, be a little bit agressive by scanning the local block where we
4658 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004659 // from/to. If so, the previous load or store would have already trapped,
4660 // so there is no harm doing an extra load (also, CSE will later eliminate
4661 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004662 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4663
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004664 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004665 --BBI;
4666
4667 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4668 if (LI->getOperand(0) == V) return true;
4669 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4670 if (SI->getOperand(1) == V) return true;
4671
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004672 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004673 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004674}
4675
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004676Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4677 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004678
Chris Lattner81a7a232004-10-16 18:11:37 +00004679 if (Constant *C = dyn_cast<Constant>(Op)) {
4680 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004681 !LI.isVolatile()) { // load null/undef -> undef
4682 // Insert a new store to null instruction before the load to indicate that
4683 // this code is not reachable. We do this instead of inserting an
4684 // unreachable instruction directly because we cannot modify the CFG.
4685 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004686 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004687 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004688
Chris Lattner81a7a232004-10-16 18:11:37 +00004689 // Instcombine load (constant global) into the value loaded.
4690 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4691 if (GV->isConstant() && !GV->isExternal())
4692 return ReplaceInstUsesWith(LI, GV->getInitializer());
4693
4694 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4695 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4696 if (CE->getOpcode() == Instruction::GetElementPtr) {
4697 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4698 if (GV->isConstant() && !GV->isExternal())
4699 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4700 return ReplaceInstUsesWith(LI, V);
4701 } else if (CE->getOpcode() == Instruction::Cast) {
4702 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4703 return Res;
4704 }
4705 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004706
4707 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004708 if (CastInst *CI = dyn_cast<CastInst>(Op))
4709 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4710 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004711
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004712 if (!LI.isVolatile() && Op->hasOneUse()) {
4713 // Change select and PHI nodes to select values instead of addresses: this
4714 // helps alias analysis out a lot, allows many others simplifications, and
4715 // exposes redundancy in the code.
4716 //
4717 // Note that we cannot do the transformation unless we know that the
4718 // introduced loads cannot trap! Something like this is valid as long as
4719 // the condition is always false: load (select bool %C, int* null, int* %G),
4720 // but it would not be valid if we transformed it to load from null
4721 // unconditionally.
4722 //
4723 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4724 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004725 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4726 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004727 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004728 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004729 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004730 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004731 return new SelectInst(SI->getCondition(), V1, V2);
4732 }
4733
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004734 // load (select (cond, null, P)) -> load P
4735 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4736 if (C->isNullValue()) {
4737 LI.setOperand(0, SI->getOperand(2));
4738 return &LI;
4739 }
4740
4741 // load (select (cond, P, null)) -> load P
4742 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4743 if (C->isNullValue()) {
4744 LI.setOperand(0, SI->getOperand(1));
4745 return &LI;
4746 }
4747
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004748 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4749 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004750 bool Safe = PN->getParent() == LI.getParent();
4751
4752 // Scan all of the instructions between the PHI and the load to make
4753 // sure there are no instructions that might possibly alter the value
4754 // loaded from the PHI.
4755 if (Safe) {
4756 BasicBlock::iterator I = &LI;
4757 for (--I; !isa<PHINode>(I); --I)
4758 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4759 Safe = false;
4760 break;
4761 }
4762 }
4763
4764 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004765 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004766 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004767 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004768
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004769 if (Safe) {
4770 // Create the PHI.
4771 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4772 InsertNewInstBefore(NewPN, *PN);
4773 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4774
4775 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4776 BasicBlock *BB = PN->getIncomingBlock(i);
4777 Value *&TheLoad = LoadMap[BB];
4778 if (TheLoad == 0) {
4779 Value *InVal = PN->getIncomingValue(i);
4780 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4781 InVal->getName()+".val"),
4782 *BB->getTerminator());
4783 }
4784 NewPN->addIncoming(TheLoad, BB);
4785 }
4786 return ReplaceInstUsesWith(LI, NewPN);
4787 }
4788 }
4789 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004790 return 0;
4791}
4792
Chris Lattner9eef8a72003-06-04 04:46:00 +00004793Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4794 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004795 Value *X;
4796 BasicBlock *TrueDest;
4797 BasicBlock *FalseDest;
4798 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4799 !isa<Constant>(X)) {
4800 // Swap Destinations and condition...
4801 BI.setCondition(X);
4802 BI.setSuccessor(0, FalseDest);
4803 BI.setSuccessor(1, TrueDest);
4804 return &BI;
4805 }
4806
4807 // Cannonicalize setne -> seteq
4808 Instruction::BinaryOps Op; Value *Y;
4809 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4810 TrueDest, FalseDest)))
4811 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4812 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4813 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4814 std::string Name = I->getName(); I->setName("");
4815 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4816 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004817 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004818 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004819 BI.setSuccessor(0, FalseDest);
4820 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004821 removeFromWorkList(I);
4822 I->getParent()->getInstList().erase(I);
4823 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004824 return &BI;
4825 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004826
Chris Lattner9eef8a72003-06-04 04:46:00 +00004827 return 0;
4828}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004829
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004830Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4831 Value *Cond = SI.getCondition();
4832 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4833 if (I->getOpcode() == Instruction::Add)
4834 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4835 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4836 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004837 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004838 AddRHS));
4839 SI.setOperand(0, I->getOperand(0));
4840 WorkList.push_back(I);
4841 return &SI;
4842 }
4843 }
4844 return 0;
4845}
4846
Chris Lattnerca081252001-12-14 16:52:21 +00004847
Chris Lattner99f48c62002-09-02 04:59:56 +00004848void InstCombiner::removeFromWorkList(Instruction *I) {
4849 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4850 WorkList.end());
4851}
4852
Chris Lattner39c98bb2004-12-08 23:43:58 +00004853
4854/// TryToSinkInstruction - Try to move the specified instruction from its
4855/// current block into the beginning of DestBlock, which can only happen if it's
4856/// safe to move the instruction past all of the instructions between it and the
4857/// end of its block.
4858static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
4859 assert(I->hasOneUse() && "Invariants didn't hold!");
4860
4861 // Cannot move control-flow-involving instructions.
4862 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
4863
4864 // Do not sink alloca instructions out of the entry block.
4865 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
4866 return false;
4867
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004868 // We can only sink load instructions if there is nothing between the load and
4869 // the end of block that could change the value.
4870 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4871 if (LI->isVolatile()) return false; // Don't sink volatile loads.
4872
4873 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
4874 Scan != E; ++Scan)
4875 if (Scan->mayWriteToMemory())
4876 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004877 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00004878
4879 BasicBlock::iterator InsertPos = DestBlock->begin();
4880 while (isa<PHINode>(InsertPos)) ++InsertPos;
4881
4882 BasicBlock *SrcBlock = I->getParent();
4883 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
4884 ++NumSunkInst;
4885 return true;
4886}
4887
Chris Lattner113f4f42002-06-25 16:13:24 +00004888bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004889 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004890 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004891
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004892 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4893 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004894
Chris Lattnerca081252001-12-14 16:52:21 +00004895
4896 while (!WorkList.empty()) {
4897 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4898 WorkList.pop_back();
4899
Misha Brukman632df282002-10-29 23:06:16 +00004900 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004901 // Check to see if we can DIE the instruction...
4902 if (isInstructionTriviallyDead(I)) {
4903 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004904 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004905 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004906 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004907
Chris Lattnercd517ff2005-01-28 19:32:01 +00004908 DEBUG(std::cerr << "IC: DCE: " << *I);
4909
4910 I->eraseFromParent();
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004911 removeFromWorkList(I);
4912 continue;
4913 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004914
Misha Brukman632df282002-10-29 23:06:16 +00004915 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004916 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004917 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00004918 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004919 cast<Constant>(Ptr)->isNullValue() &&
4920 !isa<ConstantPointerNull>(C) &&
4921 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00004922 // If this is a constant expr gep that is effectively computing an
4923 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4924 bool isFoldableGEP = true;
4925 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4926 if (!isa<ConstantInt>(I->getOperand(i)))
4927 isFoldableGEP = false;
4928 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004929 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00004930 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4931 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004932 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004933 C = ConstantExpr::getCast(C, I->getType());
4934 }
4935 }
4936
Chris Lattnercd517ff2005-01-28 19:32:01 +00004937 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
4938
Chris Lattner99f48c62002-09-02 04:59:56 +00004939 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004940 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004941 ReplaceInstUsesWith(*I, C);
4942
Chris Lattner99f48c62002-09-02 04:59:56 +00004943 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004944 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004945 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004946 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004947 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004948
Chris Lattner39c98bb2004-12-08 23:43:58 +00004949 // See if we can trivially sink this instruction to a successor basic block.
4950 if (I->hasOneUse()) {
4951 BasicBlock *BB = I->getParent();
4952 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
4953 if (UserParent != BB) {
4954 bool UserIsSuccessor = false;
4955 // See if the user is one of our successors.
4956 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
4957 if (*SI == UserParent) {
4958 UserIsSuccessor = true;
4959 break;
4960 }
4961
4962 // If the user is one of our immediate successors, and if that successor
4963 // only has us as a predecessors (we'd have to split the critical edge
4964 // otherwise), we can keep going.
4965 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
4966 next(pred_begin(UserParent)) == pred_end(UserParent))
4967 // Okay, the CFG is simple enough, try to sink this instruction.
4968 Changed |= TryToSinkInstruction(I, UserParent);
4969 }
4970 }
4971
Chris Lattnerca081252001-12-14 16:52:21 +00004972 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004973 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004974 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004975 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004976 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004977 DEBUG(std::cerr << "IC: Old = " << *I
4978 << " New = " << *Result);
4979
Chris Lattner396dbfe2004-06-09 05:08:07 +00004980 // Everything uses the new instruction now.
4981 I->replaceAllUsesWith(Result);
4982
4983 // Push the new instruction and any users onto the worklist.
4984 WorkList.push_back(Result);
4985 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004986
4987 // Move the name to the new instruction first...
4988 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004989 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004990
4991 // Insert the new instruction into the basic block...
4992 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00004993 BasicBlock::iterator InsertPos = I;
4994
4995 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4996 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4997 ++InsertPos;
4998
4999 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005000
Chris Lattner63d75af2004-05-01 23:27:23 +00005001 // Make sure that we reprocess all operands now that we reduced their
5002 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00005003 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5004 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5005 WorkList.push_back(OpI);
5006
Chris Lattner396dbfe2004-06-09 05:08:07 +00005007 // Instructions can end up on the worklist more than once. Make sure
5008 // we do not process an instruction that has been deleted.
5009 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00005010
5011 // Erase the old instruction.
5012 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00005013 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00005014 DEBUG(std::cerr << "IC: MOD = " << *I);
5015
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005016 // If the instruction was modified, it's possible that it is now dead.
5017 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00005018 if (isInstructionTriviallyDead(I)) {
5019 // Make sure we process all operands now that we are reducing their
5020 // use counts.
5021 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5022 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5023 WorkList.push_back(OpI);
5024
5025 // Instructions may end up in the worklist more than once. Erase all
5026 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00005027 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00005028 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00005029 } else {
5030 WorkList.push_back(Result);
5031 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00005032 }
Chris Lattner053c0932002-05-14 15:24:07 +00005033 }
Chris Lattner260ab202002-04-18 17:39:14 +00005034 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00005035 }
5036 }
5037
Chris Lattner260ab202002-04-18 17:39:14 +00005038 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00005039}
5040
Brian Gaeke38b79e82004-07-27 17:43:21 +00005041FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00005042 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00005043}
Brian Gaeke960707c2003-11-11 22:41:34 +00005044