blob: b8ff3d4e7e73c5ff867b49c421ed9cadb01cc627 [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 Lattnerb909e8b2004-03-12 05:52:32 +0000123 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000124 Instruction *visitCallInst(CallInst &CI);
125 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000126 Instruction *visitPHINode(PHINode &PN);
127 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000128 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000129 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000130 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000131 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000132 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000133
134 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000135 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000136
Chris Lattner970c33a2003-06-19 17:00:31 +0000137 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000138 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000139 bool transformConstExprCastCall(CallSite CS);
140
Chris Lattner69193f92004-04-05 01:30:19 +0000141 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000142 // InsertNewInstBefore - insert an instruction New before instruction Old
143 // in the program. Add the new instruction to the worklist.
144 //
Chris Lattner623826c2004-09-28 21:48:02 +0000145 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000146 assert(New && New->getParent() == 0 &&
147 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000148 BasicBlock *BB = Old.getParent();
149 BB->getInstList().insert(&Old, New); // Insert inst
150 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000151 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000152 }
153
Chris Lattner7e794272004-09-24 15:21:34 +0000154 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
155 /// This also adds the cast to the worklist. Finally, this returns the
156 /// cast.
157 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
158 if (V->getType() == Ty) return V;
159
160 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
161 WorkList.push_back(C);
162 return C;
163 }
164
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000165 // ReplaceInstUsesWith - This method is to be used when an instruction is
166 // found to be dead, replacable with another preexisting expression. Here
167 // we add all uses of I to the worklist, replace all uses of I with the new
168 // value, then return I, so that the inst combiner will know that I was
169 // modified.
170 //
171 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000172 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000173 if (&I != V) {
174 I.replaceAllUsesWith(V);
175 return &I;
176 } else {
177 // If we are replacing the instruction with itself, this must be in a
178 // segment of unreachable code, so just clobber the instruction.
Chris Lattner8ba9ec92004-10-18 02:59:09 +0000179 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner8953b902004-04-05 02:10:19 +0000180 return &I;
181 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000182 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000183
184 // EraseInstFromFunction - When dealing with an instruction that has side
185 // effects or produces a void value, we can't rely on DCE to delete the
186 // instruction. Instead, visit methods should return the value returned by
187 // this function.
188 Instruction *EraseInstFromFunction(Instruction &I) {
189 assert(I.use_empty() && "Cannot erase instruction that is used!");
190 AddUsesToWorkList(I);
191 removeFromWorkList(&I);
Chris Lattner95307542004-11-18 21:41:39 +0000192 I.eraseFromParent();
Chris Lattner51ea1272004-02-28 05:22:00 +0000193 return 0; // Don't do anything with FI
194 }
195
196
Chris Lattner3ac7c262003-08-13 20:16:26 +0000197 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000198 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
199 /// InsertBefore instruction. This is specialized a bit to avoid inserting
200 /// casts that are known to not do anything...
201 ///
202 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
203 Instruction *InsertBefore);
204
Chris Lattner7fb29e12003-03-11 00:12:48 +0000205 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000206 // operators.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000207 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000208
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000209
210 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
211 // PHI node as operand #0, see if we can fold the instruction into the PHI
212 // (which is only possible if all operands to the PHI are constants).
213 Instruction *FoldOpIntoPhi(Instruction &I);
214
Chris Lattner7515cab2004-11-14 19:13:23 +0000215 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
216 // operator and they all are only used by the PHI, PHI together their
217 // inputs, and do the operation once, to the result of the PHI.
218 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
219
Chris Lattnerba1cb382003-09-19 17:17:26 +0000220 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
221 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner6862fbd2004-09-29 17:40:11 +0000222
223 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
224 bool Inside, Instruction &IB);
Chris Lattner260ab202002-04-18 17:39:14 +0000225 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000226
Chris Lattnerc8b70922002-07-26 21:12:46 +0000227 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000228}
229
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000230// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattner81a7a232004-10-16 18:11:37 +0000231// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000232static unsigned getComplexity(Value *V) {
233 if (isa<Instruction>(V)) {
234 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattner81a7a232004-10-16 18:11:37 +0000235 return 3;
236 return 4;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000237 }
Chris Lattner81a7a232004-10-16 18:11:37 +0000238 if (isa<Argument>(V)) return 3;
239 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000240}
Chris Lattner260ab202002-04-18 17:39:14 +0000241
Chris Lattner7fb29e12003-03-11 00:12:48 +0000242// isOnlyUse - Return true if this instruction will be deleted if we stop using
243// it.
244static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000245 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000246}
247
Chris Lattnere79e8542004-02-23 06:38:22 +0000248// getPromotedType - Return the specified type promoted as it would be to pass
249// though a va_arg area...
250static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000251 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000252 case Type::SByteTyID:
253 case Type::ShortTyID: return Type::IntTy;
254 case Type::UByteTyID:
255 case Type::UShortTyID: return Type::UIntTy;
256 case Type::FloatTyID: return Type::DoubleTy;
257 default: return Ty;
258 }
259}
260
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000261// SimplifyCommutative - This performs a few simplifications for commutative
262// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000263//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000264// 1. Order operands such that they are listed from right (least complex) to
265// left (most complex). This puts constants before unary operators before
266// binary operators.
267//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000268// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
269// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000270//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000271bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000272 bool Changed = false;
273 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
274 Changed = !I.swapOperands();
275
276 if (!I.isAssociative()) return Changed;
277 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000278 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
279 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
280 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000281 Constant *Folded = ConstantExpr::get(I.getOpcode(),
282 cast<Constant>(I.getOperand(1)),
283 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000284 I.setOperand(0, Op->getOperand(0));
285 I.setOperand(1, Folded);
286 return true;
287 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
288 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
289 isOnlyUse(Op) && isOnlyUse(Op1)) {
290 Constant *C1 = cast<Constant>(Op->getOperand(1));
291 Constant *C2 = cast<Constant>(Op1->getOperand(1));
292
293 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000294 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000295 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
296 Op1->getOperand(0),
297 Op1->getName(), &I);
298 WorkList.push_back(New);
299 I.setOperand(0, New);
300 I.setOperand(1, Folded);
301 return true;
302 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000303 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000304 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000305}
Chris Lattnerca081252001-12-14 16:52:21 +0000306
Chris Lattnerbb74e222003-03-10 23:06:50 +0000307// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
308// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000309//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000310static inline Value *dyn_castNegVal(Value *V) {
311 if (BinaryOperator::isNeg(V))
312 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
313
Chris Lattner9ad0d552004-12-14 20:08:06 +0000314 // Constants can be considered to be negated values if they can be folded.
315 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
316 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000317 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000318}
319
Chris Lattnerbb74e222003-03-10 23:06:50 +0000320static inline Value *dyn_castNotVal(Value *V) {
321 if (BinaryOperator::isNot(V))
322 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
323
324 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000325 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000326 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000327 return 0;
328}
329
Chris Lattner7fb29e12003-03-11 00:12:48 +0000330// dyn_castFoldableMul - If this value is a multiply that can be folded into
331// other computations (because it has a constant operand), return the
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000332// non-constant operand of the multiply, and set CST to point to the multiplier.
333// Otherwise, return null.
Chris Lattner7fb29e12003-03-11 00:12:48 +0000334//
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000335static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000336 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000337 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattner7fb29e12003-03-11 00:12:48 +0000338 if (I->getOpcode() == Instruction::Mul)
Chris Lattner970136362004-11-15 05:54:07 +0000339 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattner7fb29e12003-03-11 00:12:48 +0000340 return I->getOperand(0);
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000341 if (I->getOpcode() == Instruction::Shl)
Chris Lattner970136362004-11-15 05:54:07 +0000342 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000343 // The multiplier is really 1 << CST.
344 Constant *One = ConstantInt::get(V->getType(), 1);
345 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
346 return I->getOperand(0);
347 }
348 }
Chris Lattner7fb29e12003-03-11 00:12:48 +0000349 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000350}
Chris Lattner31ae8632002-08-14 17:51:49 +0000351
Chris Lattner0798af32005-01-13 20:14:25 +0000352/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
353/// expression, return it.
354static User *dyn_castGetElementPtr(Value *V) {
355 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
356 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
357 if (CE->getOpcode() == Instruction::GetElementPtr)
358 return cast<User>(V);
359 return false;
360}
361
Chris Lattner3082c5a2003-02-18 19:28:33 +0000362// Log2 - Calculate the log base 2 for the specified value if it is exactly a
363// power of 2.
364static unsigned Log2(uint64_t Val) {
365 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
366 unsigned Count = 0;
367 while (Val != 1) {
368 if (Val & 1) return 0; // Multiple bits set?
369 Val >>= 1;
370 ++Count;
371 }
372 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000373}
374
Chris Lattner623826c2004-09-28 21:48:02 +0000375// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattner6862fbd2004-09-29 17:40:11 +0000376static ConstantInt *AddOne(ConstantInt *C) {
377 return cast<ConstantInt>(ConstantExpr::getAdd(C,
378 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000379}
Chris Lattner6862fbd2004-09-29 17:40:11 +0000380static ConstantInt *SubOne(ConstantInt *C) {
381 return cast<ConstantInt>(ConstantExpr::getSub(C,
382 ConstantInt::get(C->getType(), 1)));
Chris Lattner623826c2004-09-28 21:48:02 +0000383}
384
385// isTrueWhenEqual - Return true if the specified setcondinst instruction is
386// true when both operands are equal...
387//
388static bool isTrueWhenEqual(Instruction &I) {
389 return I.getOpcode() == Instruction::SetEQ ||
390 I.getOpcode() == Instruction::SetGE ||
391 I.getOpcode() == Instruction::SetLE;
392}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000393
394/// AssociativeOpt - Perform an optimization on an associative operator. This
395/// function is designed to check a chain of associative operators for a
396/// potential to apply a certain optimization. Since the optimization may be
397/// applicable if the expression was reassociated, this checks the chain, then
398/// reassociates the expression as necessary to expose the optimization
399/// opportunity. This makes use of a special Functor, which must define
400/// 'shouldApply' and 'apply' methods.
401///
402template<typename Functor>
403Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
404 unsigned Opcode = Root.getOpcode();
405 Value *LHS = Root.getOperand(0);
406
407 // Quick check, see if the immediate LHS matches...
408 if (F.shouldApply(LHS))
409 return F.apply(Root);
410
411 // Otherwise, if the LHS is not of the same opcode as the root, return.
412 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000413 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000414 // Should we apply this transform to the RHS?
415 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
416
417 // If not to the RHS, check to see if we should apply to the LHS...
418 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
419 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
420 ShouldApply = true;
421 }
422
423 // If the functor wants to apply the optimization to the RHS of LHSI,
424 // reassociate the expression from ((? op A) op B) to (? op (A op B))
425 if (ShouldApply) {
426 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000427
428 // Now all of the instructions are in the current basic block, go ahead
429 // and perform the reassociation.
430 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
431
432 // First move the selected RHS to the LHS of the root...
433 Root.setOperand(0, LHSI->getOperand(1));
434
435 // Make what used to be the LHS of the root be the user of the root...
436 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000437 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000438 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
439 return 0;
440 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000441 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000442 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000443 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
444 BasicBlock::iterator ARI = &Root; ++ARI;
445 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
446 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000447
448 // Now propagate the ExtraOperand down the chain of instructions until we
449 // get to LHSI.
450 while (TmpLHSI != LHSI) {
451 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000452 // Move the instruction to immediately before the chain we are
453 // constructing to avoid breaking dominance properties.
454 NextLHSI->getParent()->getInstList().remove(NextLHSI);
455 BB->getInstList().insert(ARI, NextLHSI);
456 ARI = NextLHSI;
457
Chris Lattnerb8b97502003-08-13 19:01:45 +0000458 Value *NextOp = NextLHSI->getOperand(1);
459 NextLHSI->setOperand(1, ExtraOperand);
460 TmpLHSI = NextLHSI;
461 ExtraOperand = NextOp;
462 }
463
464 // Now that the instructions are reassociated, have the functor perform
465 // the transformation...
466 return F.apply(Root);
467 }
468
469 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
470 }
471 return 0;
472}
473
474
475// AddRHS - Implements: X + X --> X << 1
476struct AddRHS {
477 Value *RHS;
478 AddRHS(Value *rhs) : RHS(rhs) {}
479 bool shouldApply(Value *LHS) const { return LHS == RHS; }
480 Instruction *apply(BinaryOperator &Add) const {
481 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
482 ConstantInt::get(Type::UByteTy, 1));
483 }
484};
485
486// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
487// iff C1&C2 == 0
488struct AddMaskingAnd {
489 Constant *C2;
490 AddMaskingAnd(Constant *c) : C2(c) {}
491 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000492 ConstantInt *C1;
493 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
494 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000495 }
496 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000497 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000498 }
499};
500
Chris Lattner86102b82005-01-01 16:22:27 +0000501static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner183b3362004-04-09 19:05:30 +0000502 InstCombiner *IC) {
Chris Lattner86102b82005-01-01 16:22:27 +0000503 if (isa<CastInst>(I)) {
504 if (Constant *SOC = dyn_cast<Constant>(SO))
505 return ConstantExpr::getCast(SOC, I.getType());
506
507 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
508 SO->getName() + ".cast"), I);
509 }
510
Chris Lattner183b3362004-04-09 19:05:30 +0000511 // Figure out if the constant is the left or the right argument.
Chris Lattner86102b82005-01-01 16:22:27 +0000512 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
513 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000514
Chris Lattner183b3362004-04-09 19:05:30 +0000515 if (Constant *SOC = dyn_cast<Constant>(SO)) {
516 if (ConstIsRHS)
Chris Lattner86102b82005-01-01 16:22:27 +0000517 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
518 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner183b3362004-04-09 19:05:30 +0000519 }
520
521 Value *Op0 = SO, *Op1 = ConstOperand;
522 if (!ConstIsRHS)
523 std::swap(Op0, Op1);
524 Instruction *New;
Chris Lattner86102b82005-01-01 16:22:27 +0000525 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
526 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
527 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
528 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000529 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000530 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000531 abort();
532 }
Chris Lattner86102b82005-01-01 16:22:27 +0000533 return IC->InsertNewInstBefore(New, I);
534}
535
536// FoldOpIntoSelect - Given an instruction with a select as one operand and a
537// constant as the other operand, try to fold the binary operator into the
538// select arguments. This also works for Cast instructions, which obviously do
539// not have a second operand.
540static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
541 InstCombiner *IC) {
542 // Don't modify shared select instructions
543 if (!SI->hasOneUse()) return 0;
544 Value *TV = SI->getOperand(1);
545 Value *FV = SI->getOperand(2);
546
547 if (isa<Constant>(TV) || isa<Constant>(FV)) {
548 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
549 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
550
551 return new SelectInst(SI->getCondition(), SelectTrueVal,
552 SelectFalseVal);
553 }
554 return 0;
Chris Lattner183b3362004-04-09 19:05:30 +0000555}
556
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000557
558/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
559/// node as operand #0, see if we can fold the instruction into the PHI (which
560/// is only possible if all operands to the PHI are constants).
561Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
562 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattner7515cab2004-11-14 19:13:23 +0000563 unsigned NumPHIValues = PN->getNumIncomingValues();
564 if (!PN->hasOneUse() || NumPHIValues == 0 ||
565 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000566
567 // Check to see if all of the operands of the PHI are constants. If not, we
568 // cannot do the transformation.
Chris Lattner7515cab2004-11-14 19:13:23 +0000569 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000570 if (!isa<Constant>(PN->getIncomingValue(i)))
571 return 0;
572
573 // Okay, we can do the transformation: create the new PHI node.
574 PHINode *NewPN = new PHINode(I.getType(), I.getName());
575 I.setName("");
576 NewPN->op_reserve(PN->getNumOperands());
577 InsertNewInstBefore(NewPN, *PN);
578
579 // Next, add all of the operands to the PHI.
580 if (I.getNumOperands() == 2) {
581 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattner7515cab2004-11-14 19:13:23 +0000582 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000583 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
584 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
585 PN->getIncomingBlock(i));
586 }
587 } else {
588 assert(isa<CastInst>(I) && "Unary op should be a cast!");
589 const Type *RetTy = I.getType();
Chris Lattner7515cab2004-11-14 19:13:23 +0000590 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000591 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
592 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
593 PN->getIncomingBlock(i));
594 }
595 }
596 return ReplaceInstUsesWith(I, NewPN);
597}
598
Chris Lattner113f4f42002-06-25 16:13:24 +0000599Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000600 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000601 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000602
Chris Lattnercf4a9962004-04-10 22:01:55 +0000603 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner81a7a232004-10-16 18:11:37 +0000604 // X + undef -> undef
605 if (isa<UndefValue>(RHS))
606 return ReplaceInstUsesWith(I, RHS);
607
Chris Lattnercf4a9962004-04-10 22:01:55 +0000608 // X + 0 --> X
609 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
610 RHSC->isNullValue())
611 return ReplaceInstUsesWith(I, LHS);
612
613 // X + (signbit) --> X ^ signbit
614 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
615 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
616 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattner33eb9092004-11-05 04:45:43 +0000617 if (Val == (1ULL << (NumBits-1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000618 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000619 }
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000620
621 if (isa<PHINode>(LHS))
622 if (Instruction *NV = FoldOpIntoPhi(I))
623 return NV;
Chris Lattnercf4a9962004-04-10 22:01:55 +0000624 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000625
Chris Lattnerb8b97502003-08-13 19:01:45 +0000626 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000627 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000628 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000629 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000630
Chris Lattner147e9752002-05-08 22:46:53 +0000631 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000632 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000633 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000634
635 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000636 if (!isa<Constant>(RHS))
637 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000638 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000639
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000640 ConstantInt *C2;
641 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
642 if (X == RHS) // X*C + X --> X * (C+1)
643 return BinaryOperator::createMul(RHS, AddOne(C2));
644
645 // X*C1 + X*C2 --> X * (C1+C2)
646 ConstantInt *C1;
647 if (X == dyn_castFoldableMul(RHS, C1))
648 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattner57c8d992003-02-18 19:57:07 +0000649 }
650
651 // X + X*C --> X * (C+1)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000652 if (dyn_castFoldableMul(RHS, C2) == LHS)
653 return BinaryOperator::createMul(LHS, AddOne(C2));
654
Chris Lattner57c8d992003-02-18 19:57:07 +0000655
Chris Lattnerb8b97502003-08-13 19:01:45 +0000656 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000657 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000658 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000659
Chris Lattnerb9cde762003-10-02 15:11:26 +0000660 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000661 Value *X;
662 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
663 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
664 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000665 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000666
Chris Lattnerbff91d92004-10-08 05:07:56 +0000667 // (X & FF00) + xx00 -> (X+xx00) & FF00
668 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
669 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
670 if (Anded == CRHS) {
671 // See if all bits from the first bit set in the Add RHS up are included
672 // in the mask. First, get the rightmost bit.
673 uint64_t AddRHSV = CRHS->getRawValue();
674
675 // Form a mask of all bits from the lowest bit added through the top.
676 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
677 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
678
679 // See if the and mask includes all of these bits.
680 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
681
682 if (AddRHSHighBits == AddRHSHighBitsAnd) {
683 // Okay, the xform is safe. Insert the new add pronto.
684 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
685 LHS->getName()), I);
686 return BinaryOperator::createAnd(NewAdd, C2);
687 }
688 }
689 }
690
Chris Lattnerd4252a72004-07-30 07:50:03 +0000691 // Try to fold constant add into select arguments.
692 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner86102b82005-01-01 16:22:27 +0000693 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerd4252a72004-07-30 07:50:03 +0000694 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000695 }
696
Chris Lattner113f4f42002-06-25 16:13:24 +0000697 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000698}
699
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000700// isSignBit - Return true if the value represented by the constant only has the
701// highest order bit set.
702static bool isSignBit(ConstantInt *CI) {
703 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
704 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
705}
706
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000707static unsigned getTypeSizeInBits(const Type *Ty) {
708 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
709}
710
Chris Lattner022167f2004-03-13 00:11:49 +0000711/// RemoveNoopCast - Strip off nonconverting casts from the value.
712///
713static Value *RemoveNoopCast(Value *V) {
714 if (CastInst *CI = dyn_cast<CastInst>(V)) {
715 const Type *CTy = CI->getType();
716 const Type *OpTy = CI->getOperand(0)->getType();
717 if (CTy->isInteger() && OpTy->isInteger()) {
718 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
719 return RemoveNoopCast(CI->getOperand(0));
720 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
721 return RemoveNoopCast(CI->getOperand(0));
722 }
723 return V;
724}
725
Chris Lattner113f4f42002-06-25 16:13:24 +0000726Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000727 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000728
Chris Lattnere6794492002-08-12 21:17:25 +0000729 if (Op0 == Op1) // sub X, X -> 0
730 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000731
Chris Lattnere6794492002-08-12 21:17:25 +0000732 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000733 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000734 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000735
Chris Lattner81a7a232004-10-16 18:11:37 +0000736 if (isa<UndefValue>(Op0))
737 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
738 if (isa<UndefValue>(Op1))
739 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
740
Chris Lattner8f2f5982003-11-05 01:06:05 +0000741 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
742 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000743 if (C->isAllOnesValue())
744 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000745
Chris Lattner8f2f5982003-11-05 01:06:05 +0000746 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000747 Value *X;
748 if (match(Op1, m_Not(m_Value(X))))
749 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000750 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000751 // -((uint)X >> 31) -> ((int)X >> 31)
752 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000753 if (C->isNullValue()) {
754 Value *NoopCastedRHS = RemoveNoopCast(Op1);
755 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000756 if (SI->getOpcode() == Instruction::Shr)
757 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
758 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000759 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000760 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000761 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000762 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000763 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000764 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000765 // Ok, the transformation is safe. Insert a cast of the incoming
766 // value, then the new shift, then the new cast.
767 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
768 SI->getOperand(0)->getName());
769 Value *InV = InsertNewInstBefore(FirstCast, I);
770 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
771 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000772 if (NewShift->getType() == I.getType())
773 return NewShift;
774 else {
775 InV = InsertNewInstBefore(NewShift, I);
776 return new CastInst(NewShift, I.getType());
777 }
Chris Lattner92295c52004-03-12 23:53:13 +0000778 }
779 }
Chris Lattner022167f2004-03-13 00:11:49 +0000780 }
Chris Lattner183b3362004-04-09 19:05:30 +0000781
782 // Try to fold constant sub into select arguments.
783 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +0000784 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000785 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000786
787 if (isa<PHINode>(Op0))
788 if (Instruction *NV = FoldOpIntoPhi(I))
789 return NV;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000790 }
791
Chris Lattner3082c5a2003-02-18 19:28:33 +0000792 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000793 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000794 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
795 // is not used by anyone else...
796 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000797 if (Op1I->getOpcode() == Instruction::Sub &&
798 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000799 // Swap the two operands of the subexpr...
800 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
801 Op1I->setOperand(0, IIOp1);
802 Op1I->setOperand(1, IIOp0);
803
804 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000805 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000806 }
807
808 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
809 //
810 if (Op1I->getOpcode() == Instruction::And &&
811 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
812 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
813
Chris Lattner396dbfe2004-06-09 05:08:07 +0000814 Value *NewNot =
815 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000816 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000817 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000818
Chris Lattner0aee4b72004-10-06 15:08:25 +0000819 // -(X sdiv C) -> (X sdiv -C)
820 if (Op1I->getOpcode() == Instruction::Div)
821 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
822 if (CSI->getValue() == 0)
823 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
824 return BinaryOperator::createDiv(Op1I->getOperand(0),
825 ConstantExpr::getNeg(DivRHS));
826
Chris Lattner57c8d992003-02-18 19:57:07 +0000827 // X - X*C --> X * (1-C)
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000828 ConstantInt *C2;
829 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
830 Constant *CP1 =
831 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000832 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000833 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000834 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000835
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000836
837 ConstantInt *C1;
838 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
839 if (X == Op1) { // X*C - X --> X * (C-1)
840 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
841 return BinaryOperator::createMul(Op1, CP1);
842 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000843
Chris Lattner8c3e7b92004-11-13 19:50:12 +0000844 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
845 if (X == dyn_castFoldableMul(Op1, C2))
846 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
847 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000848 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000849}
850
Chris Lattnere79e8542004-02-23 06:38:22 +0000851/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
852/// really just returns true if the most significant (sign) bit is set.
853static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
854 if (RHS->getType()->isSigned()) {
855 // True if source is LHS < 0 or LHS <= -1
856 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
857 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
858 } else {
859 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
860 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
861 // the size of the integer type.
862 if (Opcode == Instruction::SetGE)
863 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
864 if (Opcode == Instruction::SetGT)
865 return RHSC->getValue() ==
866 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
867 }
868 return false;
869}
870
Chris Lattner113f4f42002-06-25 16:13:24 +0000871Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000872 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000873 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000874
Chris Lattner81a7a232004-10-16 18:11:37 +0000875 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
877
Chris Lattnere6794492002-08-12 21:17:25 +0000878 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000879 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
880 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000881
882 // ((X << C1)*C2) == (X * (C2 << C1))
883 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
884 if (SI->getOpcode() == Instruction::Shl)
885 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000886 return BinaryOperator::createMul(SI->getOperand(0),
887 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000888
Chris Lattnercce81be2003-09-11 22:24:54 +0000889 if (CI->isNullValue())
890 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
891 if (CI->equalsInt(1)) // X * 1 == X
892 return ReplaceInstUsesWith(I, Op0);
893 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000894 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000895
Chris Lattnercce81be2003-09-11 22:24:54 +0000896 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000897 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
898 return new ShiftInst(Instruction::Shl, Op0,
899 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000900 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000901 if (Op1F->isNullValue())
902 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000903
Chris Lattner3082c5a2003-02-18 19:28:33 +0000904 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
905 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
906 if (Op1F->getValue() == 1.0)
907 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
908 }
Chris Lattner183b3362004-04-09 19:05:30 +0000909
910 // Try to fold constant mul into select arguments.
911 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +0000912 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +0000913 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +0000914
915 if (isa<PHINode>(Op0))
916 if (Instruction *NV = FoldOpIntoPhi(I))
917 return NV;
Chris Lattner260ab202002-04-18 17:39:14 +0000918 }
919
Chris Lattner934a64cf2003-03-10 23:23:04 +0000920 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
921 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000922 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000923
Chris Lattner2635b522004-02-23 05:39:21 +0000924 // If one of the operands of the multiply is a cast from a boolean value, then
925 // we know the bool is either zero or one, so this is a 'masking' multiply.
926 // See if we can simplify things based on how the boolean was originally
927 // formed.
928 CastInst *BoolCast = 0;
929 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
930 if (CI->getOperand(0)->getType() == Type::BoolTy)
931 BoolCast = CI;
932 if (!BoolCast)
933 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
934 if (CI->getOperand(0)->getType() == Type::BoolTy)
935 BoolCast = CI;
936 if (BoolCast) {
937 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
938 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
939 const Type *SCOpTy = SCIOp0->getType();
940
Chris Lattnere79e8542004-02-23 06:38:22 +0000941 // If the setcc is true iff the sign bit of X is set, then convert this
942 // multiply into a shift/and combination.
943 if (isa<ConstantInt>(SCIOp1) &&
944 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000945 // Shift the X value right to turn it into "all signbits".
946 Constant *Amt = ConstantUInt::get(Type::UByteTy,
947 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000948 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000949 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000950 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
951 SCIOp0->getName()), I);
952 }
953
954 Value *V =
955 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
956 BoolCast->getOperand(0)->getName()+
957 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000958
959 // If the multiply type is not the same as the source type, sign extend
960 // or truncate to the multiply type.
961 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000962 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000963
964 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000965 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000966 }
967 }
968 }
969
Chris Lattner113f4f42002-06-25 16:13:24 +0000970 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000971}
972
Chris Lattner113f4f42002-06-25 16:13:24 +0000973Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner81a7a232004-10-16 18:11:37 +0000975
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000976 if (isa<UndefValue>(Op0)) // undef / X -> 0
977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
978 if (isa<UndefValue>(Op1))
979 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
980
981 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000982 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000983 if (RHS->equalsInt(1))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000984 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000985
Chris Lattnere20c3342004-04-26 14:01:59 +0000986 // div X, -1 == -X
987 if (RHS->isAllOnesValue())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000988 return BinaryOperator::createNeg(Op0);
Chris Lattnere20c3342004-04-26 14:01:59 +0000989
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +0000990 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner272d5ca2004-09-28 18:22:15 +0000991 if (LHS->getOpcode() == Instruction::Div)
992 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner272d5ca2004-09-28 18:22:15 +0000993 // (X / C1) / C2 -> X / (C1*C2)
994 return BinaryOperator::createDiv(LHS->getOperand(0),
995 ConstantExpr::getMul(RHS, LHSRHS));
996 }
997
Chris Lattner3082c5a2003-02-18 19:28:33 +0000998 // Check to see if this is an unsigned division with an exact power of 2,
999 // if so, convert to a right shift.
1000 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1001 if (uint64_t Val = C->getValue()) // Don't break X / 0
1002 if (uint64_t C = Log2(Val))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001003 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattner3082c5a2003-02-18 19:28:33 +00001004 ConstantUInt::get(Type::UByteTy, C));
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001005
Chris Lattner4ad08352004-10-09 02:50:40 +00001006 // -X/C -> X/-C
1007 if (RHS->getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001008 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattner4ad08352004-10-09 02:50:40 +00001009 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1010
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001011 if (!RHS->isNullValue()) {
1012 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001013 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001014 return R;
1015 if (isa<PHINode>(Op0))
1016 if (Instruction *NV = FoldOpIntoPhi(I))
1017 return NV;
1018 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001019 }
1020
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001021 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1022 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1023 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1024 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1025 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1026 if (STO->getValue() == 0) { // Couldn't be this argument.
1027 I.setOperand(1, SFO);
1028 return &I;
1029 } else if (SFO->getValue() == 0) {
1030 I.setOperand(1, STO);
1031 return &I;
1032 }
1033
1034 if (uint64_t TSA = Log2(STO->getValue()))
1035 if (uint64_t FSA = Log2(SFO->getValue())) {
1036 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1037 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1038 TC, SI->getName()+".t");
1039 TSI = InsertNewInstBefore(TSI, I);
1040
1041 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1042 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1043 FC, SI->getName()+".f");
1044 FSI = InsertNewInstBefore(FSI, I);
1045 return new SelectInst(SI->getOperand(0), TSI, FSI);
1046 }
1047 }
1048
Chris Lattner3082c5a2003-02-18 19:28:33 +00001049 // 0 / X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001050 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001051 if (LHS->equalsInt(0))
1052 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1053
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001054 return 0;
1055}
1056
1057
Chris Lattner113f4f42002-06-25 16:13:24 +00001058Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001059 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner7fd5f072004-07-06 07:01:22 +00001060 if (I.getType()->isSigned())
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001061 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner98c6bdf2004-07-06 07:11:42 +00001062 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +00001063 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +00001064 // X % -Y -> X % Y
1065 AddUsesToWorkList(I);
1066 I.setOperand(1, RHSNeg);
1067 return &I;
1068 }
1069
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001070 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattner81a7a232004-10-16 18:11:37 +00001071 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001072 if (isa<UndefValue>(Op1))
1073 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattner81a7a232004-10-16 18:11:37 +00001074
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001075 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +00001076 if (RHS->equalsInt(1)) // X % 1 == 0
1077 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1078
1079 // Check to see if this is an unsigned remainder with an exact power of 2,
1080 // if so, convert to a bitwise and.
1081 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1082 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +00001083 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001084 return BinaryOperator::createAnd(Op0,
1085 ConstantUInt::get(I.getType(), Val-1));
1086
1087 if (!RHS->isNullValue()) {
1088 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001089 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001090 return R;
1091 if (isa<PHINode>(Op0))
1092 if (Instruction *NV = FoldOpIntoPhi(I))
1093 return NV;
1094 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001095 }
1096
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001097 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1098 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1099 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1100 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1101 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1102 if (STO->getValue() == 0) { // Couldn't be this argument.
1103 I.setOperand(1, SFO);
1104 return &I;
1105 } else if (SFO->getValue() == 0) {
1106 I.setOperand(1, STO);
1107 return &I;
1108 }
1109
1110 if (!(STO->getValue() & (STO->getValue()-1)) &&
1111 !(SFO->getValue() & (SFO->getValue()-1))) {
1112 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1113 SubOne(STO), SI->getName()+".t"), I);
1114 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1115 SubOne(SFO), SI->getName()+".f"), I);
1116 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1117 }
1118 }
1119
Chris Lattner3082c5a2003-02-18 19:28:33 +00001120 // 0 % X == 0, we don't need to preserve faults!
Chris Lattnerbf5b7cf2004-12-12 21:48:58 +00001121 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattner3082c5a2003-02-18 19:28:33 +00001122 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +00001123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1124
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001125 return 0;
1126}
1127
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001128// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +00001129static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001130 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1131 // Calculate -1 casted to the right type...
1132 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1133 uint64_t Val = ~0ULL; // All ones
1134 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1135 return CU->getValue() == Val-1;
1136 }
1137
1138 const ConstantSInt *CS = cast<ConstantSInt>(C);
1139
1140 // Calculate 0111111111..11111
1141 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1142 int64_t Val = INT64_MAX; // All ones
1143 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1144 return CS->getValue() == Val-1;
1145}
1146
1147// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +00001148static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001149 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1150 return CU->getValue() == 1;
1151
1152 const ConstantSInt *CS = cast<ConstantSInt>(C);
1153
1154 // Calculate 1111111111000000000000
1155 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1156 int64_t Val = -1; // All ones
1157 Val <<= TypeBits-1; // Shift over to the right spot
1158 return CS->getValue() == Val+1;
1159}
1160
Chris Lattner35167c32004-06-09 07:59:58 +00001161// isOneBitSet - Return true if there is exactly one bit set in the specified
1162// constant.
1163static bool isOneBitSet(const ConstantInt *CI) {
1164 uint64_t V = CI->getRawValue();
1165 return V && (V & (V-1)) == 0;
1166}
1167
Chris Lattner8fc5af42004-09-23 21:46:38 +00001168#if 0 // Currently unused
1169// isLowOnes - Return true if the constant is of the form 0+1+.
1170static bool isLowOnes(const ConstantInt *CI) {
1171 uint64_t V = CI->getRawValue();
1172
1173 // There won't be bits set in parts that the type doesn't contain.
1174 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1175
1176 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1177 return U && V && (U & V) == 0;
1178}
1179#endif
1180
1181// isHighOnes - Return true if the constant is of the form 1+0+.
1182// This is the same as lowones(~X).
1183static bool isHighOnes(const ConstantInt *CI) {
1184 uint64_t V = ~CI->getRawValue();
1185
1186 // There won't be bits set in parts that the type doesn't contain.
1187 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1188
1189 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1190 return U && V && (U & V) == 0;
1191}
1192
1193
Chris Lattner3ac7c262003-08-13 20:16:26 +00001194/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1195/// are carefully arranged to allow folding of expressions such as:
1196///
1197/// (A < B) | (A > B) --> (A != B)
1198///
1199/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1200/// represents that the comparison is true if A == B, and bit value '1' is true
1201/// if A < B.
1202///
1203static unsigned getSetCondCode(const SetCondInst *SCI) {
1204 switch (SCI->getOpcode()) {
1205 // False -> 0
1206 case Instruction::SetGT: return 1;
1207 case Instruction::SetEQ: return 2;
1208 case Instruction::SetGE: return 3;
1209 case Instruction::SetLT: return 4;
1210 case Instruction::SetNE: return 5;
1211 case Instruction::SetLE: return 6;
1212 // True -> 7
1213 default:
1214 assert(0 && "Invalid SetCC opcode!");
1215 return 0;
1216 }
1217}
1218
1219/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1220/// opcode and two operands into either a constant true or false, or a brand new
1221/// SetCC instruction.
1222static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1223 switch (Opcode) {
1224 case 0: return ConstantBool::False;
1225 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1226 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1227 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1228 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1229 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1230 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1231 case 7: return ConstantBool::True;
1232 default: assert(0 && "Illegal SetCCCode!"); return 0;
1233 }
1234}
1235
1236// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1237struct FoldSetCCLogical {
1238 InstCombiner &IC;
1239 Value *LHS, *RHS;
1240 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1241 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1242 bool shouldApply(Value *V) const {
1243 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1244 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1245 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1246 return false;
1247 }
1248 Instruction *apply(BinaryOperator &Log) const {
1249 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1250 if (SCI->getOperand(0) != LHS) {
1251 assert(SCI->getOperand(1) == LHS);
1252 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1253 }
1254
1255 unsigned LHSCode = getSetCondCode(SCI);
1256 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1257 unsigned Code;
1258 switch (Log.getOpcode()) {
1259 case Instruction::And: Code = LHSCode & RHSCode; break;
1260 case Instruction::Or: Code = LHSCode | RHSCode; break;
1261 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001262 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001263 }
1264
1265 Value *RV = getSetCCValue(Code, LHS, RHS);
1266 if (Instruction *I = dyn_cast<Instruction>(RV))
1267 return I;
1268 // Otherwise, it's a constant boolean value...
1269 return IC.ReplaceInstUsesWith(Log, RV);
1270 }
1271};
1272
1273
Chris Lattner86102b82005-01-01 16:22:27 +00001274/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1275/// this predicate to simplify operations downstream. V and Mask are known to
1276/// be the same type.
1277static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
1278 if (isa<UndefValue>(V) || Mask->isNullValue())
1279 return true;
1280 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
1281 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
1282
1283 if (Instruction *I = dyn_cast<Instruction>(V)) {
1284 switch (I->getOpcode()) {
1285 case Instruction::And:
1286 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
1287 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
1288 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
1289 return true;
1290 break;
1291 case Instruction::Cast: {
1292 const Type *SrcTy = I->getOperand(0)->getType();
1293 if (SrcTy->isIntegral()) {
1294 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
1295 if (SrcTy->isUnsigned() && // Only handle zero ext.
1296 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
1297 return true;
1298
1299 // If this is a noop cast, recurse.
1300 if (SrcTy != Type::BoolTy)
1301 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() ==I->getType()) ||
1302 SrcTy->getSignedVersion() == I->getType()) {
1303 Constant *NewMask =
1304 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
1305 return MaskedValueIsZero(I->getOperand(0),
1306 cast<ConstantIntegral>(NewMask));
1307 }
1308 }
1309 break;
1310 }
1311 case Instruction::Shl:
1312 // (shl X, C1) & C2 == 0 iff (-1 << C1) & C2 == 0
1313 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1314 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1315 C1 = ConstantExpr::getShl(C1, SA);
1316 C1 = ConstantExpr::getAnd(C1, Mask);
1317 if (C1->isNullValue())
1318 return true;
1319 }
1320 break;
1321 case Instruction::Shr:
1322 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
1323 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1324 if (I->getType()->isUnsigned()) {
1325 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
1326 C1 = ConstantExpr::getShr(C1, SA);
1327 C1 = ConstantExpr::getAnd(C1, Mask);
1328 if (C1->isNullValue())
1329 return true;
1330 }
1331 break;
1332 }
1333 }
1334
1335 return false;
1336}
1337
Chris Lattnerba1cb382003-09-19 17:17:26 +00001338// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1339// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1340// guaranteed to be either a shift instruction or a binary operator.
1341Instruction *InstCombiner::OptAndOp(Instruction *Op,
1342 ConstantIntegral *OpRHS,
1343 ConstantIntegral *AndRHS,
1344 BinaryOperator &TheAnd) {
1345 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001346 Constant *Together = 0;
1347 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001348 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001349
Chris Lattnerba1cb382003-09-19 17:17:26 +00001350 switch (Op->getOpcode()) {
1351 case Instruction::Xor:
Chris Lattner86102b82005-01-01 16:22:27 +00001352 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001353 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1354 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001355 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001356 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001357 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001358 }
1359 break;
1360 case Instruction::Or:
Chris Lattner86102b82005-01-01 16:22:27 +00001361 if (Together == AndRHS) // (X | C) & C --> C
1362 return ReplaceInstUsesWith(TheAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001363
Chris Lattner86102b82005-01-01 16:22:27 +00001364 if (Op->hasOneUse() && Together != OpRHS) {
1365 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1366 std::string Op0Name = Op->getName(); Op->setName("");
1367 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1368 InsertNewInstBefore(Or, TheAnd);
1369 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001370 }
1371 break;
1372 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001373 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001374 // Adding a one to a single bit bit-field should be turned into an XOR
1375 // of the bit. First thing to check is to see if this AND is with a
1376 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001377 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001378
1379 // Clear bits that are not part of the constant.
1380 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1381
1382 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001383 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001384 // Ok, at this point, we know that we are masking the result of the
1385 // ADD down to exactly one bit. If the constant we are adding has
1386 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001387 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001388
1389 // Check to see if any bits below the one bit set in AndRHSV are set.
1390 if ((AddRHS & (AndRHSV-1)) == 0) {
1391 // If not, the only thing that can effect the output of the AND is
1392 // the bit specified by AndRHSV. If that bit is set, the effect of
1393 // the XOR is to toggle the bit. If it is clear, then the ADD has
1394 // no effect.
1395 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1396 TheAnd.setOperand(0, X);
1397 return &TheAnd;
1398 } else {
1399 std::string Name = Op->getName(); Op->setName("");
1400 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001401 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001402 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001403 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001404 }
1405 }
1406 }
1407 }
1408 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001409
1410 case Instruction::Shl: {
1411 // We know that the AND will not produce any of the bits shifted in, so if
1412 // the anded constant includes them, clear them now!
1413 //
1414 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001415 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1416 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1417
1418 if (CI == ShlMask) { // Masking out bits that the shift already masks
1419 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1420 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001421 TheAnd.setOperand(1, CI);
1422 return &TheAnd;
1423 }
1424 break;
1425 }
1426 case Instruction::Shr:
1427 // We know that the AND will not produce any of the bits shifted in, so if
1428 // the anded constant includes them, clear them now! This only applies to
1429 // unsigned shifts, because a signed shr may bring in set bits!
1430 //
1431 if (AndRHS->getType()->isUnsigned()) {
1432 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001433 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1434 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1435
1436 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1437 return ReplaceInstUsesWith(TheAnd, Op);
1438 } else if (CI != AndRHS) {
1439 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001440 return &TheAnd;
1441 }
Chris Lattner7e794272004-09-24 15:21:34 +00001442 } else { // Signed shr.
1443 // See if this is shifting in some sign extension, then masking it out
1444 // with an and.
1445 if (Op->hasOneUse()) {
1446 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1447 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1448 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner5c3c21e2004-10-22 04:53:16 +00001449 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner7e794272004-09-24 15:21:34 +00001450 // Make the argument unsigned.
1451 Value *ShVal = Op->getOperand(0);
1452 ShVal = InsertCastBefore(ShVal,
1453 ShVal->getType()->getUnsignedVersion(),
1454 TheAnd);
1455 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1456 OpRHS, Op->getName()),
1457 TheAnd);
Chris Lattner70c20392004-10-27 05:57:15 +00001458 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1459 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1460 TheAnd.getName()),
1461 TheAnd);
Chris Lattner7e794272004-09-24 15:21:34 +00001462 return new CastInst(ShVal, Op->getType());
1463 }
1464 }
Chris Lattner2da29172003-09-19 19:05:02 +00001465 }
1466 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001467 }
1468 return 0;
1469}
1470
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001471
Chris Lattner6862fbd2004-09-29 17:40:11 +00001472/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1473/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1474/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1475/// insert new instructions.
1476Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1477 bool Inside, Instruction &IB) {
1478 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1479 "Lo is not <= Hi in range emission code!");
1480 if (Inside) {
1481 if (Lo == Hi) // Trivially false.
1482 return new SetCondInst(Instruction::SetNE, V, V);
1483 if (cast<ConstantIntegral>(Lo)->isMinValue())
1484 return new SetCondInst(Instruction::SetLT, V, Hi);
1485
1486 Constant *AddCST = ConstantExpr::getNeg(Lo);
1487 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1488 InsertNewInstBefore(Add, IB);
1489 // Convert to unsigned for the comparison.
1490 const Type *UnsType = Add->getType()->getUnsignedVersion();
1491 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1492 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1493 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1494 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1495 }
1496
1497 if (Lo == Hi) // Trivially true.
1498 return new SetCondInst(Instruction::SetEQ, V, V);
1499
1500 Hi = SubOne(cast<ConstantInt>(Hi));
1501 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1502 return new SetCondInst(Instruction::SetGT, V, Hi);
1503
1504 // Emit X-Lo > Hi-Lo-1
1505 Constant *AddCST = ConstantExpr::getNeg(Lo);
1506 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1507 InsertNewInstBefore(Add, IB);
1508 // Convert to unsigned for the comparison.
1509 const Type *UnsType = Add->getType()->getUnsignedVersion();
1510 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1511 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1512 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1513 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1514}
1515
1516
Chris Lattner113f4f42002-06-25 16:13:24 +00001517Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001518 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001519 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001520
Chris Lattner81a7a232004-10-16 18:11:37 +00001521 if (isa<UndefValue>(Op1)) // X & undef -> 0
1522 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1523
Chris Lattner86102b82005-01-01 16:22:27 +00001524 // and X, X = X
1525 if (Op0 == Op1)
Chris Lattnere6794492002-08-12 21:17:25 +00001526 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001527
1528 // and X, -1 == X
Chris Lattner86102b82005-01-01 16:22:27 +00001529 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
1530 if (AndRHS->isAllOnesValue()) // and X, -1 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001531 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001532
Chris Lattner86102b82005-01-01 16:22:27 +00001533 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1534 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1535
1536 // If the mask is not masking out any bits, there is no reason to do the
1537 // and in the first place.
1538 if (MaskedValueIsZero(Op0,
1539 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS))))
1540 return ReplaceInstUsesWith(I, Op0);
1541
Chris Lattnerba1cb382003-09-19 17:17:26 +00001542 // Optimize a variety of ((val OP C1) & C2) combinations...
1543 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1544 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner86102b82005-01-01 16:22:27 +00001545 Value *Op0LHS = Op0I->getOperand(0);
1546 Value *Op0RHS = Op0I->getOperand(1);
1547 switch (Op0I->getOpcode()) {
1548 case Instruction::Xor:
1549 case Instruction::Or:
1550 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1551 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1552 if (MaskedValueIsZero(Op0LHS, AndRHS))
1553 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1554 if (MaskedValueIsZero(Op0RHS, AndRHS))
1555 return BinaryOperator::createAnd(Op0LHS, AndRHS);
1556 break;
1557 case Instruction::And:
1558 // (X & V) & C2 --> 0 iff (V & C2) == 0
1559 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1560 MaskedValueIsZero(Op0RHS, AndRHS))
1561 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1562 break;
1563 }
1564
Chris Lattner16464b32003-07-23 19:25:52 +00001565 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner86102b82005-01-01 16:22:27 +00001566 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001567 return Res;
Chris Lattner86102b82005-01-01 16:22:27 +00001568 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1569 const Type *SrcTy = CI->getOperand(0)->getType();
1570
1571 // If this is an integer sign or zero extension instruction.
1572 if (SrcTy->isIntegral() &&
1573 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
1574
1575 if (SrcTy->isUnsigned()) {
1576 // See if this and is clearing out bits that are known to be zero
1577 // anyway (due to the zero extension).
1578 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1579 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1580 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1581 if (Result == Mask) // The "and" isn't doing anything, remove it.
1582 return ReplaceInstUsesWith(I, CI);
1583 if (Result != AndRHS) { // Reduce the and RHS constant.
1584 I.setOperand(1, Result);
1585 return &I;
1586 }
1587
1588 } else {
1589 if (CI->hasOneUse() && SrcTy->isInteger()) {
1590 // We can only do this if all of the sign bits brought in are masked
1591 // out. Compute this by first getting 0000011111, then inverting
1592 // it.
1593 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1594 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1595 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1596 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1597 // If the and is clearing all of the sign bits, change this to a
1598 // zero extension cast. To do this, cast the cast input to
1599 // unsigned, then to the requested size.
1600 Value *CastOp = CI->getOperand(0);
1601 Instruction *NC =
1602 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1603 CI->getName()+".uns");
1604 NC = InsertNewInstBefore(NC, I);
1605 // Finally, insert a replacement for CI.
1606 NC = new CastInst(NC, CI->getType(), CI->getName());
1607 CI->setName("");
1608 NC = InsertNewInstBefore(NC, I);
1609 WorkList.push_back(CI); // Delete CI later.
1610 I.setOperand(0, NC);
1611 return &I; // The AND operand was modified.
1612 }
1613 }
1614 }
1615 }
Chris Lattner33217db2003-07-23 19:36:21 +00001616 }
Chris Lattner183b3362004-04-09 19:05:30 +00001617
1618 // Try to fold constant and into select arguments.
1619 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001620 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001621 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001622 if (isa<PHINode>(Op0))
1623 if (Instruction *NV = FoldOpIntoPhi(I))
1624 return NV;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001625 }
1626
Chris Lattnerbb74e222003-03-10 23:06:50 +00001627 Value *Op0NotVal = dyn_castNotVal(Op0);
1628 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001629
Chris Lattner023a4832004-06-18 06:07:51 +00001630 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1631 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1632
Misha Brukman9c003d82004-07-30 12:50:08 +00001633 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001634 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001635 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1636 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001637 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001638 return BinaryOperator::createNot(Or);
1639 }
1640
Chris Lattner623826c2004-09-28 21:48:02 +00001641 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1642 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattner3ac7c262003-08-13 20:16:26 +00001643 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1644 return R;
1645
Chris Lattner623826c2004-09-28 21:48:02 +00001646 Value *LHSVal, *RHSVal;
1647 ConstantInt *LHSCst, *RHSCst;
1648 Instruction::BinaryOps LHSCC, RHSCC;
1649 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1650 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1651 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1652 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1653 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1654 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1655 // Ensure that the larger constant is on the RHS.
1656 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1657 SetCondInst *LHS = cast<SetCondInst>(Op0);
1658 if (cast<ConstantBool>(Cmp)->getValue()) {
1659 std::swap(LHS, RHS);
1660 std::swap(LHSCst, RHSCst);
1661 std::swap(LHSCC, RHSCC);
1662 }
1663
1664 // At this point, we know we have have two setcc instructions
1665 // comparing a value against two constants and and'ing the result
1666 // together. Because of the above check, we know that we only have
1667 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1668 // FoldSetCCLogical check above), that the two constants are not
1669 // equal.
1670 assert(LHSCst != RHSCst && "Compares not folded above?");
1671
1672 switch (LHSCC) {
1673 default: assert(0 && "Unknown integer condition code!");
1674 case Instruction::SetEQ:
1675 switch (RHSCC) {
1676 default: assert(0 && "Unknown integer condition code!");
1677 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1678 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1679 return ReplaceInstUsesWith(I, ConstantBool::False);
1680 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1681 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1682 return ReplaceInstUsesWith(I, LHS);
1683 }
1684 case Instruction::SetNE:
1685 switch (RHSCC) {
1686 default: assert(0 && "Unknown integer condition code!");
1687 case Instruction::SetLT:
1688 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1689 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1690 break; // (X != 13 & X < 15) -> no change
1691 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1692 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1693 return ReplaceInstUsesWith(I, RHS);
1694 case Instruction::SetNE:
1695 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1696 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1697 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1698 LHSVal->getName()+".off");
1699 InsertNewInstBefore(Add, I);
1700 const Type *UnsType = Add->getType()->getUnsignedVersion();
1701 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1702 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1703 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1704 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1705 }
1706 break; // (X != 13 & X != 15) -> no change
1707 }
1708 break;
1709 case Instruction::SetLT:
1710 switch (RHSCC) {
1711 default: assert(0 && "Unknown integer condition code!");
1712 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1713 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1714 return ReplaceInstUsesWith(I, ConstantBool::False);
1715 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1716 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1717 return ReplaceInstUsesWith(I, LHS);
1718 }
1719 case Instruction::SetGT:
1720 switch (RHSCC) {
1721 default: assert(0 && "Unknown integer condition code!");
1722 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1723 return ReplaceInstUsesWith(I, LHS);
1724 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1725 return ReplaceInstUsesWith(I, RHS);
1726 case Instruction::SetNE:
1727 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1728 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1729 break; // (X > 13 & X != 15) -> no change
Chris Lattner6862fbd2004-09-29 17:40:11 +00001730 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1731 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner623826c2004-09-28 21:48:02 +00001732 }
1733 }
1734 }
1735 }
1736
Chris Lattner113f4f42002-06-25 16:13:24 +00001737 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001738}
1739
Chris Lattner113f4f42002-06-25 16:13:24 +00001740Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001741 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001742 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001743
Chris Lattner81a7a232004-10-16 18:11:37 +00001744 if (isa<UndefValue>(Op1))
1745 return ReplaceInstUsesWith(I, // X | undef -> -1
1746 ConstantIntegral::getAllOnesValue(I.getType()));
1747
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001748 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001749 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1750 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001751
1752 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001753 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner86102b82005-01-01 16:22:27 +00001754 // If X is known to only contain bits that already exist in RHS, just
1755 // replace this instruction with RHS directly.
1756 if (MaskedValueIsZero(Op0,
1757 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
1758 return ReplaceInstUsesWith(I, RHS);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001759
Chris Lattnerd4252a72004-07-30 07:50:03 +00001760 ConstantInt *C1; Value *X;
1761 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1762 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1763 std::string Op0Name = Op0->getName(); Op0->setName("");
1764 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1765 InsertNewInstBefore(Or, I);
1766 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1767 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001768
Chris Lattnerd4252a72004-07-30 07:50:03 +00001769 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1770 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1771 std::string Op0Name = Op0->getName(); Op0->setName("");
1772 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1773 InsertNewInstBefore(Or, I);
1774 return BinaryOperator::createXor(Or,
1775 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001776 }
Chris Lattner183b3362004-04-09 19:05:30 +00001777
1778 // Try to fold constant and into select arguments.
1779 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001780 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001781 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00001782 if (isa<PHINode>(Op0))
1783 if (Instruction *NV = FoldOpIntoPhi(I))
1784 return NV;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001785 }
1786
Chris Lattner812aab72003-08-12 19:11:07 +00001787 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001788 Value *A, *B; ConstantInt *C1, *C2;
1789 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1790 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1791 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001792
Chris Lattnerd4252a72004-07-30 07:50:03 +00001793 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1794 if (A == Op1) // ~A | A == -1
1795 return ReplaceInstUsesWith(I,
1796 ConstantIntegral::getAllOnesValue(I.getType()));
1797 } else {
1798 A = 0;
1799 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001800
Chris Lattnerd4252a72004-07-30 07:50:03 +00001801 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1802 if (Op0 == B)
1803 return ReplaceInstUsesWith(I,
1804 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001805
Misha Brukman9c003d82004-07-30 12:50:08 +00001806 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001807 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1808 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1809 I.getName()+".demorgan"), I);
1810 return BinaryOperator::createNot(And);
1811 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001812 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001813
Chris Lattner3ac7c262003-08-13 20:16:26 +00001814 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001815 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattner3ac7c262003-08-13 20:16:26 +00001816 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1817 return R;
1818
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001819 Value *LHSVal, *RHSVal;
1820 ConstantInt *LHSCst, *RHSCst;
1821 Instruction::BinaryOps LHSCC, RHSCC;
1822 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1823 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1824 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1825 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1826 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1827 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1828 // Ensure that the larger constant is on the RHS.
1829 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1830 SetCondInst *LHS = cast<SetCondInst>(Op0);
1831 if (cast<ConstantBool>(Cmp)->getValue()) {
1832 std::swap(LHS, RHS);
1833 std::swap(LHSCst, RHSCst);
1834 std::swap(LHSCC, RHSCC);
1835 }
1836
1837 // At this point, we know we have have two setcc instructions
1838 // comparing a value against two constants and or'ing the result
1839 // together. Because of the above check, we know that we only have
1840 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1841 // FoldSetCCLogical check above), that the two constants are not
1842 // equal.
1843 assert(LHSCst != RHSCst && "Compares not folded above?");
1844
1845 switch (LHSCC) {
1846 default: assert(0 && "Unknown integer condition code!");
1847 case Instruction::SetEQ:
1848 switch (RHSCC) {
1849 default: assert(0 && "Unknown integer condition code!");
1850 case Instruction::SetEQ:
1851 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1852 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1853 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1854 LHSVal->getName()+".off");
1855 InsertNewInstBefore(Add, I);
1856 const Type *UnsType = Add->getType()->getUnsignedVersion();
1857 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1858 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1859 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1860 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1861 }
1862 break; // (X == 13 | X == 15) -> no change
1863
1864 case Instruction::SetGT:
1865 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1866 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1867 break; // (X == 13 | X > 15) -> no change
1868 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1869 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1870 return ReplaceInstUsesWith(I, RHS);
1871 }
1872 break;
1873 case Instruction::SetNE:
1874 switch (RHSCC) {
1875 default: assert(0 && "Unknown integer condition code!");
1876 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1877 return ReplaceInstUsesWith(I, RHS);
1878 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1879 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1880 return ReplaceInstUsesWith(I, LHS);
1881 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1882 return ReplaceInstUsesWith(I, ConstantBool::True);
1883 }
1884 break;
1885 case Instruction::SetLT:
1886 switch (RHSCC) {
1887 default: assert(0 && "Unknown integer condition code!");
1888 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1889 break;
Chris Lattner6862fbd2004-09-29 17:40:11 +00001890 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1891 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerdcf756e2004-09-28 22:33:08 +00001892 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1893 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1894 return ReplaceInstUsesWith(I, RHS);
1895 }
1896 break;
1897 case Instruction::SetGT:
1898 switch (RHSCC) {
1899 default: assert(0 && "Unknown integer condition code!");
1900 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1901 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1902 return ReplaceInstUsesWith(I, LHS);
1903 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1904 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1905 return ReplaceInstUsesWith(I, ConstantBool::True);
1906 }
1907 }
1908 }
1909 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001910 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001911}
1912
Chris Lattnerc2076352004-02-16 01:20:27 +00001913// XorSelf - Implements: X ^ X --> 0
1914struct XorSelf {
1915 Value *RHS;
1916 XorSelf(Value *rhs) : RHS(rhs) {}
1917 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1918 Instruction *apply(BinaryOperator &Xor) const {
1919 return &Xor;
1920 }
1921};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001922
1923
Chris Lattner113f4f42002-06-25 16:13:24 +00001924Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001925 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001926 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001927
Chris Lattner81a7a232004-10-16 18:11:37 +00001928 if (isa<UndefValue>(Op1))
1929 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1930
Chris Lattnerc2076352004-02-16 01:20:27 +00001931 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1932 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1933 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001934 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001935 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001936
Chris Lattner97638592003-07-23 21:37:07 +00001937 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001938 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001939 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001940 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001941
Chris Lattner97638592003-07-23 21:37:07 +00001942 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001943 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001944 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001945 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001946 return new SetCondInst(SCI->getInverseCondition(),
1947 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001948
Chris Lattner8f2f5982003-11-05 01:06:05 +00001949 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001950 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1951 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001952 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1953 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001954 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001955 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001956 }
Chris Lattner023a4832004-06-18 06:07:51 +00001957
1958 // ~(~X & Y) --> (X | ~Y)
1959 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1960 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1961 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1962 Instruction *NotY =
1963 BinaryOperator::createNot(Op0I->getOperand(1),
1964 Op0I->getOperand(1)->getName()+".not");
1965 InsertNewInstBefore(NotY, I);
1966 return BinaryOperator::createOr(Op0NotVal, NotY);
1967 }
1968 }
Chris Lattner97638592003-07-23 21:37:07 +00001969
1970 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001971 switch (Op0I->getOpcode()) {
1972 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001973 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001974 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001975 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1976 return BinaryOperator::createSub(
1977 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001978 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001979 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001980 }
Chris Lattnere5806662003-11-04 23:50:51 +00001981 break;
1982 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001983 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001984 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1985 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001986 break;
1987 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001988 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001989 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001990 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001991 break;
1992 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001993 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001994 }
Chris Lattner183b3362004-04-09 19:05:30 +00001995
1996 // Try to fold constant and into select arguments.
1997 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00001998 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00001999 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002000 if (isa<PHINode>(Op0))
2001 if (Instruction *NV = FoldOpIntoPhi(I))
2002 return NV;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002003 }
2004
Chris Lattnerbb74e222003-03-10 23:06:50 +00002005 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002006 if (X == Op1)
2007 return ReplaceInstUsesWith(I,
2008 ConstantIntegral::getAllOnesValue(I.getType()));
2009
Chris Lattnerbb74e222003-03-10 23:06:50 +00002010 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00002011 if (X == Op0)
2012 return ReplaceInstUsesWith(I,
2013 ConstantIntegral::getAllOnesValue(I.getType()));
2014
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002015 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00002016 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002017 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2018 cast<BinaryOperator>(Op1I)->swapOperands();
2019 I.swapOperands();
2020 std::swap(Op0, Op1);
2021 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2022 I.swapOperands();
2023 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00002024 }
2025 } else if (Op1I->getOpcode() == Instruction::Xor) {
2026 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2027 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2028 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2029 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2030 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002031
2032 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002033 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002034 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2035 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002036 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00002037 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2038 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002039 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002040 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00002041 } else if (Op0I->getOpcode() == Instruction::Xor) {
2042 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2043 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2044 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2045 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00002046 }
2047
Chris Lattner7aa2d472004-08-01 19:42:59 +00002048 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00002049 Value *A, *B; ConstantInt *C1, *C2;
2050 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2051 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00002052 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00002053 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00002054
Chris Lattner3ac7c262003-08-13 20:16:26 +00002055 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2056 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2057 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2058 return R;
2059
Chris Lattner113f4f42002-06-25 16:13:24 +00002060 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002061}
2062
Chris Lattner6862fbd2004-09-29 17:40:11 +00002063/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2064/// overflowed for this type.
2065static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2066 ConstantInt *In2) {
2067 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2068 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2069}
2070
2071static bool isPositive(ConstantInt *C) {
2072 return cast<ConstantSInt>(C)->getValue() >= 0;
2073}
2074
2075/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2076/// overflowed for this type.
2077static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2078 ConstantInt *In2) {
2079 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2080
2081 if (In1->getType()->isUnsigned())
2082 return cast<ConstantUInt>(Result)->getValue() <
2083 cast<ConstantUInt>(In1)->getValue();
2084 if (isPositive(In1) != isPositive(In2))
2085 return false;
2086 if (isPositive(In1))
2087 return cast<ConstantSInt>(Result)->getValue() <
2088 cast<ConstantSInt>(In1)->getValue();
2089 return cast<ConstantSInt>(Result)->getValue() >
2090 cast<ConstantSInt>(In1)->getValue();
2091}
2092
Chris Lattner0798af32005-01-13 20:14:25 +00002093/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2094/// code necessary to compute the offset from the base pointer (without adding
2095/// in the base pointer). Return the result as a signed integer of intptr size.
2096static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2097 TargetData &TD = IC.getTargetData();
2098 gep_type_iterator GTI = gep_type_begin(GEP);
2099 const Type *UIntPtrTy = TD.getIntPtrType();
2100 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2101 Value *Result = Constant::getNullValue(SIntPtrTy);
2102
2103 // Build a mask for high order bits.
2104 uint64_t PtrSizeMask = ~0ULL;
2105 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2106
2107 ++GTI; // Measure type stepping over.
2108 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2109 Value *Op = GEP->getOperand(i);
2110 uint64_t Size = TD.getTypeSize(*GTI) & PtrSizeMask;
2111 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2112 SIntPtrTy);
2113 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2114 if (!OpC->isNullValue()) {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002115 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner0798af32005-01-13 20:14:25 +00002116 Scale = ConstantExpr::getMul(OpC, Scale);
2117 if (Constant *RC = dyn_cast<Constant>(Result))
2118 Result = ConstantExpr::getAdd(RC, Scale);
2119 else {
2120 // Emit an add instruction.
2121 Result = IC.InsertNewInstBefore(
2122 BinaryOperator::createAdd(Result, Scale,
2123 GEP->getName()+".offs"), I);
2124 }
2125 }
2126 } else {
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002127 //if (Op->getType() != Scale->getType())
2128 if (Size != 1) {
2129 // Convert to correct type.
2130 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2131 Op->getName()+".c"), I);
2132
2133 // We'll let instcombine(mul) convert this to a shl if possible.
2134 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2135 GEP->getName()+".idx"), I);
2136 }
Chris Lattner0798af32005-01-13 20:14:25 +00002137
2138 // Emit an add instruction.
Chris Lattner4cb9fa32005-01-13 20:40:58 +00002139 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner0798af32005-01-13 20:14:25 +00002140 GEP->getName()+".offs"), I);
2141 }
2142 }
2143 return Result;
2144}
2145
2146/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2147/// else. At this point we know that the GEP is on the LHS of the comparison.
2148Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2149 Instruction::BinaryOps Cond,
2150 Instruction &I) {
2151 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattner81e84172005-01-13 22:25:21 +00002152
2153 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2154 if (isa<PointerType>(CI->getOperand(0)->getType()))
2155 RHS = CI->getOperand(0);
2156
Chris Lattner0798af32005-01-13 20:14:25 +00002157 Value *PtrBase = GEPLHS->getOperand(0);
2158 if (PtrBase == RHS) {
2159 // As an optimization, we don't actually have to compute the actual value of
2160 // OFFSET if this is a seteq or setne comparison, just return whether each
2161 // index is zero or not.
Chris Lattner81e84172005-01-13 22:25:21 +00002162 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2163 Instruction *InVal = 0;
2164 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i) {
2165 bool EmitIt = true;
2166 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2167 if (isa<UndefValue>(C)) // undef index -> undef.
2168 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2169 if (C->isNullValue())
2170 EmitIt = false;
2171 else if (isa<ConstantInt>(C))
2172 return ReplaceInstUsesWith(I, // No comparison is needed here.
2173 ConstantBool::get(Cond == Instruction::SetNE));
2174 }
2175
2176 if (EmitIt) {
2177 Instruction *Comp =
2178 new SetCondInst(Cond, GEPLHS->getOperand(i),
2179 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2180 if (InVal == 0)
2181 InVal = Comp;
2182 else {
2183 InVal = InsertNewInstBefore(InVal, I);
2184 InsertNewInstBefore(Comp, I);
2185 if (Cond == Instruction::SetNE) // True if any are unequal
2186 InVal = BinaryOperator::createOr(InVal, Comp);
2187 else // True if all are equal
2188 InVal = BinaryOperator::createAnd(InVal, Comp);
2189 }
2190 }
2191 }
2192
2193 if (InVal)
2194 return InVal;
2195 else
2196 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2197 ConstantBool::get(Cond == Instruction::SetEQ));
2198 }
Chris Lattner0798af32005-01-13 20:14:25 +00002199
2200 // Only lower this if the setcc is the only user of the GEP or if we expect
2201 // the result to fold to a constant!
2202 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2203 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2204 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2205 return new SetCondInst(Cond, Offset,
2206 Constant::getNullValue(Offset->getType()));
2207 }
2208 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2209 if (PtrBase != GEPRHS->getOperand(0))
2210 return 0;
2211
Chris Lattner81e84172005-01-13 22:25:21 +00002212 // If one of the GEPs has all zero indices, recurse.
2213 bool AllZeros = true;
2214 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2215 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2216 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2217 AllZeros = false;
2218 break;
2219 }
2220 if (AllZeros)
2221 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2222 SetCondInst::getSwappedCondition(Cond), I);
2223 AllZeros = true;
2224 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2225 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2226 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2227 AllZeros = false;
2228 break;
2229 }
2230 if (AllZeros)
2231 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2232
Chris Lattner0798af32005-01-13 20:14:25 +00002233 // Only lower this if the setcc is the only user of the GEP or if we expect
2234 // the result to fold to a constant!
2235 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2236 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2237 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2238 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2239 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2240 return new SetCondInst(Cond, L, R);
2241 }
2242 }
2243 return 0;
2244}
2245
2246
Chris Lattner113f4f42002-06-25 16:13:24 +00002247Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00002248 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002249 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2250 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002251
2252 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002253 if (Op0 == Op1)
2254 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00002255
Chris Lattner81a7a232004-10-16 18:11:37 +00002256 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2257 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2258
Chris Lattner15ff1e12004-11-14 07:33:16 +00002259 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2260 // addresses never equal each other! We already know that Op0 != Op1.
2261 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2262 isa<ConstantPointerNull>(Op0)) &&
2263 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2264 isa<ConstantPointerNull>(Op1)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002265 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2266
2267 // setcc's with boolean values can always be turned into bitwise operations
2268 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00002269 switch (I.getOpcode()) {
2270 default: assert(0 && "Invalid setcc instruction!");
2271 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002272 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002273 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00002274 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002275 }
Chris Lattner4456da62004-08-11 00:50:51 +00002276 case Instruction::SetNE:
2277 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002278
Chris Lattner4456da62004-08-11 00:50:51 +00002279 case Instruction::SetGT:
2280 std::swap(Op0, Op1); // Change setgt -> setlt
2281 // FALL THROUGH
2282 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2283 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2284 InsertNewInstBefore(Not, I);
2285 return BinaryOperator::createAnd(Not, Op1);
2286 }
2287 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002288 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00002289 // FALL THROUGH
2290 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2291 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2292 InsertNewInstBefore(Not, I);
2293 return BinaryOperator::createOr(Not, Op1);
2294 }
2295 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002296 }
2297
Chris Lattner2dd01742004-06-09 04:24:29 +00002298 // See if we are doing a comparison between a constant and an instruction that
2299 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00002300 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002301 // Check to see if we are comparing against the minimum or maximum value...
2302 if (CI->isMinValue()) {
2303 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2304 return ReplaceInstUsesWith(I, ConstantBool::False);
2305 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2306 return ReplaceInstUsesWith(I, ConstantBool::True);
2307 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2308 return BinaryOperator::createSetEQ(Op0, Op1);
2309 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2310 return BinaryOperator::createSetNE(Op0, Op1);
2311
2312 } else if (CI->isMaxValue()) {
2313 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2314 return ReplaceInstUsesWith(I, ConstantBool::False);
2315 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2316 return ReplaceInstUsesWith(I, ConstantBool::True);
2317 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2318 return BinaryOperator::createSetEQ(Op0, Op1);
2319 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2320 return BinaryOperator::createSetNE(Op0, Op1);
2321
2322 // Comparing against a value really close to min or max?
2323 } else if (isMinValuePlusOne(CI)) {
2324 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2325 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2326 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2327 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2328
2329 } else if (isMaxValueMinusOne(CI)) {
2330 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2331 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2332 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2333 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2334 }
2335
2336 // If we still have a setle or setge instruction, turn it into the
2337 // appropriate setlt or setgt instruction. Since the border cases have
2338 // already been handled above, this requires little checking.
2339 //
2340 if (I.getOpcode() == Instruction::SetLE)
2341 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2342 if (I.getOpcode() == Instruction::SetGE)
2343 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2344
Chris Lattnere1e10e12004-05-25 06:32:08 +00002345 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002346 switch (LHSI->getOpcode()) {
Chris Lattner6a4adcd2004-09-29 05:07:12 +00002347 case Instruction::PHI:
2348 if (Instruction *NV = FoldOpIntoPhi(I))
2349 return NV;
2350 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002351 case Instruction::And:
2352 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2353 LHSI->getOperand(0)->hasOneUse()) {
2354 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2355 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2356 // happens a LOT in code produced by the C front-end, for bitfield
2357 // access.
2358 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2359 ConstantUInt *ShAmt;
2360 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2361 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2362 const Type *Ty = LHSI->getType();
2363
2364 // We can fold this as long as we can't shift unknown bits
2365 // into the mask. This can only happen with signed shift
2366 // rights, as they sign-extend.
2367 if (ShAmt) {
2368 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner6afc02f2004-09-28 17:54:07 +00002369 Shift->getType()->isUnsigned();
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002370 if (!CanFold) {
2371 // To test for the bad case of the signed shr, see if any
2372 // of the bits shifted in could be tested after the mask.
2373 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00002374 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002375 Constant *ShVal =
2376 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2377 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2378 CanFold = true;
2379 }
2380
2381 if (CanFold) {
Chris Lattner6afc02f2004-09-28 17:54:07 +00002382 Constant *NewCst;
2383 if (Shift->getOpcode() == Instruction::Shl)
2384 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2385 else
2386 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002387
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002388 // Check to see if we are shifting out any of the bits being
2389 // compared.
2390 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2391 // If we shifted bits out, the fold is not going to work out.
2392 // As a special case, check to see if this means that the
2393 // result is always true or false now.
2394 if (I.getOpcode() == Instruction::SetEQ)
2395 return ReplaceInstUsesWith(I, ConstantBool::False);
2396 if (I.getOpcode() == Instruction::SetNE)
2397 return ReplaceInstUsesWith(I, ConstantBool::True);
2398 } else {
2399 I.setOperand(1, NewCst);
Chris Lattner6afc02f2004-09-28 17:54:07 +00002400 Constant *NewAndCST;
2401 if (Shift->getOpcode() == Instruction::Shl)
2402 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2403 else
2404 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2405 LHSI->setOperand(1, NewAndCST);
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002406 LHSI->setOperand(0, Shift->getOperand(0));
2407 WorkList.push_back(Shift); // Shift is dead.
2408 AddUsesToWorkList(I);
2409 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00002410 }
2411 }
Chris Lattner35167c32004-06-09 07:59:58 +00002412 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002413 }
2414 break;
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002415
Reid Spencer279fa252004-11-28 21:31:15 +00002416 // (setcc (cast X to larger), CI)
2417 case Instruction::Cast: {
2418 Instruction* replacement =
2419 visitSetCondInstWithCastAndConstant(I,cast<CastInst>(LHSI),CI);
2420 if (replacement)
2421 return replacement;
Chris Lattnerbe7a69e2004-09-29 03:09:18 +00002422 break;
2423 }
Reid Spencer279fa252004-11-28 21:31:15 +00002424
Chris Lattner272d5ca2004-09-28 18:22:15 +00002425 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2426 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2427 switch (I.getOpcode()) {
2428 default: break;
2429 case Instruction::SetEQ:
2430 case Instruction::SetNE: {
2431 // If we are comparing against bits always shifted out, the
2432 // comparison cannot succeed.
2433 Constant *Comp =
2434 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2435 if (Comp != CI) {// Comparing against a bit that we know is zero.
2436 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2437 Constant *Cst = ConstantBool::get(IsSetNE);
2438 return ReplaceInstUsesWith(I, Cst);
2439 }
2440
2441 if (LHSI->hasOneUse()) {
2442 // Otherwise strength reduce the shift into an and.
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002443 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002444 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2445 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2446
2447 Constant *Mask;
2448 if (CI->getType()->isUnsigned()) {
2449 Mask = ConstantUInt::get(CI->getType(), Val);
2450 } else if (ShAmtVal != 0) {
2451 Mask = ConstantSInt::get(CI->getType(), Val);
2452 } else {
2453 Mask = ConstantInt::getAllOnesValue(CI->getType());
2454 }
2455
2456 Instruction *AndI =
2457 BinaryOperator::createAnd(LHSI->getOperand(0),
2458 Mask, LHSI->getName()+".mask");
2459 Value *And = InsertNewInstBefore(AndI, I);
2460 return new SetCondInst(I.getOpcode(), And,
2461 ConstantExpr::getUShr(CI, ShAmt));
2462 }
2463 }
2464 }
2465 }
2466 break;
2467
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002468 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattner1023b872004-09-27 16:18:50 +00002469 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattner1023b872004-09-27 16:18:50 +00002470 switch (I.getOpcode()) {
2471 default: break;
2472 case Instruction::SetEQ:
2473 case Instruction::SetNE: {
2474 // If we are comparing against bits always shifted out, the
2475 // comparison cannot succeed.
2476 Constant *Comp =
2477 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2478
2479 if (Comp != CI) {// Comparing against a bit that we know is zero.
2480 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2481 Constant *Cst = ConstantBool::get(IsSetNE);
2482 return ReplaceInstUsesWith(I, Cst);
2483 }
2484
2485 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00002486 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner272d5ca2004-09-28 18:22:15 +00002487
Chris Lattner1023b872004-09-27 16:18:50 +00002488 // Otherwise strength reduce the shift into an and.
2489 uint64_t Val = ~0ULL; // All ones.
2490 Val <<= ShAmtVal; // Shift over to the right spot.
2491
2492 Constant *Mask;
2493 if (CI->getType()->isUnsigned()) {
2494 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2495 Val &= (1ULL << TypeBits)-1;
2496 Mask = ConstantUInt::get(CI->getType(), Val);
2497 } else {
2498 Mask = ConstantSInt::get(CI->getType(), Val);
2499 }
2500
2501 Instruction *AndI =
2502 BinaryOperator::createAnd(LHSI->getOperand(0),
2503 Mask, LHSI->getName()+".mask");
2504 Value *And = InsertNewInstBefore(AndI, I);
2505 return new SetCondInst(I.getOpcode(), And,
2506 ConstantExpr::getShl(CI, ShAmt));
2507 }
2508 break;
2509 }
2510 }
2511 }
2512 break;
Chris Lattner7e794272004-09-24 15:21:34 +00002513
Chris Lattner6862fbd2004-09-29 17:40:11 +00002514 case Instruction::Div:
2515 // Fold: (div X, C1) op C2 -> range check
2516 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2517 // Fold this div into the comparison, producing a range check.
2518 // Determine, based on the divide type, what the range is being
2519 // checked. If there is an overflow on the low or high side, remember
2520 // it, otherwise compute the range [low, hi) bounding the new value.
2521 bool LoOverflow = false, HiOverflow = 0;
2522 ConstantInt *LoBound = 0, *HiBound = 0;
2523
2524 ConstantInt *Prod;
2525 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2526
Chris Lattnera92af962004-10-11 19:40:04 +00002527 Instruction::BinaryOps Opcode = I.getOpcode();
2528
Chris Lattner6862fbd2004-09-29 17:40:11 +00002529 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2530 } else if (LHSI->getType()->isUnsigned()) { // udiv
2531 LoBound = Prod;
2532 LoOverflow = ProdOV;
2533 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2534 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2535 if (CI->isNullValue()) { // (X / pos) op 0
2536 // Can't overflow.
2537 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2538 HiBound = DivRHS;
2539 } else if (isPositive(CI)) { // (X / pos) op pos
2540 LoBound = Prod;
2541 LoOverflow = ProdOV;
2542 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2543 } else { // (X / pos) op neg
2544 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2545 LoOverflow = AddWithOverflow(LoBound, Prod,
2546 cast<ConstantInt>(DivRHSH));
2547 HiBound = Prod;
2548 HiOverflow = ProdOV;
2549 }
2550 } else { // Divisor is < 0.
2551 if (CI->isNullValue()) { // (X / neg) op 0
2552 LoBound = AddOne(DivRHS);
2553 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2554 } else if (isPositive(CI)) { // (X / neg) op pos
2555 HiOverflow = LoOverflow = ProdOV;
2556 if (!LoOverflow)
2557 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2558 HiBound = AddOne(Prod);
2559 } else { // (X / neg) op neg
2560 LoBound = Prod;
2561 LoOverflow = HiOverflow = ProdOV;
2562 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2563 }
Chris Lattner0b41e862004-10-08 19:15:44 +00002564
Chris Lattnera92af962004-10-11 19:40:04 +00002565 // Dividing by a negate swaps the condition.
2566 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattner6862fbd2004-09-29 17:40:11 +00002567 }
2568
2569 if (LoBound) {
2570 Value *X = LHSI->getOperand(0);
Chris Lattnera92af962004-10-11 19:40:04 +00002571 switch (Opcode) {
Chris Lattner6862fbd2004-09-29 17:40:11 +00002572 default: assert(0 && "Unhandled setcc opcode!");
2573 case Instruction::SetEQ:
2574 if (LoOverflow && HiOverflow)
2575 return ReplaceInstUsesWith(I, ConstantBool::False);
2576 else if (HiOverflow)
2577 return new SetCondInst(Instruction::SetGE, X, LoBound);
2578 else if (LoOverflow)
2579 return new SetCondInst(Instruction::SetLT, X, HiBound);
2580 else
2581 return InsertRangeTest(X, LoBound, HiBound, true, I);
2582 case Instruction::SetNE:
2583 if (LoOverflow && HiOverflow)
2584 return ReplaceInstUsesWith(I, ConstantBool::True);
2585 else if (HiOverflow)
2586 return new SetCondInst(Instruction::SetLT, X, LoBound);
2587 else if (LoOverflow)
2588 return new SetCondInst(Instruction::SetGE, X, HiBound);
2589 else
2590 return InsertRangeTest(X, LoBound, HiBound, false, I);
2591 case Instruction::SetLT:
2592 if (LoOverflow)
2593 return ReplaceInstUsesWith(I, ConstantBool::False);
2594 return new SetCondInst(Instruction::SetLT, X, LoBound);
2595 case Instruction::SetGT:
2596 if (HiOverflow)
2597 return ReplaceInstUsesWith(I, ConstantBool::False);
2598 return new SetCondInst(Instruction::SetGE, X, HiBound);
2599 }
2600 }
2601 }
2602 break;
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002603 case Instruction::Select:
2604 // If either operand of the select is a constant, we can fold the
2605 // comparison into the select arms, which will cause one to be
2606 // constant folded and the select turned into a bitwise or.
2607 Value *Op1 = 0, *Op2 = 0;
2608 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00002609 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002610 // Fold the known value into the constant operand.
2611 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2612 // Insert a new SetCC of the other select operand.
2613 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002614 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002615 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00002616 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00002617 // Fold the known value into the constant operand.
2618 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2619 // Insert a new SetCC of the other select operand.
2620 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00002621 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00002622 I.getName()), I);
2623 }
Chris Lattner2dd01742004-06-09 04:24:29 +00002624 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00002625
2626 if (Op1)
2627 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2628 break;
2629 }
2630
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002631 // Simplify seteq and setne instructions...
2632 if (I.getOpcode() == Instruction::SetEQ ||
2633 I.getOpcode() == Instruction::SetNE) {
2634 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2635
Chris Lattnercfbce7c2003-07-23 17:26:36 +00002636 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002637 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00002638 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2639 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00002640 case Instruction::Rem:
2641 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2642 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2643 BO->hasOneUse() &&
2644 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2645 if (unsigned L2 =
2646 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2647 const Type *UTy = BO->getType()->getUnsignedVersion();
2648 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2649 UTy, "tmp"), I);
2650 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2651 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2652 RHSCst, BO->getName()), I);
2653 return BinaryOperator::create(I.getOpcode(), NewRem,
2654 Constant::getNullValue(UTy));
2655 }
2656 break;
2657
Chris Lattnerc992add2003-08-13 05:33:12 +00002658 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00002659 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2660 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00002661 if (BO->hasOneUse())
2662 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2663 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00002664 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002665 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2666 // efficiently invertible, or if the add has just this one use.
2667 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00002668
Chris Lattnerc992add2003-08-13 05:33:12 +00002669 if (Value *NegVal = dyn_castNegVal(BOp1))
2670 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2671 else if (Value *NegVal = dyn_castNegVal(BOp0))
2672 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002673 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00002674 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2675 BO->setName("");
2676 InsertNewInstBefore(Neg, I);
2677 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2678 }
2679 }
2680 break;
2681 case Instruction::Xor:
2682 // For the xor case, we can xor two constants together, eliminating
2683 // the explicit xor.
2684 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2685 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002686 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00002687
2688 // FALLTHROUGH
2689 case Instruction::Sub:
2690 // Replace (([sub|xor] A, B) != 0) with (A != B)
2691 if (CI->isNullValue())
2692 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2693 BO->getOperand(1));
2694 break;
2695
2696 case Instruction::Or:
2697 // If bits are being or'd in that are not present in the constant we
2698 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002699 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002700 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002701 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002702 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002703 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002704 break;
2705
2706 case Instruction::And:
2707 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002708 // If bits are being compared against that are and'd out, then the
2709 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00002710 if (!ConstantExpr::getAnd(CI,
2711 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002712 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00002713
Chris Lattner35167c32004-06-09 07:59:58 +00002714 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00002715 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00002716 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2717 Instruction::SetNE, Op0,
2718 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00002719
Chris Lattnerc992add2003-08-13 05:33:12 +00002720 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2721 // to be a signed value as appropriate.
2722 if (isSignBit(BOC)) {
2723 Value *X = BO->getOperand(0);
2724 // If 'X' is not signed, insert a cast now...
2725 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00002726 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002727 X = InsertCastBefore(X, DestTy, I);
Chris Lattnerc992add2003-08-13 05:33:12 +00002728 }
2729 return new SetCondInst(isSetNE ? Instruction::SetLT :
2730 Instruction::SetGE, X,
2731 Constant::getNullValue(X->getType()));
2732 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00002733
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002734 // ((X & ~7) == 0) --> X < 8
Chris Lattner8fc5af42004-09-23 21:46:38 +00002735 if (CI->isNullValue() && isHighOnes(BOC)) {
2736 Value *X = BO->getOperand(0);
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002737 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002738
2739 // If 'X' is signed, insert a cast now.
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002740 if (NegX->getType()->isSigned()) {
2741 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2742 X = InsertCastBefore(X, DestTy, I);
2743 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002744 }
2745
2746 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattnerbfff18a2004-09-27 19:29:18 +00002747 Instruction::SetLT, X, NegX);
Chris Lattner8fc5af42004-09-23 21:46:38 +00002748 }
2749
Chris Lattnerd492a0b2003-07-23 17:02:11 +00002750 }
Chris Lattnerc992add2003-08-13 05:33:12 +00002751 default: break;
2752 }
2753 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00002754 } else { // Not a SetEQ/SetNE
2755 // If the LHS is a cast from an integral value of the same size,
2756 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2757 Value *CastOp = Cast->getOperand(0);
2758 const Type *SrcTy = CastOp->getType();
2759 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2760 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2761 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2762 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2763 "Source and destination signednesses should differ!");
2764 if (Cast->getType()->isSigned()) {
2765 // If this is a signed comparison, check for comparisons in the
2766 // vicinity of zero.
2767 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2768 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002769 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002770 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2771 else if (I.getOpcode() == Instruction::SetGT &&
2772 cast<ConstantSInt>(CI)->getValue() == -1)
2773 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002774 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00002775 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2776 } else {
2777 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2778 if (I.getOpcode() == Instruction::SetLT &&
2779 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2780 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002781 return BinaryOperator::createSetGT(CastOp,
2782 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002783 else if (I.getOpcode() == Instruction::SetGT &&
2784 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2785 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002786 return BinaryOperator::createSetLT(CastOp,
2787 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00002788 }
2789 }
2790 }
Chris Lattnere967b342003-06-04 05:10:11 +00002791 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002792 }
2793
Chris Lattner0798af32005-01-13 20:14:25 +00002794 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
2795 if (User *GEP = dyn_castGetElementPtr(Op0))
2796 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
2797 return NI;
2798 if (User *GEP = dyn_castGetElementPtr(Op1))
2799 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
2800 SetCondInst::getSwappedCondition(I.getOpcode()), I))
2801 return NI;
2802
Chris Lattner16930792003-11-03 04:25:02 +00002803 // Test to see if the operands of the setcc are casted versions of other
2804 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00002805 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2806 Value *CastOp0 = CI->getOperand(0);
2807 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00002808 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00002809 (I.getOpcode() == Instruction::SetEQ ||
2810 I.getOpcode() == Instruction::SetNE)) {
2811 // We keep moving the cast from the left operand over to the right
2812 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00002813 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00002814
2815 // If operand #1 is a cast instruction, see if we can eliminate it as
2816 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00002817 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2818 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00002819 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00002820 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00002821
2822 // If Op1 is a constant, we can fold the cast into the constant.
2823 if (Op1->getType() != Op0->getType())
2824 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2825 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2826 } else {
2827 // Otherwise, cast the RHS right before the setcc
2828 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2829 InsertNewInstBefore(cast<Instruction>(Op1), I);
2830 }
2831 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2832 }
2833
Chris Lattner6444c372003-11-03 05:17:03 +00002834 // Handle the special case of: setcc (cast bool to X), <cst>
2835 // This comes up when you have code like
2836 // int X = A < B;
2837 // if (X) ...
2838 // For generality, we handle any zero-extension of any operand comparison
2839 // with a constant.
2840 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2841 const Type *SrcTy = CastOp0->getType();
2842 const Type *DestTy = Op0->getType();
2843 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2844 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2845 // Ok, we have an expansion of operand 0 into a new type. Get the
2846 // constant value, masink off bits which are not set in the RHS. These
2847 // could be set if the destination value is signed.
2848 uint64_t ConstVal = ConstantRHS->getRawValue();
2849 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2850
2851 // If the constant we are comparing it with has high bits set, which
2852 // don't exist in the original value, the values could never be equal,
2853 // because the source would be zero extended.
2854 unsigned SrcBits =
2855 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00002856 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2857 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00002858 switch (I.getOpcode()) {
2859 default: assert(0 && "Unknown comparison type!");
2860 case Instruction::SetEQ:
2861 return ReplaceInstUsesWith(I, ConstantBool::False);
2862 case Instruction::SetNE:
2863 return ReplaceInstUsesWith(I, ConstantBool::True);
2864 case Instruction::SetLT:
2865 case Instruction::SetLE:
2866 if (DestTy->isSigned() && HasSignBit)
2867 return ReplaceInstUsesWith(I, ConstantBool::False);
2868 return ReplaceInstUsesWith(I, ConstantBool::True);
2869 case Instruction::SetGT:
2870 case Instruction::SetGE:
2871 if (DestTy->isSigned() && HasSignBit)
2872 return ReplaceInstUsesWith(I, ConstantBool::True);
2873 return ReplaceInstUsesWith(I, ConstantBool::False);
2874 }
2875 }
2876
2877 // Otherwise, we can replace the setcc with a setcc of the smaller
2878 // operand value.
2879 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2880 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2881 }
2882 }
2883 }
Chris Lattner113f4f42002-06-25 16:13:24 +00002884 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002885}
2886
Reid Spencer279fa252004-11-28 21:31:15 +00002887// visitSetCondInstWithCastAndConstant - this method is part of the
2888// visitSetCondInst method. It handles the situation where we have:
2889// (setcc (cast X to larger), CI)
2890// It tries to remove the cast and even the setcc if the CI value
2891// and range of the cast allow it.
2892Instruction *
2893InstCombiner::visitSetCondInstWithCastAndConstant(BinaryOperator&I,
2894 CastInst* LHSI,
2895 ConstantInt* CI) {
2896 const Type *SrcTy = LHSI->getOperand(0)->getType();
2897 const Type *DestTy = LHSI->getType();
2898 if (SrcTy->isIntegral() && DestTy->isIntegral()) {
2899 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2900 unsigned DestBits = DestTy->getPrimitiveSize()*8;
2901 if (SrcTy == Type::BoolTy)
2902 SrcBits = 1;
2903 if (DestTy == Type::BoolTy)
2904 DestBits = 1;
2905 if (SrcBits < DestBits) {
2906 // There are fewer bits in the source of the cast than in the result
2907 // of the cast. Any other case doesn't matter because the constant
2908 // value won't have changed due to sign extension.
2909 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2910 if (ConstantExpr::getCast(NewCst, DestTy) == CI) {
2911 // The constant value operand of the setCC before and after a
2912 // cast to the source type of the cast instruction is the same
2913 // value, so we just replace with the same setcc opcode, but
2914 // using the source value compared to the constant casted to the
2915 // source type.
2916 if (SrcTy->isSigned() && DestTy->isUnsigned()) {
2917 CastInst* Cst = new CastInst(LHSI->getOperand(0),
2918 SrcTy->getUnsignedVersion(), LHSI->getName());
2919 InsertNewInstBefore(Cst,I);
2920 return new SetCondInst(I.getOpcode(), Cst,
2921 ConstantExpr::getCast(CI, SrcTy->getUnsignedVersion()));
2922 }
2923 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),NewCst);
2924 }
2925 // The constant value before and after a cast to the source type
2926 // is different, so various cases are possible depending on the
2927 // opcode and the signs of the types involved in the cast.
2928 switch (I.getOpcode()) {
2929 case Instruction::SetLT: {
2930 Constant* Max = ConstantIntegral::getMaxValue(SrcTy);
2931 Max = ConstantExpr::getCast(Max, DestTy);
2932 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2933 }
2934 case Instruction::SetGT: {
2935 Constant* Min = ConstantIntegral::getMinValue(SrcTy);
2936 Min = ConstantExpr::getCast(Min, DestTy);
2937 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2938 }
2939 case Instruction::SetEQ:
2940 // We're looking for equality, and we know the values are not
2941 // equal so replace with constant False.
2942 return ReplaceInstUsesWith(I, ConstantBool::False);
2943 case Instruction::SetNE:
2944 // We're testing for inequality, and we know the values are not
2945 // equal so replace with constant True.
2946 return ReplaceInstUsesWith(I, ConstantBool::True);
2947 case Instruction::SetLE:
2948 case Instruction::SetGE:
2949 assert(!"SetLE and SetGE should be handled elsewhere");
2950 default:
2951 assert(!"unknown integer comparison");
2952 }
2953 }
2954 }
2955 return 0;
2956}
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002957
2958
Chris Lattnere8d6c602003-03-10 19:16:08 +00002959Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00002960 assert(I.getOperand(1)->getType() == Type::UByteTy);
2961 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002962 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002963
2964 // shl X, 0 == X and shr X, 0 == X
2965 // shl 0, X == 0 and shr 0, X == 0
2966 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00002967 Op0 == Constant::getNullValue(Op0->getType()))
2968 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002969
Chris Lattner81a7a232004-10-16 18:11:37 +00002970 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2971 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner67f05452004-10-16 23:28:04 +00002972 return ReplaceInstUsesWith(I, Op0);
Chris Lattner81a7a232004-10-16 18:11:37 +00002973 else // undef << X -> 0 AND undef >>u X -> 0
2974 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2975 }
2976 if (isa<UndefValue>(Op1)) {
2977 if (isLeftShift || I.getType()->isUnsigned())
2978 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2979 else
2980 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2981 }
2982
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002983 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2984 if (!isLeftShift)
2985 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2986 if (CSI->isAllOnesValue())
2987 return ReplaceInstUsesWith(I, CSI);
2988
Chris Lattner183b3362004-04-09 19:05:30 +00002989 // Try to fold constant and into select arguments.
2990 if (isa<Constant>(Op0))
2991 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner86102b82005-01-01 16:22:27 +00002992 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00002993 return R;
2994
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002995 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002996 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2997 // of a signed value.
2998 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00002999 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003000 if (CUI->getValue() >= TypeBits) {
3001 if (!Op0->getType()->isSigned() || isLeftShift)
3002 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3003 else {
3004 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3005 return &I;
3006 }
3007 }
Chris Lattner55f3d942002-09-10 23:04:09 +00003008
Chris Lattnerede3fe02003-08-13 04:18:28 +00003009 // ((X*C1) << C2) == (X * (C1 << C2))
3010 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3011 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3012 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003013 return BinaryOperator::createMul(BO->getOperand(0),
3014 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00003015
Chris Lattner183b3362004-04-09 19:05:30 +00003016 // Try to fold constant and into select arguments.
3017 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner86102b82005-01-01 16:22:27 +00003018 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner183b3362004-04-09 19:05:30 +00003019 return R;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003020 if (isa<PHINode>(Op0))
3021 if (Instruction *NV = FoldOpIntoPhi(I))
3022 return NV;
Chris Lattnerede3fe02003-08-13 04:18:28 +00003023
Chris Lattner86102b82005-01-01 16:22:27 +00003024 if (Op0->hasOneUse()) {
3025 // If this is a SHL of a sign-extending cast, see if we can turn the input
3026 // into a zero extending cast (a simple strength reduction).
3027 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3028 const Type *SrcTy = CI->getOperand(0)->getType();
3029 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3030 SrcTy->getPrimitiveSize() < CI->getType()->getPrimitiveSize()) {
3031 // We can change it to a zero extension if we are shifting out all of
3032 // the sign extended bits. To check this, form a mask of all of the
3033 // sign extend bits, then shift them left and see if we have anything
3034 // left.
3035 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3036 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3037 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3038 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3039 // If the shift is nuking all of the sign bits, change this to a
3040 // zero extension cast. To do this, cast the cast input to
3041 // unsigned, then to the requested size.
3042 Value *CastOp = CI->getOperand(0);
3043 Instruction *NC =
3044 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3045 CI->getName()+".uns");
3046 NC = InsertNewInstBefore(NC, I);
3047 // Finally, insert a replacement for CI.
3048 NC = new CastInst(NC, CI->getType(), CI->getName());
3049 CI->setName("");
3050 NC = InsertNewInstBefore(NC, I);
3051 WorkList.push_back(CI); // Delete CI later.
3052 I.setOperand(0, NC);
3053 return &I; // The SHL operand was modified.
3054 }
3055 }
3056 }
3057
3058 // If the operand is an bitwise operator with a constant RHS, and the
3059 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003060 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
3061 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3062 bool isValid = true; // Valid only for And, Or, Xor
3063 bool highBitSet = false; // Transform if high bit of constant set?
3064
3065 switch (Op0BO->getOpcode()) {
3066 default: isValid = false; break; // Do not perform transform!
Chris Lattner44bd3922004-10-08 03:46:20 +00003067 case Instruction::Add:
3068 isValid = isLeftShift;
3069 break;
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003070 case Instruction::Or:
3071 case Instruction::Xor:
3072 highBitSet = false;
3073 break;
3074 case Instruction::And:
3075 highBitSet = true;
3076 break;
3077 }
3078
3079 // If this is a signed shift right, and the high bit is modified
3080 // by the logical operation, do not perform the transformation.
3081 // The highBitSet boolean indicates the value of the high bit of
3082 // the constant which would cause it to be modified for this
3083 // operation.
3084 //
3085 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3086 uint64_t Val = Op0C->getRawValue();
3087 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3088 }
3089
3090 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00003091 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003092
3093 Instruction *NewShift =
3094 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3095 Op0BO->getName());
3096 Op0BO->setName("");
3097 InsertNewInstBefore(NewShift, I);
3098
3099 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3100 NewRHS);
3101 }
3102 }
Chris Lattner86102b82005-01-01 16:22:27 +00003103 }
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003104
Chris Lattner3204d4e2003-07-24 17:52:58 +00003105 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003106 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00003107 if (ConstantUInt *ShiftAmt1C =
3108 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003109 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3110 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Chris Lattner3204d4e2003-07-24 17:52:58 +00003111
3112 // Check for (A << c1) << c2 and (A >> c1) >> c2
3113 if (I.getOpcode() == Op0SI->getOpcode()) {
3114 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00003115 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
3116 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00003117 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3118 ConstantUInt::get(Type::UByteTy, Amt));
3119 }
3120
Chris Lattnerab780df2003-07-24 18:38:56 +00003121 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3122 // signed types, we can only support the (A >> c1) << c2 configuration,
3123 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003124 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00003125 // Calculate bitmask for what gets shifted off the edge...
3126 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003127 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003128 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00003129 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003130 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00003131
3132 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003133 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3134 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00003135 InsertNewInstBefore(Mask, I);
3136
3137 // Figure out what flavor of shift we should use...
3138 if (ShiftAmt1 == ShiftAmt2)
3139 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3140 else if (ShiftAmt1 < ShiftAmt2) {
3141 return new ShiftInst(I.getOpcode(), Mask,
3142 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3143 } else {
3144 return new ShiftInst(Op0SI->getOpcode(), Mask,
3145 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3146 }
3147 }
3148 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003149 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00003150
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003151 return 0;
3152}
3153
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003154enum CastType {
3155 Noop = 0,
3156 Truncate = 1,
3157 Signext = 2,
3158 Zeroext = 3
3159};
3160
3161/// getCastType - In the future, we will split the cast instruction into these
3162/// various types. Until then, we have to do the analysis here.
3163static CastType getCastType(const Type *Src, const Type *Dest) {
3164 assert(Src->isIntegral() && Dest->isIntegral() &&
3165 "Only works on integral types!");
3166 unsigned SrcSize = Src->getPrimitiveSize()*8;
3167 if (Src == Type::BoolTy) SrcSize = 1;
3168 unsigned DestSize = Dest->getPrimitiveSize()*8;
3169 if (Dest == Type::BoolTy) DestSize = 1;
3170
3171 if (SrcSize == DestSize) return Noop;
3172 if (SrcSize > DestSize) return Truncate;
3173 if (Src->isSigned()) return Signext;
3174 return Zeroext;
3175}
3176
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00003177
Chris Lattner48a44f72002-05-02 17:06:02 +00003178// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3179// instruction.
3180//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003181static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00003182 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003183
Chris Lattner650b6da2002-08-02 20:00:25 +00003184 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3185 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00003186 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00003187 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00003188 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00003189
Chris Lattner4fbad962004-07-21 04:27:24 +00003190 // If we are casting between pointer and integer types, treat pointers as
3191 // integers of the appropriate size for the code below.
3192 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3193 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3194 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00003195
Chris Lattner48a44f72002-05-02 17:06:02 +00003196 // Allow free casting and conversion of sizes as long as the sign doesn't
3197 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003198 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003199 CastType FirstCast = getCastType(SrcTy, MidTy);
3200 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00003201
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003202 // Capture the effect of these two casts. If the result is a legal cast,
3203 // the CastType is stored here, otherwise a special code is used.
3204 static const unsigned CastResult[] = {
3205 // First cast is noop
3206 0, 1, 2, 3,
3207 // First cast is a truncate
3208 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3209 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00003210 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003211 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00003212 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00003213 };
3214
3215 unsigned Result = CastResult[FirstCast*4+SecondCast];
3216 switch (Result) {
3217 default: assert(0 && "Illegal table value!");
3218 case 0:
3219 case 1:
3220 case 2:
3221 case 3:
3222 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3223 // truncates, we could eliminate more casts.
3224 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3225 case 4:
3226 return false; // Not possible to eliminate this here.
3227 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00003228 // Sign or zero extend followed by truncate is always ok if the result
3229 // is a truncate or noop.
3230 CastType ResultCast = getCastType(SrcTy, DstTy);
3231 if (ResultCast == Noop || ResultCast == Truncate)
3232 return true;
3233 // Otherwise we are still growing the value, we are only safe if the
3234 // result will match the sign/zeroextendness of the result.
3235 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00003236 }
Chris Lattner650b6da2002-08-02 20:00:25 +00003237 }
Chris Lattner48a44f72002-05-02 17:06:02 +00003238 return false;
3239}
3240
Chris Lattner11ffd592004-07-20 05:21:00 +00003241static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003242 if (V->getType() == Ty || isa<Constant>(V)) return false;
3243 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00003244 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3245 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003246 return false;
3247 return true;
3248}
3249
3250/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3251/// InsertBefore instruction. This is specialized a bit to avoid inserting
3252/// casts that are known to not do anything...
3253///
3254Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3255 Instruction *InsertBefore) {
3256 if (V->getType() == DestTy) return V;
3257 if (Constant *C = dyn_cast<Constant>(V))
3258 return ConstantExpr::getCast(C, DestTy);
3259
3260 CastInst *CI = new CastInst(V, DestTy, V->getName());
3261 InsertNewInstBefore(CI, *InsertBefore);
3262 return CI;
3263}
Chris Lattner48a44f72002-05-02 17:06:02 +00003264
3265// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00003266//
Chris Lattner113f4f42002-06-25 16:13:24 +00003267Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00003268 Value *Src = CI.getOperand(0);
3269
Chris Lattner48a44f72002-05-02 17:06:02 +00003270 // If the user is casting a value to the same type, eliminate this cast
3271 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00003272 if (CI.getType() == Src->getType())
3273 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00003274
Chris Lattner81a7a232004-10-16 18:11:37 +00003275 if (isa<UndefValue>(Src)) // cast undef -> undef
3276 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3277
Chris Lattner48a44f72002-05-02 17:06:02 +00003278 // If casting the result of another cast instruction, try to eliminate this
3279 // one!
3280 //
Chris Lattner86102b82005-01-01 16:22:27 +00003281 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3282 Value *A = CSrc->getOperand(0);
3283 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3284 CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00003285 // This instruction now refers directly to the cast's src operand. This
3286 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00003287 CI.setOperand(0, CSrc->getOperand(0));
3288 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00003289 }
3290
Chris Lattner650b6da2002-08-02 20:00:25 +00003291 // If this is an A->B->A cast, and we are dealing with integral types, try
3292 // to convert this into a logical 'and' instruction.
3293 //
Chris Lattner86102b82005-01-01 16:22:27 +00003294 if (A->getType()->isInteger() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00003295 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner86102b82005-01-01 16:22:27 +00003296 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
3297 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()&&
3298 A->getType()->getPrimitiveSize() == CI.getType()->getPrimitiveSize()) {
Chris Lattner650b6da2002-08-02 20:00:25 +00003299 assert(CSrc->getType() != Type::ULongTy &&
3300 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00003301 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner86102b82005-01-01 16:22:27 +00003302 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3303 AndValue);
3304 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3305 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3306 if (And->getType() != CI.getType()) {
3307 And->setName(CSrc->getName()+".mask");
3308 InsertNewInstBefore(And, CI);
3309 And = new CastInst(And, CI.getType());
3310 }
3311 return And;
Chris Lattner650b6da2002-08-02 20:00:25 +00003312 }
3313 }
Chris Lattner86102b82005-01-01 16:22:27 +00003314
Chris Lattner03841652004-05-25 04:29:21 +00003315 // If this is a cast to bool, turn it into the appropriate setne instruction.
3316 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003317 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00003318 Constant::getNullValue(CI.getOperand(0)->getType()));
3319
Chris Lattnerd0d51602003-06-21 23:12:02 +00003320 // If casting the result of a getelementptr instruction with no offset, turn
3321 // this into a cast of the original pointer!
3322 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00003323 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00003324 bool AllZeroOperands = true;
3325 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3326 if (!isa<Constant>(GEP->getOperand(i)) ||
3327 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3328 AllZeroOperands = false;
3329 break;
3330 }
3331 if (AllZeroOperands) {
3332 CI.setOperand(0, GEP->getOperand(0));
3333 return &CI;
3334 }
3335 }
3336
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003337 // If we are casting a malloc or alloca to a pointer to a type of the same
3338 // size, rewrite the allocation instruction to allocate the "right" type.
3339 //
3340 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00003341 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003342 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3343 // Get the type really allocated and the type casted to...
3344 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003345 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003346 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00003347 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3348 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00003349
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003350 // If the allocation is for an even multiple of the cast type size
3351 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
3352 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003353 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00003354 std::string Name = AI->getName(); AI->setName("");
3355 AllocationInst *New;
3356 if (isa<MallocInst>(AI))
3357 New = new MallocInst(CastElTy, Amt, Name);
3358 else
3359 New = new AllocaInst(CastElTy, Amt, Name);
3360 InsertNewInstBefore(New, *AI);
3361 return ReplaceInstUsesWith(CI, New);
3362 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003363 }
3364 }
3365
Chris Lattner86102b82005-01-01 16:22:27 +00003366 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3367 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3368 return NV;
Chris Lattner6a4adcd2004-09-29 05:07:12 +00003369 if (isa<PHINode>(Src))
3370 if (Instruction *NV = FoldOpIntoPhi(CI))
3371 return NV;
3372
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003373 // If the source value is an instruction with only this use, we can attempt to
3374 // propagate the cast into the instruction. Also, only handle integral types
3375 // for now.
3376 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00003377 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003378 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3379 const Type *DestTy = CI.getType();
3380 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
3381 unsigned DestBitSize = getTypeSizeInBits(DestTy);
3382
3383 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3384 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3385
3386 switch (SrcI->getOpcode()) {
3387 case Instruction::Add:
3388 case Instruction::Mul:
3389 case Instruction::And:
3390 case Instruction::Or:
3391 case Instruction::Xor:
3392 // If we are discarding information, or just changing the sign, rewrite.
3393 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3394 // Don't insert two casts if they cannot be eliminated. We allow two
3395 // casts to be inserted if the sizes are the same. This could only be
3396 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00003397 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3398 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00003399 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3400 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3401 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3402 ->getOpcode(), Op0c, Op1c);
3403 }
3404 }
3405 break;
3406 case Instruction::Shl:
3407 // Allow changing the sign of the source operand. Do not allow changing
3408 // the size of the shift, UNLESS the shift amount is a constant. We
3409 // mush not change variable sized shifts to a smaller size, because it
3410 // is undefined to shift more bits out than exist in the value.
3411 if (DestBitSize == SrcBitSize ||
3412 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3413 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3414 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3415 }
3416 break;
3417 }
3418 }
3419
Chris Lattner260ab202002-04-18 17:39:14 +00003420 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00003421}
3422
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003423/// GetSelectFoldableOperands - We want to turn code that looks like this:
3424/// %C = or %A, %B
3425/// %D = select %cond, %C, %A
3426/// into:
3427/// %C = select %cond, %B, 0
3428/// %D = or %A, %C
3429///
3430/// Assuming that the specified instruction is an operand to the select, return
3431/// a bitmask indicating which operands of this instruction are foldable if they
3432/// equal the other incoming value of the select.
3433///
3434static unsigned GetSelectFoldableOperands(Instruction *I) {
3435 switch (I->getOpcode()) {
3436 case Instruction::Add:
3437 case Instruction::Mul:
3438 case Instruction::And:
3439 case Instruction::Or:
3440 case Instruction::Xor:
3441 return 3; // Can fold through either operand.
3442 case Instruction::Sub: // Can only fold on the amount subtracted.
3443 case Instruction::Shl: // Can only fold on the shift amount.
3444 case Instruction::Shr:
3445 return 1;
3446 default:
3447 return 0; // Cannot fold
3448 }
3449}
3450
3451/// GetSelectFoldableConstant - For the same transformation as the previous
3452/// function, return the identity constant that goes into the select.
3453static Constant *GetSelectFoldableConstant(Instruction *I) {
3454 switch (I->getOpcode()) {
3455 default: assert(0 && "This cannot happen!"); abort();
3456 case Instruction::Add:
3457 case Instruction::Sub:
3458 case Instruction::Or:
3459 case Instruction::Xor:
3460 return Constant::getNullValue(I->getType());
3461 case Instruction::Shl:
3462 case Instruction::Shr:
3463 return Constant::getNullValue(Type::UByteTy);
3464 case Instruction::And:
3465 return ConstantInt::getAllOnesValue(I->getType());
3466 case Instruction::Mul:
3467 return ConstantInt::get(I->getType(), 1);
3468 }
3469}
3470
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003471Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00003472 Value *CondVal = SI.getCondition();
3473 Value *TrueVal = SI.getTrueValue();
3474 Value *FalseVal = SI.getFalseValue();
3475
3476 // select true, X, Y -> X
3477 // select false, X, Y -> Y
3478 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003479 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00003480 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003481 else {
3482 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00003483 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003484 }
Chris Lattner533bc492004-03-30 19:37:13 +00003485
3486 // select C, X, X -> X
3487 if (TrueVal == FalseVal)
3488 return ReplaceInstUsesWith(SI, TrueVal);
3489
Chris Lattner81a7a232004-10-16 18:11:37 +00003490 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3491 return ReplaceInstUsesWith(SI, FalseVal);
3492 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3493 return ReplaceInstUsesWith(SI, TrueVal);
3494 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3495 if (isa<Constant>(TrueVal))
3496 return ReplaceInstUsesWith(SI, TrueVal);
3497 else
3498 return ReplaceInstUsesWith(SI, FalseVal);
3499 }
3500
Chris Lattner1c631e82004-04-08 04:43:23 +00003501 if (SI.getType() == Type::BoolTy)
3502 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3503 if (C == ConstantBool::True) {
3504 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003505 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003506 } else {
3507 // Change: A = select B, false, C --> A = and !B, C
3508 Value *NotCond =
3509 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3510 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003511 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003512 }
3513 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3514 if (C == ConstantBool::False) {
3515 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003516 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003517 } else {
3518 // Change: A = select B, C, true --> A = or !B, C
3519 Value *NotCond =
3520 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3521 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00003522 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00003523 }
3524 }
3525
Chris Lattner183b3362004-04-09 19:05:30 +00003526 // Selecting between two integer constants?
3527 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3528 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3529 // select C, 1, 0 -> cast C to int
3530 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3531 return new CastInst(CondVal, SI.getType());
3532 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3533 // select C, 0, 1 -> cast !C to int
3534 Value *NotCond =
3535 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00003536 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00003537 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00003538 }
Chris Lattner35167c32004-06-09 07:59:58 +00003539
3540 // If one of the constants is zero (we know they can't both be) and we
3541 // have a setcc instruction with zero, and we have an 'and' with the
3542 // non-constant value, eliminate this whole mess. This corresponds to
3543 // cases like this: ((X & 27) ? 27 : 0)
3544 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3545 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3546 if ((IC->getOpcode() == Instruction::SetEQ ||
3547 IC->getOpcode() == Instruction::SetNE) &&
3548 isa<ConstantInt>(IC->getOperand(1)) &&
3549 cast<Constant>(IC->getOperand(1))->isNullValue())
3550 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3551 if (ICA->getOpcode() == Instruction::And &&
3552 isa<ConstantInt>(ICA->getOperand(1)) &&
3553 (ICA->getOperand(1) == TrueValC ||
3554 ICA->getOperand(1) == FalseValC) &&
3555 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3556 // Okay, now we know that everything is set up, we just don't
3557 // know whether we have a setne or seteq and whether the true or
3558 // false val is the zero.
3559 bool ShouldNotVal = !TrueValC->isNullValue();
3560 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3561 Value *V = ICA;
3562 if (ShouldNotVal)
3563 V = InsertNewInstBefore(BinaryOperator::create(
3564 Instruction::Xor, V, ICA->getOperand(1)), SI);
3565 return ReplaceInstUsesWith(SI, V);
3566 }
Chris Lattner533bc492004-03-30 19:37:13 +00003567 }
Chris Lattner623fba12004-04-10 22:21:27 +00003568
3569 // See if we are selecting two values based on a comparison of the two values.
3570 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3571 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3572 // Transform (X == Y) ? X : Y -> Y
3573 if (SCI->getOpcode() == Instruction::SetEQ)
3574 return ReplaceInstUsesWith(SI, FalseVal);
3575 // Transform (X != Y) ? X : Y -> X
3576 if (SCI->getOpcode() == Instruction::SetNE)
3577 return ReplaceInstUsesWith(SI, TrueVal);
3578 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3579
3580 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3581 // Transform (X == Y) ? Y : X -> X
3582 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00003583 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003584 // Transform (X != Y) ? Y : X -> Y
3585 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00003586 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00003587 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3588 }
3589 }
Chris Lattner1c631e82004-04-08 04:43:23 +00003590
Chris Lattnera04c9042005-01-13 22:52:24 +00003591 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is legal for
3592 // FP as well.
3593 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
3594 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
3595 if (TI->hasOneUse() && FI->hasOneUse()) {
3596 bool isInverse = false;
3597 Instruction *AddOp = 0, *SubOp = 0;
3598
3599 if (TI->getOpcode() == Instruction::Sub &&
3600 FI->getOpcode() == Instruction::Add) {
3601 AddOp = FI; SubOp = TI;
3602 } else if (FI->getOpcode() == Instruction::Sub &&
3603 TI->getOpcode() == Instruction::Add) {
3604 AddOp = TI; SubOp = FI;
3605 }
3606
3607 if (AddOp) {
3608 Value *OtherAddOp = 0;
3609 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
3610 OtherAddOp = AddOp->getOperand(1);
3611 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
3612 OtherAddOp = AddOp->getOperand(0);
3613 }
3614
3615 if (OtherAddOp) {
3616 // So at this point we know we have:
3617 // select C, (add X, Y), (sub X, ?)
3618 // We can do the transform profitably if either 'Y' = '?' or '?' is
3619 // a constant.
3620 if (SubOp->getOperand(1) == AddOp ||
3621 isa<Constant>(SubOp->getOperand(1))) {
3622 Value *NegVal;
3623 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
3624 NegVal = ConstantExpr::getNeg(C);
3625 } else {
3626 NegVal = InsertNewInstBefore(
3627 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
3628 }
3629
3630 Value *NewTrueOp = AddOp->getOperand(1);
3631 Value *NewFalseOp = NegVal;
3632 if (AddOp != TI)
3633 std::swap(NewTrueOp, NewFalseOp);
3634 Instruction *NewSel =
3635 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
3636
3637 NewSel = InsertNewInstBefore(NewSel, SI);
3638 return BinaryOperator::createAdd(AddOp->getOperand(0), NewSel);
3639 }
3640 }
3641 }
3642 }
3643
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003644 // See if we can fold the select into one of our operands.
3645 if (SI.getType()->isInteger()) {
3646 // See the comment above GetSelectFoldableOperands for a description of the
3647 // transformation we are doing here.
3648 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3649 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3650 !isa<Constant>(FalseVal))
3651 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3652 unsigned OpToFold = 0;
3653 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3654 OpToFold = 1;
3655 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3656 OpToFold = 2;
3657 }
3658
3659 if (OpToFold) {
3660 Constant *C = GetSelectFoldableConstant(TVI);
3661 std::string Name = TVI->getName(); TVI->setName("");
3662 Instruction *NewSel =
3663 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3664 Name);
3665 InsertNewInstBefore(NewSel, SI);
3666 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3667 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3668 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3669 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3670 else {
3671 assert(0 && "Unknown instruction!!");
3672 }
3673 }
3674 }
Chris Lattner6862fbd2004-09-29 17:40:11 +00003675
Chris Lattner56e4d3d2004-04-09 23:46:01 +00003676 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3677 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3678 !isa<Constant>(TrueVal))
3679 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3680 unsigned OpToFold = 0;
3681 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3682 OpToFold = 1;
3683 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3684 OpToFold = 2;
3685 }
3686
3687 if (OpToFold) {
3688 Constant *C = GetSelectFoldableConstant(FVI);
3689 std::string Name = FVI->getName(); FVI->setName("");
3690 Instruction *NewSel =
3691 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3692 Name);
3693 InsertNewInstBefore(NewSel, SI);
3694 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3695 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3696 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3697 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3698 else {
3699 assert(0 && "Unknown instruction!!");
3700 }
3701 }
3702 }
3703 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00003704 return 0;
3705}
3706
3707
Chris Lattner970c33a2003-06-19 17:00:31 +00003708// CallInst simplification
3709//
3710Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00003711 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3712 // visitCallSite.
Chris Lattner00648e12004-10-12 04:52:52 +00003713 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3714 bool Changed = false;
3715
3716 // memmove/cpy/set of zero bytes is a noop.
3717 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3718 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3719
3720 // FIXME: Increase alignment here.
3721
3722 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3723 if (CI->getRawValue() == 1) {
3724 // Replace the instruction with just byte operations. We would
3725 // transform other cases to loads/stores, but we don't know if
3726 // alignment is sufficient.
3727 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003728 }
3729
Chris Lattner00648e12004-10-12 04:52:52 +00003730 // If we have a memmove and the source operation is a constant global,
3731 // then the source and dest pointers can't alias, so we can change this
3732 // into a call to memcpy.
3733 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3734 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3735 if (GVSrc->isConstant()) {
3736 Module *M = CI.getParent()->getParent()->getParent();
3737 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3738 CI.getCalledFunction()->getFunctionType());
3739 CI.setOperand(0, MemCpy);
3740 Changed = true;
3741 }
3742
3743 if (Changed) return &CI;
Chris Lattner95307542004-11-18 21:41:39 +00003744 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3745 // If this stoppoint is at the same source location as the previous
3746 // stoppoint in the chain, it is not needed.
3747 if (DbgStopPointInst *PrevSPI =
3748 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3749 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3750 SPI->getColNo() == PrevSPI->getColNo()) {
3751 SPI->replaceAllUsesWith(PrevSPI);
3752 return EraseInstFromFunction(CI);
3753 }
Chris Lattner00648e12004-10-12 04:52:52 +00003754 }
3755
Chris Lattneraec3d942003-10-07 22:32:43 +00003756 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00003757}
3758
3759// InvokeInst simplification
3760//
3761Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00003762 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00003763}
3764
Chris Lattneraec3d942003-10-07 22:32:43 +00003765// visitCallSite - Improvements for call and invoke instructions.
3766//
3767Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003768 bool Changed = false;
3769
3770 // If the callee is a constexpr cast of a function, attempt to move the cast
3771 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00003772 if (transformConstExprCastCall(CS)) return 0;
3773
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003774 Value *Callee = CS.getCalledValue();
Chris Lattner81a7a232004-10-16 18:11:37 +00003775
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003776 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3777 // This instruction is not reachable, just remove it. We insert a store to
3778 // undef so that we know that this code is not reachable, despite the fact
3779 // that we can't modify the CFG here.
3780 new StoreInst(ConstantBool::True,
3781 UndefValue::get(PointerType::get(Type::BoolTy)),
3782 CS.getInstruction());
3783
3784 if (!CS.getInstruction()->use_empty())
3785 CS.getInstruction()->
3786 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3787
3788 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3789 // Don't break the CFG, insert a dummy cond branch.
3790 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3791 ConstantBool::True, II);
Chris Lattner81a7a232004-10-16 18:11:37 +00003792 }
Chris Lattner8ba9ec92004-10-18 02:59:09 +00003793 return EraseInstFromFunction(*CS.getInstruction());
3794 }
Chris Lattner81a7a232004-10-16 18:11:37 +00003795
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003796 const PointerType *PTy = cast<PointerType>(Callee->getType());
3797 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3798 if (FTy->isVarArg()) {
3799 // See if we can optimize any arguments passed through the varargs area of
3800 // the call.
3801 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3802 E = CS.arg_end(); I != E; ++I)
3803 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3804 // If this cast does not effect the value passed through the varargs
3805 // area, we can eliminate the use of the cast.
3806 Value *Op = CI->getOperand(0);
3807 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3808 *I = Op;
3809 Changed = true;
3810 }
3811 }
3812 }
Chris Lattneraec3d942003-10-07 22:32:43 +00003813
Chris Lattner75b4d1d2003-10-07 22:54:13 +00003814 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00003815}
3816
Chris Lattner970c33a2003-06-19 17:00:31 +00003817// transformConstExprCastCall - If the callee is a constexpr cast of a function,
3818// attempt to move the cast to the arguments of the call/invoke.
3819//
3820bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3821 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3822 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00003823 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00003824 return false;
Reid Spencer87436872004-07-18 00:38:32 +00003825 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00003826 Instruction *Caller = CS.getInstruction();
3827
3828 // Okay, this is a cast from a function to a different type. Unless doing so
3829 // would cause a type conversion of one of our arguments, change this call to
3830 // be a direct call with arguments casted to the appropriate types.
3831 //
3832 const FunctionType *FT = Callee->getFunctionType();
3833 const Type *OldRetTy = Caller->getType();
3834
Chris Lattner1f7942f2004-01-14 06:06:08 +00003835 // Check to see if we are changing the return type...
3836 if (OldRetTy != FT->getReturnType()) {
3837 if (Callee->isExternal() &&
3838 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3839 !Caller->use_empty())
3840 return false; // Cannot transform this return value...
3841
3842 // If the callsite is an invoke instruction, and the return value is used by
3843 // a PHI node in a successor, we cannot change the return type of the call
3844 // because there is no place to put the cast instruction (without breaking
3845 // the critical edge). Bail out in this case.
3846 if (!Caller->use_empty())
3847 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3848 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3849 UI != E; ++UI)
3850 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3851 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003852 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00003853 return false;
3854 }
Chris Lattner970c33a2003-06-19 17:00:31 +00003855
3856 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3857 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3858
3859 CallSite::arg_iterator AI = CS.arg_begin();
3860 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3861 const Type *ParamTy = FT->getParamType(i);
3862 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3863 if (Callee->isExternal() && !isConvertible) return false;
3864 }
3865
3866 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3867 Callee->isExternal())
3868 return false; // Do not delete arguments unless we have a function body...
3869
3870 // Okay, we decided that this is a safe thing to do: go ahead and start
3871 // inserting cast instructions as necessary...
3872 std::vector<Value*> Args;
3873 Args.reserve(NumActualArgs);
3874
3875 AI = CS.arg_begin();
3876 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3877 const Type *ParamTy = FT->getParamType(i);
3878 if ((*AI)->getType() == ParamTy) {
3879 Args.push_back(*AI);
3880 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00003881 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3882 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00003883 }
3884 }
3885
3886 // If the function takes more arguments than the call was taking, add them
3887 // now...
3888 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3889 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3890
3891 // If we are removing arguments to the function, emit an obnoxious warning...
3892 if (FT->getNumParams() < NumActualArgs)
3893 if (!FT->isVarArg()) {
3894 std::cerr << "WARNING: While resolving call to function '"
3895 << Callee->getName() << "' arguments were dropped!\n";
3896 } else {
3897 // Add all of the arguments in their promoted form to the arg list...
3898 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3899 const Type *PTy = getPromotedType((*AI)->getType());
3900 if (PTy != (*AI)->getType()) {
3901 // Must promote to pass through va_arg area!
3902 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3903 InsertNewInstBefore(Cast, *Caller);
3904 Args.push_back(Cast);
3905 } else {
3906 Args.push_back(*AI);
3907 }
3908 }
3909 }
3910
3911 if (FT->getReturnType() == Type::VoidTy)
3912 Caller->setName(""); // Void type should not have a name...
3913
3914 Instruction *NC;
3915 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00003916 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00003917 Args, Caller->getName(), Caller);
3918 } else {
3919 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3920 }
3921
3922 // Insert a cast of the return type as necessary...
3923 Value *NV = NC;
3924 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3925 if (NV->getType() != Type::VoidTy) {
3926 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00003927
3928 // If this is an invoke instruction, we should insert it after the first
3929 // non-phi, instruction in the normal successor block.
3930 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3931 BasicBlock::iterator I = II->getNormalDest()->begin();
3932 while (isa<PHINode>(I)) ++I;
3933 InsertNewInstBefore(NC, *I);
3934 } else {
3935 // Otherwise, it's a call, just insert cast right after the call instr
3936 InsertNewInstBefore(NC, *Caller);
3937 }
Chris Lattner51ea1272004-02-28 05:22:00 +00003938 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00003939 } else {
Chris Lattnere29d6342004-10-17 21:22:38 +00003940 NV = UndefValue::get(Caller->getType());
Chris Lattner970c33a2003-06-19 17:00:31 +00003941 }
3942 }
3943
3944 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3945 Caller->replaceAllUsesWith(NV);
3946 Caller->getParent()->getInstList().erase(Caller);
3947 removeFromWorkList(Caller);
3948 return true;
3949}
3950
3951
Chris Lattner7515cab2004-11-14 19:13:23 +00003952// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
3953// operator and they all are only used by the PHI, PHI together their
3954// inputs, and do the operation once, to the result of the PHI.
3955Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
3956 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
3957
3958 // Scan the instruction, looking for input operations that can be folded away.
3959 // If all input operands to the phi are the same instruction (e.g. a cast from
3960 // the same type or "+42") we can pull the operation through the PHI, reducing
3961 // code size and simplifying code.
3962 Constant *ConstantOp = 0;
3963 const Type *CastSrcTy = 0;
3964 if (isa<CastInst>(FirstInst)) {
3965 CastSrcTy = FirstInst->getOperand(0)->getType();
3966 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
3967 // Can fold binop or shift if the RHS is a constant.
3968 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
3969 if (ConstantOp == 0) return 0;
3970 } else {
3971 return 0; // Cannot fold this operation.
3972 }
3973
3974 // Check to see if all arguments are the same operation.
3975 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3976 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
3977 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
3978 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
3979 return 0;
3980 if (CastSrcTy) {
3981 if (I->getOperand(0)->getType() != CastSrcTy)
3982 return 0; // Cast operation must match.
3983 } else if (I->getOperand(1) != ConstantOp) {
3984 return 0;
3985 }
3986 }
3987
3988 // Okay, they are all the same operation. Create a new PHI node of the
3989 // correct type, and PHI together all of the LHS's of the instructions.
3990 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
3991 PN.getName()+".in");
3992 NewPN->op_reserve(PN.getNumOperands());
Chris Lattner46dd5a62004-11-14 19:29:34 +00003993
3994 Value *InVal = FirstInst->getOperand(0);
3995 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattner7515cab2004-11-14 19:13:23 +00003996
3997 // Add all operands to the new PHI.
Chris Lattner46dd5a62004-11-14 19:29:34 +00003998 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3999 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4000 if (NewInVal != InVal)
4001 InVal = 0;
4002 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4003 }
4004
4005 Value *PhiVal;
4006 if (InVal) {
4007 // The new PHI unions all of the same values together. This is really
4008 // common, so we handle it intelligently here for compile-time speed.
4009 PhiVal = InVal;
4010 delete NewPN;
4011 } else {
4012 InsertNewInstBefore(NewPN, PN);
4013 PhiVal = NewPN;
4014 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004015
4016 // Insert and return the new operation.
4017 if (isa<CastInst>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004018 return new CastInst(PhiVal, PN.getType());
Chris Lattner7515cab2004-11-14 19:13:23 +00004019 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner46dd5a62004-11-14 19:29:34 +00004020 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004021 else
4022 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattner46dd5a62004-11-14 19:29:34 +00004023 PhiVal, ConstantOp);
Chris Lattner7515cab2004-11-14 19:13:23 +00004024}
Chris Lattner48a44f72002-05-02 17:06:02 +00004025
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004026// PHINode simplification
4027//
Chris Lattner113f4f42002-06-25 16:13:24 +00004028Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattnere29d6342004-10-17 21:22:38 +00004029 if (Value *V = hasConstantValue(&PN)) {
4030 // If V is an instruction, we have to be certain that it dominates PN.
4031 // However, because we don't have dom info, we can't do a perfect job.
4032 if (Instruction *I = dyn_cast<Instruction>(V)) {
4033 // We know that the instruction dominates the PHI if there are no undef
4034 // values coming in.
Chris Lattner3b92f172004-10-18 01:48:31 +00004035 if (I->getParent() != &I->getParent()->getParent()->front() ||
4036 isa<InvokeInst>(I))
Chris Lattner107c15c2004-10-17 21:31:34 +00004037 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4038 if (isa<UndefValue>(PN.getIncomingValue(i))) {
4039 V = 0;
4040 break;
4041 }
Chris Lattnere29d6342004-10-17 21:22:38 +00004042 }
4043
4044 if (V)
4045 return ReplaceInstUsesWith(PN, V);
4046 }
Chris Lattner4db2d222004-02-16 05:07:08 +00004047
4048 // If the only user of this instruction is a cast instruction, and all of the
4049 // incoming values are constants, change this PHI to merge together the casted
4050 // constants.
4051 if (PN.hasOneUse())
4052 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4053 if (CI->getType() != PN.getType()) { // noop casts will be folded
4054 bool AllConstant = true;
4055 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4056 if (!isa<Constant>(PN.getIncomingValue(i))) {
4057 AllConstant = false;
4058 break;
4059 }
4060 if (AllConstant) {
4061 // Make a new PHI with all casted values.
4062 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4063 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4064 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4065 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4066 PN.getIncomingBlock(i));
4067 }
4068
4069 // Update the cast instruction.
4070 CI->setOperand(0, New);
4071 WorkList.push_back(CI); // revisit the cast instruction to fold.
4072 WorkList.push_back(New); // Make sure to revisit the new Phi
4073 return &PN; // PN is now dead!
4074 }
4075 }
Chris Lattner7515cab2004-11-14 19:13:23 +00004076
4077 // If all PHI operands are the same operation, pull them through the PHI,
4078 // reducing code size.
4079 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4080 PN.getIncomingValue(0)->hasOneUse())
4081 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4082 return Result;
4083
4084
Chris Lattner91daeb52003-12-19 05:58:40 +00004085 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00004086}
4087
Chris Lattner69193f92004-04-05 01:30:19 +00004088static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4089 Instruction *InsertPoint,
4090 InstCombiner *IC) {
4091 unsigned PS = IC->getTargetData().getPointerSize();
4092 const Type *VTy = V->getType();
Chris Lattner69193f92004-04-05 01:30:19 +00004093 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4094 // We must insert a cast to ensure we sign-extend.
4095 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4096 V->getName()), *InsertPoint);
4097 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4098 *InsertPoint);
4099}
4100
Chris Lattner48a44f72002-05-02 17:06:02 +00004101
Chris Lattner113f4f42002-06-25 16:13:24 +00004102Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004103 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00004104 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00004105 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004106 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00004107 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004108
Chris Lattner81a7a232004-10-16 18:11:37 +00004109 if (isa<UndefValue>(GEP.getOperand(0)))
4110 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4111
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004112 bool HasZeroPointerIndex = false;
4113 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4114 HasZeroPointerIndex = C->isNullValue();
4115
4116 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00004117 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00004118
Chris Lattner69193f92004-04-05 01:30:19 +00004119 // Eliminate unneeded casts for indices.
4120 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00004121 gep_type_iterator GTI = gep_type_begin(GEP);
4122 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4123 if (isa<SequentialType>(*GTI)) {
4124 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4125 Value *Src = CI->getOperand(0);
4126 const Type *SrcTy = Src->getType();
4127 const Type *DestTy = CI->getType();
4128 if (Src->getType()->isInteger()) {
4129 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
4130 // We can always eliminate a cast from ulong or long to the other.
4131 // We can always eliminate a cast from uint to int or the other on
4132 // 32-bit pointer platforms.
4133 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
4134 MadeChange = true;
4135 GEP.setOperand(i, Src);
4136 }
4137 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4138 SrcTy->getPrimitiveSize() == 4) {
4139 // We can always eliminate a cast from int to [u]long. We can
4140 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4141 // pointer target.
4142 if (SrcTy->isSigned() ||
4143 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
4144 MadeChange = true;
4145 GEP.setOperand(i, Src);
4146 }
Chris Lattner69193f92004-04-05 01:30:19 +00004147 }
4148 }
4149 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00004150 // If we are using a wider index than needed for this platform, shrink it
4151 // to what we need. If the incoming value needs a cast instruction,
4152 // insert it. This explicit cast can make subsequent optimizations more
4153 // obvious.
4154 Value *Op = GEP.getOperand(i);
4155 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004156 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00004157 GEP.setOperand(i, ConstantExpr::getCast(C,
4158 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00004159 MadeChange = true;
4160 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00004161 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4162 Op->getName()), GEP);
4163 GEP.setOperand(i, Op);
4164 MadeChange = true;
4165 }
Chris Lattner44d0b952004-07-20 01:48:15 +00004166
4167 // If this is a constant idx, make sure to canonicalize it to be a signed
4168 // operand, otherwise CSE and other optimizations are pessimized.
4169 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4170 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4171 CUI->getType()->getSignedVersion()));
4172 MadeChange = true;
4173 }
Chris Lattner69193f92004-04-05 01:30:19 +00004174 }
4175 if (MadeChange) return &GEP;
4176
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004177 // Combine Indices - If the source pointer to this getelementptr instruction
4178 // is a getelementptr instruction, combine the indices of the two
4179 // getelementptr instructions into a single instruction.
4180 //
Chris Lattner57c67b02004-03-25 22:59:29 +00004181 std::vector<Value*> SrcGEPOperands;
Chris Lattner0798af32005-01-13 20:14:25 +00004182 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner57c67b02004-03-25 22:59:29 +00004183 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner57c67b02004-03-25 22:59:29 +00004184
4185 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00004186 // Note that if our source is a gep chain itself that we wait for that
4187 // chain to be resolved before we perform this transformation. This
4188 // avoids us creating a TON of code in some cases.
4189 //
4190 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4191 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4192 return 0; // Wait until our source is folded to completion.
4193
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004194 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00004195
4196 // Find out whether the last index in the source GEP is a sequential idx.
4197 bool EndsWithSequential = false;
4198 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4199 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00004200 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00004201
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004202 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00004203 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00004204 // Replace: gep (gep %P, long B), long A, ...
4205 // With: T = long A+B; gep %P, T, ...
4206 //
Chris Lattner5f667a62004-05-07 22:09:22 +00004207 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00004208 if (SO1 == Constant::getNullValue(SO1->getType())) {
4209 Sum = GO1;
4210 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4211 Sum = SO1;
4212 } else {
4213 // If they aren't the same type, convert both to an integer of the
4214 // target's pointer size.
4215 if (SO1->getType() != GO1->getType()) {
4216 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4217 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4218 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4219 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4220 } else {
4221 unsigned PS = TD->getPointerSize();
Chris Lattner69193f92004-04-05 01:30:19 +00004222 if (SO1->getType()->getPrimitiveSize() == PS) {
4223 // Convert GO1 to SO1's type.
4224 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4225
4226 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4227 // Convert SO1 to GO1's type.
4228 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4229 } else {
4230 const Type *PT = TD->getIntPtrType();
4231 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4232 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4233 }
4234 }
4235 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004236 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4237 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4238 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00004239 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4240 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00004241 }
Chris Lattner69193f92004-04-05 01:30:19 +00004242 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004243
4244 // Recycle the GEP we already have if possible.
4245 if (SrcGEPOperands.size() == 2) {
4246 GEP.setOperand(0, SrcGEPOperands[0]);
4247 GEP.setOperand(1, Sum);
4248 return &GEP;
4249 } else {
4250 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4251 SrcGEPOperands.end()-1);
4252 Indices.push_back(Sum);
4253 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4254 }
Chris Lattner69193f92004-04-05 01:30:19 +00004255 } else if (isa<Constant>(*GEP.idx_begin()) &&
4256 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00004257 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004258 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00004259 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4260 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004261 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4262 }
4263
4264 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00004265 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004266
Chris Lattner5f667a62004-05-07 22:09:22 +00004267 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004268 // GEP of global variable. If all of the indices for this GEP are
4269 // constants, we can promote this to a constexpr instead of an instruction.
4270
4271 // Scan for nonconstants...
4272 std::vector<Constant*> Indices;
4273 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4274 for (; I != E && isa<Constant>(*I); ++I)
4275 Indices.push_back(cast<Constant>(*I));
4276
4277 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00004278 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00004279
4280 // Replace all uses of the GEP with the new constexpr...
4281 return ReplaceInstUsesWith(GEP, CE);
4282 }
Chris Lattner5f667a62004-05-07 22:09:22 +00004283 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004284 if (CE->getOpcode() == Instruction::Cast) {
4285 if (HasZeroPointerIndex) {
4286 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4287 // into : GEP [10 x ubyte]* X, long 0, ...
4288 //
4289 // This occurs when the program declares an array extern like "int X[];"
4290 //
4291 Constant *X = CE->getOperand(0);
4292 const PointerType *CPTy = cast<PointerType>(CE->getType());
4293 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
4294 if (const ArrayType *XATy =
4295 dyn_cast<ArrayType>(XTy->getElementType()))
4296 if (const ArrayType *CATy =
4297 dyn_cast<ArrayType>(CPTy->getElementType()))
4298 if (CATy->getElementType() == XATy->getElementType()) {
4299 // At this point, we know that the cast source type is a pointer
4300 // to an array of the same type as the destination pointer
4301 // array. Because the array type is never stepped over (there
4302 // is a leading zero) we can fold the cast into this GEP.
4303 GEP.setOperand(0, X);
4304 return &GEP;
4305 }
Chris Lattner0798af32005-01-13 20:14:25 +00004306 } else if (GEP.getNumOperands() == 2 &&
4307 isa<PointerType>(CE->getOperand(0)->getType())) {
Chris Lattner14f3cdc2004-11-27 17:55:46 +00004308 // Transform things like:
4309 // %t = getelementptr ubyte* cast ([2 x sbyte]* %str to ubyte*), uint %V
4310 // into: %t1 = getelementptr [2 x sbyte*]* %str, int 0, uint %V; cast
4311 Constant *X = CE->getOperand(0);
4312 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
4313 const Type *ResElTy =cast<PointerType>(CE->getType())->getElementType();
4314 if (isa<ArrayType>(SrcElTy) &&
4315 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
4316 TD->getTypeSize(ResElTy)) {
4317 Value *V = InsertNewInstBefore(
4318 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
4319 GEP.getOperand(1), GEP.getName()), GEP);
4320 return new CastInst(V, GEP.getType());
4321 }
Chris Lattner8d0bacb2004-02-22 05:25:17 +00004322 }
4323 }
Chris Lattnerca081252001-12-14 16:52:21 +00004324 }
4325
Chris Lattnerca081252001-12-14 16:52:21 +00004326 return 0;
4327}
4328
Chris Lattner1085bdf2002-11-04 16:18:53 +00004329Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
4330 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
4331 if (AI.isArrayAllocation()) // Check C != 1
4332 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
4333 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004334 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00004335
4336 // Create and insert the replacement instruction...
4337 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00004338 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004339 else {
4340 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00004341 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00004342 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004343
4344 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00004345
4346 // Scan to the end of the allocation instructions, to skip over a block of
4347 // allocas if possible...
4348 //
4349 BasicBlock::iterator It = New;
4350 while (isa<AllocationInst>(*It)) ++It;
4351
4352 // Now that I is pointing to the first non-allocation-inst in the block,
4353 // insert our getelementptr instruction...
4354 //
Chris Lattner69193f92004-04-05 01:30:19 +00004355 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004356 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
4357
4358 // Now make everything use the getelementptr instead of the original
4359 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00004360 return ReplaceInstUsesWith(AI, V);
Chris Lattner81a7a232004-10-16 18:11:37 +00004361 } else if (isa<UndefValue>(AI.getArraySize())) {
4362 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner1085bdf2002-11-04 16:18:53 +00004363 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00004364
4365 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
4366 // Note that we only do this for alloca's, because malloc should allocate and
4367 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00004368 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
4369 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00004370 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
4371
Chris Lattner1085bdf2002-11-04 16:18:53 +00004372 return 0;
4373}
4374
Chris Lattner8427bff2003-12-07 01:24:23 +00004375Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
4376 Value *Op = FI.getOperand(0);
4377
4378 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
4379 if (CastInst *CI = dyn_cast<CastInst>(Op))
4380 if (isa<PointerType>(CI->getOperand(0)->getType())) {
4381 FI.setOperand(0, CI->getOperand(0));
4382 return &FI;
4383 }
4384
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004385 // free undef -> unreachable.
4386 if (isa<UndefValue>(Op)) {
4387 // Insert a new store to null because we cannot modify the CFG here.
4388 new StoreInst(ConstantBool::True,
4389 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
4390 return EraseInstFromFunction(FI);
4391 }
4392
Chris Lattnerf3a36602004-02-28 04:57:37 +00004393 // If we have 'free null' delete the instruction. This can happen in stl code
4394 // when lots of inlining happens.
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004395 if (isa<ConstantPointerNull>(Op))
Chris Lattner51ea1272004-02-28 05:22:00 +00004396 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00004397
Chris Lattner8427bff2003-12-07 01:24:23 +00004398 return 0;
4399}
4400
4401
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004402/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
4403/// constantexpr, return the constant value being addressed by the constant
4404/// expression, or null if something is funny.
4405///
4406static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00004407 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004408 return 0; // Do not allow stepping over the value!
4409
4410 // Loop over all of the operands, tracking down which value we are
4411 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00004412 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
4413 for (++I; I != E; ++I)
4414 if (const StructType *STy = dyn_cast<StructType>(*I)) {
4415 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
4416 assert(CU->getValue() < STy->getNumElements() &&
4417 "Struct index out of range!");
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004418 unsigned El = (unsigned)CU->getValue();
Chris Lattnered79d8a2004-05-27 17:30:27 +00004419 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004420 C = CS->getOperand(El);
Chris Lattnered79d8a2004-05-27 17:30:27 +00004421 } else if (isa<ConstantAggregateZero>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004422 C = Constant::getNullValue(STy->getElementType(El));
Chris Lattner81a7a232004-10-16 18:11:37 +00004423 } else if (isa<UndefValue>(C)) {
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004424 C = UndefValue::get(STy->getElementType(El));
Chris Lattnered79d8a2004-05-27 17:30:27 +00004425 } else {
4426 return 0;
4427 }
4428 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
4429 const ArrayType *ATy = cast<ArrayType>(*I);
4430 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
4431 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Chris Lattnerfdfe3e492005-01-08 19:42:22 +00004432 C = CA->getOperand((unsigned)CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004433 else if (isa<ConstantAggregateZero>(C))
4434 C = Constant::getNullValue(ATy->getElementType());
Chris Lattner81a7a232004-10-16 18:11:37 +00004435 else if (isa<UndefValue>(C))
4436 C = UndefValue::get(ATy->getElementType());
Chris Lattnered79d8a2004-05-27 17:30:27 +00004437 else
4438 return 0;
4439 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004440 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00004441 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004442 return C;
4443}
4444
Chris Lattner35e24772004-07-13 01:49:43 +00004445static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
4446 User *CI = cast<User>(LI.getOperand(0));
4447
4448 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
4449 if (const PointerType *SrcTy =
4450 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
4451 const Type *SrcPTy = SrcTy->getElementType();
4452 if (SrcPTy->isSized() && DestPTy->isSized() &&
4453 IC.getTargetData().getTypeSize(SrcPTy) ==
4454 IC.getTargetData().getTypeSize(DestPTy) &&
4455 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
4456 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
4457 // Okay, we are casting from one integer or pointer type to another of
4458 // the same size. Instead of casting the pointer before the load, cast
4459 // the result of the loaded value.
4460 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004461 CI->getName(),
4462 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00004463 // Now cast the result of the load.
4464 return new CastInst(NewLoad, LI.getType());
4465 }
4466 }
4467 return 0;
4468}
4469
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004470/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00004471/// from this value cannot trap. If it is not obviously safe to load from the
4472/// specified pointer, we do a quick local scan of the basic block containing
4473/// ScanFrom, to determine if the address is already accessed.
4474static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
4475 // If it is an alloca or global variable, it is always safe to load from.
4476 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
4477
4478 // Otherwise, be a little bit agressive by scanning the local block where we
4479 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004480 // from/to. If so, the previous load or store would have already trapped,
4481 // so there is no harm doing an extra load (also, CSE will later eliminate
4482 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00004483 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
4484
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004485 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00004486 --BBI;
4487
4488 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
4489 if (LI->getOperand(0) == V) return true;
4490 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
4491 if (SI->getOperand(1) == V) return true;
4492
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00004493 }
Chris Lattnere6f13092004-09-19 19:18:10 +00004494 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004495}
4496
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004497Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
4498 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00004499
Chris Lattner81a7a232004-10-16 18:11:37 +00004500 if (Constant *C = dyn_cast<Constant>(Op)) {
4501 if ((C->isNullValue() || isa<UndefValue>(C)) &&
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004502 !LI.isVolatile()) { // load null/undef -> undef
4503 // Insert a new store to null instruction before the load to indicate that
4504 // this code is not reachable. We do this instead of inserting an
4505 // unreachable instruction directly because we cannot modify the CFG.
4506 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
Chris Lattner81a7a232004-10-16 18:11:37 +00004507 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8ba9ec92004-10-18 02:59:09 +00004508 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004509
Chris Lattner81a7a232004-10-16 18:11:37 +00004510 // Instcombine load (constant global) into the value loaded.
4511 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
4512 if (GV->isConstant() && !GV->isExternal())
4513 return ReplaceInstUsesWith(LI, GV->getInitializer());
4514
4515 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
4516 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
4517 if (CE->getOpcode() == Instruction::GetElementPtr) {
4518 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
4519 if (GV->isConstant() && !GV->isExternal())
4520 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
4521 return ReplaceInstUsesWith(LI, V);
4522 } else if (CE->getOpcode() == Instruction::Cast) {
4523 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4524 return Res;
4525 }
4526 }
Chris Lattnere228ee52004-04-08 20:39:49 +00004527
4528 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00004529 if (CastInst *CI = dyn_cast<CastInst>(Op))
4530 if (Instruction *Res = InstCombineLoadCast(*this, LI))
4531 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00004532
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004533 if (!LI.isVolatile() && Op->hasOneUse()) {
4534 // Change select and PHI nodes to select values instead of addresses: this
4535 // helps alias analysis out a lot, allows many others simplifications, and
4536 // exposes redundancy in the code.
4537 //
4538 // Note that we cannot do the transformation unless we know that the
4539 // introduced loads cannot trap! Something like this is valid as long as
4540 // the condition is always false: load (select bool %C, int* null, int* %G),
4541 // but it would not be valid if we transformed it to load from null
4542 // unconditionally.
4543 //
4544 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4545 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00004546 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4547 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004548 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00004549 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004550 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00004551 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004552 return new SelectInst(SI->getCondition(), V1, V2);
4553 }
4554
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00004555 // load (select (cond, null, P)) -> load P
4556 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4557 if (C->isNullValue()) {
4558 LI.setOperand(0, SI->getOperand(2));
4559 return &LI;
4560 }
4561
4562 // load (select (cond, P, null)) -> load P
4563 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4564 if (C->isNullValue()) {
4565 LI.setOperand(0, SI->getOperand(1));
4566 return &LI;
4567 }
4568
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004569 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4570 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00004571 bool Safe = PN->getParent() == LI.getParent();
4572
4573 // Scan all of the instructions between the PHI and the load to make
4574 // sure there are no instructions that might possibly alter the value
4575 // loaded from the PHI.
4576 if (Safe) {
4577 BasicBlock::iterator I = &LI;
4578 for (--I; !isa<PHINode>(I); --I)
4579 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4580 Safe = false;
4581 break;
4582 }
4583 }
4584
4585 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00004586 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00004587 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004588 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00004589
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00004590 if (Safe) {
4591 // Create the PHI.
4592 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4593 InsertNewInstBefore(NewPN, *PN);
4594 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4595
4596 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4597 BasicBlock *BB = PN->getIncomingBlock(i);
4598 Value *&TheLoad = LoadMap[BB];
4599 if (TheLoad == 0) {
4600 Value *InVal = PN->getIncomingValue(i);
4601 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4602 InVal->getName()+".val"),
4603 *BB->getTerminator());
4604 }
4605 NewPN->addIncoming(TheLoad, BB);
4606 }
4607 return ReplaceInstUsesWith(LI, NewPN);
4608 }
4609 }
4610 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00004611 return 0;
4612}
4613
Chris Lattner9eef8a72003-06-04 04:46:00 +00004614Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4615 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00004616 Value *X;
4617 BasicBlock *TrueDest;
4618 BasicBlock *FalseDest;
4619 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4620 !isa<Constant>(X)) {
4621 // Swap Destinations and condition...
4622 BI.setCondition(X);
4623 BI.setSuccessor(0, FalseDest);
4624 BI.setSuccessor(1, TrueDest);
4625 return &BI;
4626 }
4627
4628 // Cannonicalize setne -> seteq
4629 Instruction::BinaryOps Op; Value *Y;
4630 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4631 TrueDest, FalseDest)))
4632 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4633 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4634 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4635 std::string Name = I->getName(); I->setName("");
4636 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4637 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00004638 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00004639 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00004640 BI.setSuccessor(0, FalseDest);
4641 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00004642 removeFromWorkList(I);
4643 I->getParent()->getInstList().erase(I);
4644 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00004645 return &BI;
4646 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00004647
Chris Lattner9eef8a72003-06-04 04:46:00 +00004648 return 0;
4649}
Chris Lattner1085bdf2002-11-04 16:18:53 +00004650
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004651Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4652 Value *Cond = SI.getCondition();
4653 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4654 if (I->getOpcode() == Instruction::Add)
4655 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4656 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4657 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattner81a7a232004-10-16 18:11:37 +00004658 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner4c9c20a2004-07-03 00:26:11 +00004659 AddRHS));
4660 SI.setOperand(0, I->getOperand(0));
4661 WorkList.push_back(I);
4662 return &SI;
4663 }
4664 }
4665 return 0;
4666}
4667
Chris Lattnerca081252001-12-14 16:52:21 +00004668
Chris Lattner99f48c62002-09-02 04:59:56 +00004669void InstCombiner::removeFromWorkList(Instruction *I) {
4670 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4671 WorkList.end());
4672}
4673
Chris Lattner39c98bb2004-12-08 23:43:58 +00004674
4675/// TryToSinkInstruction - Try to move the specified instruction from its
4676/// current block into the beginning of DestBlock, which can only happen if it's
4677/// safe to move the instruction past all of the instructions between it and the
4678/// end of its block.
4679static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
4680 assert(I->hasOneUse() && "Invariants didn't hold!");
4681
4682 // Cannot move control-flow-involving instructions.
4683 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
4684
4685 // Do not sink alloca instructions out of the entry block.
4686 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
4687 return false;
4688
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004689 // We can only sink load instructions if there is nothing between the load and
4690 // the end of block that could change the value.
4691 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4692 if (LI->isVolatile()) return false; // Don't sink volatile loads.
4693
4694 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
4695 Scan != E; ++Scan)
4696 if (Scan->mayWriteToMemory())
4697 return false;
Chris Lattnerf17a2fb2004-12-09 07:14:34 +00004698 }
Chris Lattner39c98bb2004-12-08 23:43:58 +00004699
4700 BasicBlock::iterator InsertPos = DestBlock->begin();
4701 while (isa<PHINode>(InsertPos)) ++InsertPos;
4702
4703 BasicBlock *SrcBlock = I->getParent();
4704 DestBlock->getInstList().splice(InsertPos, SrcBlock->getInstList(), I);
4705 ++NumSunkInst;
4706 return true;
4707}
4708
Chris Lattner113f4f42002-06-25 16:13:24 +00004709bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00004710 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00004711 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00004712
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004713 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4714 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00004715
Chris Lattnerca081252001-12-14 16:52:21 +00004716
4717 while (!WorkList.empty()) {
4718 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4719 WorkList.pop_back();
4720
Misha Brukman632df282002-10-29 23:06:16 +00004721 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00004722 // Check to see if we can DIE the instruction...
4723 if (isInstructionTriviallyDead(I)) {
4724 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004725 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00004726 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00004727 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004728
4729 I->getParent()->getInstList().erase(I);
4730 removeFromWorkList(I);
4731 continue;
4732 }
Chris Lattner99f48c62002-09-02 04:59:56 +00004733
Misha Brukman632df282002-10-29 23:06:16 +00004734 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00004735 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004736 Value* Ptr = I->getOperand(0);
Chris Lattner6580e092004-10-16 19:44:59 +00004737 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004738 cast<Constant>(Ptr)->isNullValue() &&
4739 !isa<ConstantPointerNull>(C) &&
4740 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner6580e092004-10-16 19:44:59 +00004741 // If this is a constant expr gep that is effectively computing an
4742 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4743 bool isFoldableGEP = true;
4744 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4745 if (!isa<ConstantInt>(I->getOperand(i)))
4746 isFoldableGEP = false;
4747 if (isFoldableGEP) {
Alkis Evlogimenosa1291a02004-12-08 23:10:30 +00004748 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner6580e092004-10-16 19:44:59 +00004749 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4750 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner684c5c62004-10-16 19:46:33 +00004751 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner6580e092004-10-16 19:44:59 +00004752 C = ConstantExpr::getCast(C, I->getType());
4753 }
4754 }
4755
Chris Lattner99f48c62002-09-02 04:59:56 +00004756 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00004757 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00004758 ReplaceInstUsesWith(*I, C);
4759
Chris Lattner99f48c62002-09-02 04:59:56 +00004760 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004761 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00004762 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004763 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00004764 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004765
Chris Lattner39c98bb2004-12-08 23:43:58 +00004766 // See if we can trivially sink this instruction to a successor basic block.
4767 if (I->hasOneUse()) {
4768 BasicBlock *BB = I->getParent();
4769 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
4770 if (UserParent != BB) {
4771 bool UserIsSuccessor = false;
4772 // See if the user is one of our successors.
4773 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
4774 if (*SI == UserParent) {
4775 UserIsSuccessor = true;
4776 break;
4777 }
4778
4779 // If the user is one of our immediate successors, and if that successor
4780 // only has us as a predecessors (we'd have to split the critical edge
4781 // otherwise), we can keep going.
4782 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
4783 next(pred_begin(UserParent)) == pred_end(UserParent))
4784 // Okay, the CFG is simple enough, try to sink this instruction.
4785 Changed |= TryToSinkInstruction(I, UserParent);
4786 }
4787 }
4788
Chris Lattnerca081252001-12-14 16:52:21 +00004789 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004790 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00004791 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00004792 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00004793 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004794 DEBUG(std::cerr << "IC: Old = " << *I
4795 << " New = " << *Result);
4796
Chris Lattner396dbfe2004-06-09 05:08:07 +00004797 // Everything uses the new instruction now.
4798 I->replaceAllUsesWith(Result);
4799
4800 // Push the new instruction and any users onto the worklist.
4801 WorkList.push_back(Result);
4802 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004803
4804 // Move the name to the new instruction first...
4805 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00004806 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004807
4808 // Insert the new instruction into the basic block...
4809 BasicBlock *InstParent = I->getParent();
Chris Lattner7515cab2004-11-14 19:13:23 +00004810 BasicBlock::iterator InsertPos = I;
4811
4812 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4813 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4814 ++InsertPos;
4815
4816 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004817
Chris Lattner63d75af2004-05-01 23:27:23 +00004818 // Make sure that we reprocess all operands now that we reduced their
4819 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00004820 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4821 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4822 WorkList.push_back(OpI);
4823
Chris Lattner396dbfe2004-06-09 05:08:07 +00004824 // Instructions can end up on the worklist more than once. Make sure
4825 // we do not process an instruction that has been deleted.
4826 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00004827
4828 // Erase the old instruction.
4829 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00004830 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00004831 DEBUG(std::cerr << "IC: MOD = " << *I);
4832
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004833 // If the instruction was modified, it's possible that it is now dead.
4834 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00004835 if (isInstructionTriviallyDead(I)) {
4836 // Make sure we process all operands now that we are reducing their
4837 // use counts.
4838 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4839 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4840 WorkList.push_back(OpI);
4841
4842 // Instructions may end up in the worklist more than once. Erase all
4843 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00004844 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00004845 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00004846 } else {
4847 WorkList.push_back(Result);
4848 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00004849 }
Chris Lattner053c0932002-05-14 15:24:07 +00004850 }
Chris Lattner260ab202002-04-18 17:39:14 +00004851 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00004852 }
4853 }
4854
Chris Lattner260ab202002-04-18 17:39:14 +00004855 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00004856}
4857
Brian Gaeke38b79e82004-07-27 17:43:21 +00004858FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00004859 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00004860}
Brian Gaeke960707c2003-11-11 22:41:34 +00004861