blob: cdfdc34555b6aab1d15883f868366c0889385dbd [file] [log] [blame]
Chris Lattnere6794492002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
John Criswell482202a2003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnerca081252001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner99f48c62002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattnerca081252001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattnerca081252001-12-14 16:52:21 +000017// into:
Chris Lattnerdd1a86d2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattnerca081252001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner216c7b82003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattnerbfb1d032003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnerede3fe02003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbfb1d032003-07-23 21:41:57 +000032// N. This list is incomplete
33//
Chris Lattnerca081252001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner7d2a5392004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattnerb4cfa7f2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner471bd762003-05-22 19:07:21 +000038#include "llvm/Instructions.h"
Chris Lattner51ea1272004-02-28 05:22:00 +000039#include "llvm/Intrinsics.h"
Chris Lattner04805fa2002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner34428442003-05-27 16:40:51 +000041#include "llvm/Constants.h"
Chris Lattner1085bdf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner0f1d8a32003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Chris Lattnerf4ad1652003-11-02 05:57:39 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
Chris Lattner69193f92004-04-05 01:30:19 +000047#include "llvm/Support/CallSite.h"
48#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner60a65912002-02-12 21:07:25 +000049#include "llvm/Support/InstIterator.h"
Chris Lattner260ab202002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerd4252a72004-07-30 07:50:03 +000051#include "llvm/Support/PatternMatch.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000052#include "llvm/Support/Debug.h"
53#include "llvm/ADT/Statistic.h"
Chris Lattner053c0932002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner8427bff2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattnerd4252a72004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeke960707c2003-11-11 22:41:34 +000057
Chris Lattner260ab202002-04-18 17:39:14 +000058namespace {
Chris Lattnerbf3a0992002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
62
Chris Lattnerc8e66542002-04-27 06:56:12 +000063 class InstCombiner : public FunctionPass,
Chris Lattner260ab202002-04-18 17:39:14 +000064 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
Chris Lattnerf4ad1652003-11-02 05:57:39 +000067 TargetData *TD;
Chris Lattner260ab202002-04-18 17:39:14 +000068
Chris Lattner51ea1272004-02-28 05:22:00 +000069 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
71 /// now.
72 ///
73 void AddUsersToWorkList(Instruction &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +000074 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattner260ab202002-04-18 17:39:14 +000075 UI != UE; ++UI)
76 WorkList.push_back(cast<Instruction>(*UI));
77 }
78
Chris Lattner51ea1272004-02-28 05:22:00 +000079 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
81 ///
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
86 }
87
Chris Lattner99f48c62002-09-02 04:59:56 +000088 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
Chris Lattner260ab202002-04-18 17:39:14 +000090 public:
Chris Lattner113f4f42002-06-25 16:13:24 +000091 virtual bool runOnFunction(Function &F);
Chris Lattner260ab202002-04-18 17:39:14 +000092
Chris Lattnerf12cc842002-04-28 21:27:06 +000093 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerf4ad1652003-11-02 05:57:39 +000094 AU.addRequired<TargetData>();
Chris Lattner820d9712002-10-21 20:00:28 +000095 AU.setPreservesCFG();
Chris Lattnerf12cc842002-04-28 21:27:06 +000096 }
97
Chris Lattner69193f92004-04-05 01:30:19 +000098 TargetData &getTargetData() const { return *TD; }
99
Chris Lattner260ab202002-04-18 17:39:14 +0000100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
102 // Return Value:
103 // null - No change was made
Chris Lattnere6794492002-08-12 21:17:25 +0000104 // I - Change was made, I is still valid, I may be dead though
Chris Lattner260ab202002-04-18 17:39:14 +0000105 // otherwise - Change was made, replace I with returned instruction
106 //
Chris Lattner113f4f42002-06-25 16:13:24 +0000107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
Chris Lattnere8d6c602003-03-10 19:16:08 +0000116 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000117 Instruction *visitCastInst(CastInst &CI);
Chris Lattnerb909e8b2004-03-12 05:52:32 +0000118 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner970c33a2003-06-19 17:00:31 +0000119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner113f4f42002-06-25 16:13:24 +0000121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner1085bdf2002-11-04 16:18:53 +0000123 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner8427bff2003-12-07 01:24:23 +0000124 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner0f1d8a32003-06-26 05:06:25 +0000125 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner9eef8a72003-06-04 04:46:00 +0000126 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner4c9c20a2004-07-03 00:26:11 +0000127 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattner260ab202002-04-18 17:39:14 +0000128
129 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner113f4f42002-06-25 16:13:24 +0000130 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000131
Chris Lattner970c33a2003-06-19 17:00:31 +0000132 private:
Chris Lattneraec3d942003-10-07 22:32:43 +0000133 Instruction *visitCallSite(CallSite CS);
Chris Lattner970c33a2003-06-19 17:00:31 +0000134 bool transformConstExprCastCall(CallSite CS);
135
Chris Lattner69193f92004-04-05 01:30:19 +0000136 public:
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
139 //
Chris Lattnere79e8542004-02-23 06:38:22 +0000140 Value *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattner65217ff2002-08-23 18:32:43 +0000141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
Chris Lattnere79e8542004-02-23 06:38:22 +0000146 return New;
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000147 }
148
Chris Lattner7e794272004-09-24 15:21:34 +0000149 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150 /// This also adds the cast to the worklist. Finally, this returns the
151 /// cast.
152 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153 if (V->getType() == Ty) return V;
154
155 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156 WorkList.push_back(C);
157 return C;
158 }
159
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000160 // ReplaceInstUsesWith - This method is to be used when an instruction is
161 // found to be dead, replacable with another preexisting expression. Here
162 // we add all uses of I to the worklist, replace all uses of I with the new
163 // value, then return I, so that the inst combiner will know that I was
164 // modified.
165 //
166 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner51ea1272004-02-28 05:22:00 +0000167 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner8953b902004-04-05 02:10:19 +0000168 if (&I != V) {
169 I.replaceAllUsesWith(V);
170 return &I;
171 } else {
172 // If we are replacing the instruction with itself, this must be in a
173 // segment of unreachable code, so just clobber the instruction.
174 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
175 return &I;
176 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000177 }
Chris Lattner51ea1272004-02-28 05:22:00 +0000178
179 // EraseInstFromFunction - When dealing with an instruction that has side
180 // effects or produces a void value, we can't rely on DCE to delete the
181 // instruction. Instead, visit methods should return the value returned by
182 // this function.
183 Instruction *EraseInstFromFunction(Instruction &I) {
184 assert(I.use_empty() && "Cannot erase instruction that is used!");
185 AddUsesToWorkList(I);
186 removeFromWorkList(&I);
187 I.getParent()->getInstList().erase(&I);
188 return 0; // Don't do anything with FI
189 }
190
191
Chris Lattner3ac7c262003-08-13 20:16:26 +0000192 private:
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000193 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194 /// InsertBefore instruction. This is specialized a bit to avoid inserting
195 /// casts that are known to not do anything...
196 ///
197 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198 Instruction *InsertBefore);
199
Chris Lattner7fb29e12003-03-11 00:12:48 +0000200 // SimplifyCommutative - This performs a few simplifications for commutative
201 // operators...
202 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerba1cb382003-09-19 17:17:26 +0000203
204 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
205 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattner260ab202002-04-18 17:39:14 +0000206 };
Chris Lattnerb28b6802002-07-23 18:06:35 +0000207
Chris Lattnerc8b70922002-07-26 21:12:46 +0000208 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattner260ab202002-04-18 17:39:14 +0000209}
210
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000211// getComplexity: Assign a complexity or rank value to LLVM Values...
212// 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
213static unsigned getComplexity(Value *V) {
214 if (isa<Instruction>(V)) {
215 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
216 return 2;
217 return 3;
218 }
219 if (isa<Argument>(V)) return 2;
220 return isa<Constant>(V) ? 0 : 1;
221}
Chris Lattner260ab202002-04-18 17:39:14 +0000222
Chris Lattner7fb29e12003-03-11 00:12:48 +0000223// isOnlyUse - Return true if this instruction will be deleted if we stop using
224// it.
225static bool isOnlyUse(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000226 return V->hasOneUse() || isa<Constant>(V);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000227}
228
Chris Lattnere79e8542004-02-23 06:38:22 +0000229// getPromotedType - Return the specified type promoted as it would be to pass
230// though a va_arg area...
231static const Type *getPromotedType(const Type *Ty) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000232 switch (Ty->getTypeID()) {
Chris Lattnere79e8542004-02-23 06:38:22 +0000233 case Type::SByteTyID:
234 case Type::ShortTyID: return Type::IntTy;
235 case Type::UByteTyID:
236 case Type::UShortTyID: return Type::UIntTy;
237 case Type::FloatTyID: return Type::DoubleTy;
238 default: return Ty;
239 }
240}
241
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000242// SimplifyCommutative - This performs a few simplifications for commutative
243// operators:
Chris Lattner260ab202002-04-18 17:39:14 +0000244//
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000245// 1. Order operands such that they are listed from right (least complex) to
246// left (most complex). This puts constants before unary operators before
247// binary operators.
248//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000249// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
250// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000251//
Chris Lattner7fb29e12003-03-11 00:12:48 +0000252bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000253 bool Changed = false;
254 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
255 Changed = !I.swapOperands();
256
257 if (!I.isAssociative()) return Changed;
258 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattner7fb29e12003-03-11 00:12:48 +0000259 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
260 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
261 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner34428442003-05-27 16:40:51 +0000262 Constant *Folded = ConstantExpr::get(I.getOpcode(),
263 cast<Constant>(I.getOperand(1)),
264 cast<Constant>(Op->getOperand(1)));
Chris Lattner7fb29e12003-03-11 00:12:48 +0000265 I.setOperand(0, Op->getOperand(0));
266 I.setOperand(1, Folded);
267 return true;
268 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
269 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
270 isOnlyUse(Op) && isOnlyUse(Op1)) {
271 Constant *C1 = cast<Constant>(Op->getOperand(1));
272 Constant *C2 = cast<Constant>(Op1->getOperand(1));
273
274 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner34428442003-05-27 16:40:51 +0000275 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattner7fb29e12003-03-11 00:12:48 +0000276 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
277 Op1->getOperand(0),
278 Op1->getName(), &I);
279 WorkList.push_back(New);
280 I.setOperand(0, New);
281 I.setOperand(1, Folded);
282 return true;
283 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000284 }
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000285 return Changed;
Chris Lattner260ab202002-04-18 17:39:14 +0000286}
Chris Lattnerca081252001-12-14 16:52:21 +0000287
Chris Lattnerbb74e222003-03-10 23:06:50 +0000288// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
289// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattner9fa53de2002-05-06 16:49:18 +0000290//
Chris Lattnerbb74e222003-03-10 23:06:50 +0000291static inline Value *dyn_castNegVal(Value *V) {
292 if (BinaryOperator::isNeg(V))
293 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
294
Chris Lattner9244df62003-04-30 22:19:10 +0000295 // Constants can be considered to be negated values if they can be folded...
296 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000297 return ConstantExpr::getNeg(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000298 return 0;
Chris Lattner9fa53de2002-05-06 16:49:18 +0000299}
300
Chris Lattnerbb74e222003-03-10 23:06:50 +0000301static inline Value *dyn_castNotVal(Value *V) {
302 if (BinaryOperator::isNot(V))
303 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
304
305 // Constants can be considered to be not'ed values...
Chris Lattnerdd65d862003-04-30 22:34:06 +0000306 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattnerc8e7e292004-06-10 02:12:35 +0000307 return ConstantExpr::getNot(C);
Chris Lattnerbb74e222003-03-10 23:06:50 +0000308 return 0;
309}
310
Chris Lattner7fb29e12003-03-11 00:12:48 +0000311// dyn_castFoldableMul - If this value is a multiply that can be folded into
312// other computations (because it has a constant operand), return the
313// non-constant operand of the multiply.
314//
315static inline Value *dyn_castFoldableMul(Value *V) {
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000316 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner7fb29e12003-03-11 00:12:48 +0000317 if (Instruction *I = dyn_cast<Instruction>(V))
318 if (I->getOpcode() == Instruction::Mul)
319 if (isa<Constant>(I->getOperand(1)))
320 return I->getOperand(0);
321 return 0;
Chris Lattner3082c5a2003-02-18 19:28:33 +0000322}
Chris Lattner31ae8632002-08-14 17:51:49 +0000323
Chris Lattner3082c5a2003-02-18 19:28:33 +0000324// Log2 - Calculate the log base 2 for the specified value if it is exactly a
325// power of 2.
326static unsigned Log2(uint64_t Val) {
327 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
328 unsigned Count = 0;
329 while (Val != 1) {
330 if (Val & 1) return 0; // Multiple bits set?
331 Val >>= 1;
332 ++Count;
333 }
334 return Count;
Chris Lattner31ae8632002-08-14 17:51:49 +0000335}
336
Chris Lattnerb8b97502003-08-13 19:01:45 +0000337
338/// AssociativeOpt - Perform an optimization on an associative operator. This
339/// function is designed to check a chain of associative operators for a
340/// potential to apply a certain optimization. Since the optimization may be
341/// applicable if the expression was reassociated, this checks the chain, then
342/// reassociates the expression as necessary to expose the optimization
343/// opportunity. This makes use of a special Functor, which must define
344/// 'shouldApply' and 'apply' methods.
345///
346template<typename Functor>
347Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
348 unsigned Opcode = Root.getOpcode();
349 Value *LHS = Root.getOperand(0);
350
351 // Quick check, see if the immediate LHS matches...
352 if (F.shouldApply(LHS))
353 return F.apply(Root);
354
355 // Otherwise, if the LHS is not of the same opcode as the root, return.
356 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000357 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000358 // Should we apply this transform to the RHS?
359 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
360
361 // If not to the RHS, check to see if we should apply to the LHS...
362 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
363 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
364 ShouldApply = true;
365 }
366
367 // If the functor wants to apply the optimization to the RHS of LHSI,
368 // reassociate the expression from ((? op A) op B) to (? op (A op B))
369 if (ShouldApply) {
370 BasicBlock *BB = Root.getParent();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000371
372 // Now all of the instructions are in the current basic block, go ahead
373 // and perform the reassociation.
374 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
375
376 // First move the selected RHS to the LHS of the root...
377 Root.setOperand(0, LHSI->getOperand(1));
378
379 // Make what used to be the LHS of the root be the user of the root...
380 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner284d3b02004-04-16 18:08:07 +0000381 if (&Root == TmpLHSI) {
Chris Lattner8953b902004-04-05 02:10:19 +0000382 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
383 return 0;
384 }
Chris Lattner284d3b02004-04-16 18:08:07 +0000385 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattnerb8b97502003-08-13 19:01:45 +0000386 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner284d3b02004-04-16 18:08:07 +0000387 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
388 BasicBlock::iterator ARI = &Root; ++ARI;
389 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
390 ARI = Root;
Chris Lattnerb8b97502003-08-13 19:01:45 +0000391
392 // Now propagate the ExtraOperand down the chain of instructions until we
393 // get to LHSI.
394 while (TmpLHSI != LHSI) {
395 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner284d3b02004-04-16 18:08:07 +0000396 // Move the instruction to immediately before the chain we are
397 // constructing to avoid breaking dominance properties.
398 NextLHSI->getParent()->getInstList().remove(NextLHSI);
399 BB->getInstList().insert(ARI, NextLHSI);
400 ARI = NextLHSI;
401
Chris Lattnerb8b97502003-08-13 19:01:45 +0000402 Value *NextOp = NextLHSI->getOperand(1);
403 NextLHSI->setOperand(1, ExtraOperand);
404 TmpLHSI = NextLHSI;
405 ExtraOperand = NextOp;
406 }
407
408 // Now that the instructions are reassociated, have the functor perform
409 // the transformation...
410 return F.apply(Root);
411 }
412
413 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
414 }
415 return 0;
416}
417
418
419// AddRHS - Implements: X + X --> X << 1
420struct AddRHS {
421 Value *RHS;
422 AddRHS(Value *rhs) : RHS(rhs) {}
423 bool shouldApply(Value *LHS) const { return LHS == RHS; }
424 Instruction *apply(BinaryOperator &Add) const {
425 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
426 ConstantInt::get(Type::UByteTy, 1));
427 }
428};
429
430// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
431// iff C1&C2 == 0
432struct AddMaskingAnd {
433 Constant *C2;
434 AddMaskingAnd(Constant *c) : C2(c) {}
435 bool shouldApply(Value *LHS) const {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000436 ConstantInt *C1;
437 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
438 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattnerb8b97502003-08-13 19:01:45 +0000439 }
440 Instruction *apply(BinaryOperator &Add) const {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000441 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000442 }
443};
444
Chris Lattner183b3362004-04-09 19:05:30 +0000445static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
446 InstCombiner *IC) {
447 // Figure out if the constant is the left or the right argument.
448 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
449 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
Chris Lattnerb8b97502003-08-13 19:01:45 +0000450
Chris Lattner183b3362004-04-09 19:05:30 +0000451 if (Constant *SOC = dyn_cast<Constant>(SO)) {
452 if (ConstIsRHS)
453 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
454 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
455 }
456
457 Value *Op0 = SO, *Op1 = ConstOperand;
458 if (!ConstIsRHS)
459 std::swap(Op0, Op1);
460 Instruction *New;
461 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
462 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
463 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
464 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
Chris Lattnerf9d96652004-04-10 19:15:56 +0000465 else {
Chris Lattner183b3362004-04-09 19:05:30 +0000466 assert(0 && "Unknown binary instruction type!");
Chris Lattnerf9d96652004-04-10 19:15:56 +0000467 abort();
468 }
Chris Lattner183b3362004-04-09 19:05:30 +0000469 return IC->InsertNewInstBefore(New, BI);
470}
471
472// FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
473// constant as the other operand, try to fold the binary operator into the
474// select arguments.
475static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
476 InstCombiner *IC) {
477 // Don't modify shared select instructions
478 if (!SI->hasOneUse()) return 0;
479 Value *TV = SI->getOperand(1);
480 Value *FV = SI->getOperand(2);
481
482 if (isa<Constant>(TV) || isa<Constant>(FV)) {
483 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
484 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
485
486 return new SelectInst(SI->getCondition(), SelectTrueVal,
487 SelectFalseVal);
488 }
489 return 0;
490}
Chris Lattnerb8b97502003-08-13 19:01:45 +0000491
Chris Lattner113f4f42002-06-25 16:13:24 +0000492Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000493 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +0000494 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000495
Chris Lattnercf4a9962004-04-10 22:01:55 +0000496 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
497 // X + 0 --> X
498 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
499 RHSC->isNullValue())
500 return ReplaceInstUsesWith(I, LHS);
501
502 // X + (signbit) --> X ^ signbit
503 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
504 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
505 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
506 if (Val == (1ULL << NumBits-1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000507 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnercf4a9962004-04-10 22:01:55 +0000508 }
509 }
Chris Lattner9fa53de2002-05-06 16:49:18 +0000510
Chris Lattnerb8b97502003-08-13 19:01:45 +0000511 // X + X --> X << 1
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000512 if (I.getType()->isInteger()) {
Chris Lattnerb8b97502003-08-13 19:01:45 +0000513 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000514 }
Chris Lattnerede3fe02003-08-13 04:18:28 +0000515
Chris Lattner147e9752002-05-08 22:46:53 +0000516 // -A + B --> B - A
Chris Lattnerbb74e222003-03-10 23:06:50 +0000517 if (Value *V = dyn_castNegVal(LHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000518 return BinaryOperator::createSub(RHS, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000519
520 // A + -B --> A - B
Chris Lattnerbb74e222003-03-10 23:06:50 +0000521 if (!isa<Constant>(RHS))
522 if (Value *V = dyn_castNegVal(RHS))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000523 return BinaryOperator::createSub(LHS, V);
Chris Lattner260ab202002-04-18 17:39:14 +0000524
Chris Lattner57c8d992003-02-18 19:57:07 +0000525 // X*C + X --> X * (C+1)
526 if (dyn_castFoldableMul(LHS) == RHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000527 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000528 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000529 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
530 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000531 return BinaryOperator::createMul(RHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000532 }
533
534 // X + X*C --> X * (C+1)
535 if (dyn_castFoldableMul(RHS) == LHS) {
Chris Lattner34428442003-05-27 16:40:51 +0000536 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000537 ConstantExpr::getAdd(
Chris Lattner34428442003-05-27 16:40:51 +0000538 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
539 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000540 return BinaryOperator::createMul(LHS, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000541 }
542
Chris Lattnerb8b97502003-08-13 19:01:45 +0000543 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +0000544 ConstantInt *C2;
545 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnerb8b97502003-08-13 19:01:45 +0000546 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattner7fb29e12003-03-11 00:12:48 +0000547
Chris Lattnerb9cde762003-10-02 15:11:26 +0000548 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattnerd4252a72004-07-30 07:50:03 +0000549 Value *X;
550 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
551 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
552 return BinaryOperator::createSub(C, X);
Chris Lattnerb9cde762003-10-02 15:11:26 +0000553 }
Chris Lattnerd4252a72004-07-30 07:50:03 +0000554
555 // Try to fold constant add into select arguments.
556 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
557 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
558 return R;
Chris Lattnerb9cde762003-10-02 15:11:26 +0000559 }
560
Chris Lattner113f4f42002-06-25 16:13:24 +0000561 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000562}
563
Chris Lattnerbdb0ce02003-07-22 21:46:59 +0000564// isSignBit - Return true if the value represented by the constant only has the
565// highest order bit set.
566static bool isSignBit(ConstantInt *CI) {
567 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
568 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
569}
570
Chris Lattnerdfae8be2003-07-24 17:35:25 +0000571static unsigned getTypeSizeInBits(const Type *Ty) {
572 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
573}
574
Chris Lattner022167f2004-03-13 00:11:49 +0000575/// RemoveNoopCast - Strip off nonconverting casts from the value.
576///
577static Value *RemoveNoopCast(Value *V) {
578 if (CastInst *CI = dyn_cast<CastInst>(V)) {
579 const Type *CTy = CI->getType();
580 const Type *OpTy = CI->getOperand(0)->getType();
581 if (CTy->isInteger() && OpTy->isInteger()) {
582 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
583 return RemoveNoopCast(CI->getOperand(0));
584 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
585 return RemoveNoopCast(CI->getOperand(0));
586 }
587 return V;
588}
589
Chris Lattner113f4f42002-06-25 16:13:24 +0000590Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +0000591 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000592
Chris Lattnere6794492002-08-12 21:17:25 +0000593 if (Op0 == Op1) // sub X, X -> 0
594 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner260ab202002-04-18 17:39:14 +0000595
Chris Lattnere6794492002-08-12 21:17:25 +0000596 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattnerbb74e222003-03-10 23:06:50 +0000597 if (Value *V = dyn_castNegVal(Op1))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000598 return BinaryOperator::createAdd(Op0, V);
Chris Lattner9fa53de2002-05-06 16:49:18 +0000599
Chris Lattner8f2f5982003-11-05 01:06:05 +0000600 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
601 // Replace (-1 - A) with (~A)...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000602 if (C->isAllOnesValue())
603 return BinaryOperator::createNot(Op1);
Chris Lattnerad3c4952002-05-09 01:29:19 +0000604
Chris Lattner8f2f5982003-11-05 01:06:05 +0000605 // C - ~X == X + (1+C)
Chris Lattnerd4252a72004-07-30 07:50:03 +0000606 Value *X;
607 if (match(Op1, m_Not(m_Value(X))))
608 return BinaryOperator::createAdd(X,
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000609 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner92295c52004-03-12 23:53:13 +0000610 // -((uint)X >> 31) -> ((int)X >> 31)
611 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattner022167f2004-03-13 00:11:49 +0000612 if (C->isNullValue()) {
613 Value *NoopCastedRHS = RemoveNoopCast(Op1);
614 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner92295c52004-03-12 23:53:13 +0000615 if (SI->getOpcode() == Instruction::Shr)
616 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
617 const Type *NewTy;
Chris Lattner022167f2004-03-13 00:11:49 +0000618 if (SI->getType()->isSigned())
Chris Lattner97bfcea2004-06-17 18:16:02 +0000619 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000620 else
Chris Lattner97bfcea2004-06-17 18:16:02 +0000621 NewTy = SI->getType()->getSignedVersion();
Chris Lattner92295c52004-03-12 23:53:13 +0000622 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner022167f2004-03-13 00:11:49 +0000623 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
Chris Lattner92295c52004-03-12 23:53:13 +0000624 // Ok, the transformation is safe. Insert a cast of the incoming
625 // value, then the new shift, then the new cast.
626 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
627 SI->getOperand(0)->getName());
628 Value *InV = InsertNewInstBefore(FirstCast, I);
629 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
630 CU, SI->getName());
Chris Lattner022167f2004-03-13 00:11:49 +0000631 if (NewShift->getType() == I.getType())
632 return NewShift;
633 else {
634 InV = InsertNewInstBefore(NewShift, I);
635 return new CastInst(NewShift, I.getType());
636 }
Chris Lattner92295c52004-03-12 23:53:13 +0000637 }
638 }
Chris Lattner022167f2004-03-13 00:11:49 +0000639 }
Chris Lattner183b3362004-04-09 19:05:30 +0000640
641 // Try to fold constant sub into select arguments.
642 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
643 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
644 return R;
Chris Lattner8f2f5982003-11-05 01:06:05 +0000645 }
646
Chris Lattner3082c5a2003-02-18 19:28:33 +0000647 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattnerf95d9b92003-10-15 16:48:29 +0000648 if (Op1I->hasOneUse()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000649 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
650 // is not used by anyone else...
651 //
Chris Lattnerc2f0aa52004-02-02 20:09:56 +0000652 if (Op1I->getOpcode() == Instruction::Sub &&
653 !Op1I->getType()->isFloatingPoint()) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000654 // Swap the two operands of the subexpr...
655 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
656 Op1I->setOperand(0, IIOp1);
657 Op1I->setOperand(1, IIOp0);
658
659 // Create the new top level add instruction...
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000660 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000661 }
662
663 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
664 //
665 if (Op1I->getOpcode() == Instruction::And &&
666 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
667 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
668
Chris Lattner396dbfe2004-06-09 05:08:07 +0000669 Value *NewNot =
670 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000671 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000672 }
Chris Lattner57c8d992003-02-18 19:57:07 +0000673
674 // X - X*C --> X * (1-C)
675 if (dyn_castFoldableMul(Op1I) == Op0) {
Chris Lattner34428442003-05-27 16:40:51 +0000676 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000677 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Chris Lattner34428442003-05-27 16:40:51 +0000678 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
Chris Lattner57c8d992003-02-18 19:57:07 +0000679 assert(CP1 && "Couldn't constant fold 1-C?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000680 return BinaryOperator::createMul(Op0, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000681 }
Chris Lattnerad3c4952002-05-09 01:29:19 +0000682 }
Chris Lattner3082c5a2003-02-18 19:28:33 +0000683
Chris Lattner57c8d992003-02-18 19:57:07 +0000684 // X*C - X --> X * (C-1)
685 if (dyn_castFoldableMul(Op0) == Op1) {
Chris Lattner34428442003-05-27 16:40:51 +0000686 Constant *CP1 =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000687 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
Chris Lattner34428442003-05-27 16:40:51 +0000688 ConstantInt::get(I.getType(), 1));
Chris Lattner57c8d992003-02-18 19:57:07 +0000689 assert(CP1 && "Couldn't constant fold C - 1?");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000690 return BinaryOperator::createMul(Op1, CP1);
Chris Lattner57c8d992003-02-18 19:57:07 +0000691 }
692
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000693 return 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000694}
695
Chris Lattnere79e8542004-02-23 06:38:22 +0000696/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
697/// really just returns true if the most significant (sign) bit is set.
698static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
699 if (RHS->getType()->isSigned()) {
700 // True if source is LHS < 0 or LHS <= -1
701 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
702 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
703 } else {
704 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
705 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
706 // the size of the integer type.
707 if (Opcode == Instruction::SetGE)
708 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
709 if (Opcode == Instruction::SetGT)
710 return RHSC->getValue() ==
711 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
712 }
713 return false;
714}
715
Chris Lattner113f4f42002-06-25 16:13:24 +0000716Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +0000717 bool Changed = SimplifyCommutative(I);
Chris Lattner3082c5a2003-02-18 19:28:33 +0000718 Value *Op0 = I.getOperand(0);
Chris Lattner260ab202002-04-18 17:39:14 +0000719
Chris Lattnere6794492002-08-12 21:17:25 +0000720 // Simplify mul instructions with a constant RHS...
Chris Lattner3082c5a2003-02-18 19:28:33 +0000721 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
722 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerede3fe02003-08-13 04:18:28 +0000723
724 // ((X << C1)*C2) == (X * (C2 << C1))
725 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
726 if (SI->getOpcode() == Instruction::Shl)
727 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000728 return BinaryOperator::createMul(SI->getOperand(0),
729 ConstantExpr::getShl(CI, ShOp));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +0000730
Chris Lattnercce81be2003-09-11 22:24:54 +0000731 if (CI->isNullValue())
732 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
733 if (CI->equalsInt(1)) // X * 1 == X
734 return ReplaceInstUsesWith(I, Op0);
735 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner35236d82003-06-25 17:09:20 +0000736 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner31ba1292002-04-29 22:24:47 +0000737
Chris Lattnercce81be2003-09-11 22:24:54 +0000738 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattner3082c5a2003-02-18 19:28:33 +0000739 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
740 return new ShiftInst(Instruction::Shl, Op0,
741 ConstantUInt::get(Type::UByteTy, C));
Robert Bocchino7b5b86c2004-07-27 21:02:21 +0000742 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000743 if (Op1F->isNullValue())
744 return ReplaceInstUsesWith(I, Op1);
Chris Lattner31ba1292002-04-29 22:24:47 +0000745
Chris Lattner3082c5a2003-02-18 19:28:33 +0000746 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
747 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
748 if (Op1F->getValue() == 1.0)
749 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
750 }
Chris Lattner183b3362004-04-09 19:05:30 +0000751
752 // Try to fold constant mul into select arguments.
753 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
754 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
755 return R;
Chris Lattner260ab202002-04-18 17:39:14 +0000756 }
757
Chris Lattner934a64cf2003-03-10 23:23:04 +0000758 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
759 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000760 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattner934a64cf2003-03-10 23:23:04 +0000761
Chris Lattner2635b522004-02-23 05:39:21 +0000762 // If one of the operands of the multiply is a cast from a boolean value, then
763 // we know the bool is either zero or one, so this is a 'masking' multiply.
764 // See if we can simplify things based on how the boolean was originally
765 // formed.
766 CastInst *BoolCast = 0;
767 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
768 if (CI->getOperand(0)->getType() == Type::BoolTy)
769 BoolCast = CI;
770 if (!BoolCast)
771 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
772 if (CI->getOperand(0)->getType() == Type::BoolTy)
773 BoolCast = CI;
774 if (BoolCast) {
775 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
776 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
777 const Type *SCOpTy = SCIOp0->getType();
778
Chris Lattnere79e8542004-02-23 06:38:22 +0000779 // If the setcc is true iff the sign bit of X is set, then convert this
780 // multiply into a shift/and combination.
781 if (isa<ConstantInt>(SCIOp1) &&
782 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattner2635b522004-02-23 05:39:21 +0000783 // Shift the X value right to turn it into "all signbits".
784 Constant *Amt = ConstantUInt::get(Type::UByteTy,
785 SCOpTy->getPrimitiveSize()*8-1);
Chris Lattnere79e8542004-02-23 06:38:22 +0000786 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +0000787 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattnere79e8542004-02-23 06:38:22 +0000788 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
789 SCIOp0->getName()), I);
790 }
791
792 Value *V =
793 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
794 BoolCast->getOperand(0)->getName()+
795 ".mask"), I);
Chris Lattner2635b522004-02-23 05:39:21 +0000796
797 // If the multiply type is not the same as the source type, sign extend
798 // or truncate to the multiply type.
799 if (I.getType() != V->getType())
Chris Lattnere79e8542004-02-23 06:38:22 +0000800 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Chris Lattner2635b522004-02-23 05:39:21 +0000801
802 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000803 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattner2635b522004-02-23 05:39:21 +0000804 }
805 }
806 }
807
Chris Lattner113f4f42002-06-25 16:13:24 +0000808 return Changed ? &I : 0;
Chris Lattner260ab202002-04-18 17:39:14 +0000809}
810
Chris Lattner113f4f42002-06-25 16:13:24 +0000811Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner3082c5a2003-02-18 19:28:33 +0000812 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
Chris Lattnere20c3342004-04-26 14:01:59 +0000813 // div X, 1 == X
Chris Lattnere6794492002-08-12 21:17:25 +0000814 if (RHS->equalsInt(1))
815 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner3082c5a2003-02-18 19:28:33 +0000816
Chris Lattnere20c3342004-04-26 14:01:59 +0000817 // div X, -1 == -X
818 if (RHS->isAllOnesValue())
819 return BinaryOperator::createNeg(I.getOperand(0));
820
Chris Lattner3082c5a2003-02-18 19:28:33 +0000821 // Check to see if this is an unsigned division with an exact power of 2,
822 // if so, convert to a right shift.
823 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
824 if (uint64_t Val = C->getValue()) // Don't break X / 0
825 if (uint64_t C = Log2(Val))
826 return new ShiftInst(Instruction::Shr, I.getOperand(0),
827 ConstantUInt::get(Type::UByteTy, C));
828 }
829
830 // 0 / X == 0, we don't need to preserve faults!
831 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
832 if (LHS->equalsInt(0))
833 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
834
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000835 return 0;
836}
837
838
Chris Lattner113f4f42002-06-25 16:13:24 +0000839Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000840 if (I.getType()->isSigned())
841 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
Chris Lattner98c6bdf2004-07-06 07:11:42 +0000842 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattner8e726062004-08-09 21:05:48 +0000843 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner7fd5f072004-07-06 07:01:22 +0000844 // X % -Y -> X % Y
845 AddUsesToWorkList(I);
846 I.setOperand(1, RHSNeg);
847 return &I;
848 }
849
Chris Lattner3082c5a2003-02-18 19:28:33 +0000850 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
851 if (RHS->equalsInt(1)) // X % 1 == 0
852 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
853
854 // Check to see if this is an unsigned remainder with an exact power of 2,
855 // if so, convert to a bitwise and.
856 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
857 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattnerd9e58132004-05-07 15:35:56 +0000858 if (!(Val & (Val-1))) // Power of 2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +0000859 return BinaryOperator::createAnd(I.getOperand(0),
Chris Lattner3082c5a2003-02-18 19:28:33 +0000860 ConstantUInt::get(I.getType(), Val-1));
861 }
862
863 // 0 % X == 0, we don't need to preserve faults!
864 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
865 if (LHS->equalsInt(0))
Chris Lattnere6794492002-08-12 21:17:25 +0000866 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
867
Chris Lattnerf4cdbf32002-05-06 16:14:14 +0000868 return 0;
869}
870
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000871// isMaxValueMinusOne - return true if this is Max-1
Chris Lattnere6794492002-08-12 21:17:25 +0000872static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000873 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
874 // Calculate -1 casted to the right type...
875 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
876 uint64_t Val = ~0ULL; // All ones
877 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
878 return CU->getValue() == Val-1;
879 }
880
881 const ConstantSInt *CS = cast<ConstantSInt>(C);
882
883 // Calculate 0111111111..11111
884 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
885 int64_t Val = INT64_MAX; // All ones
886 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
887 return CS->getValue() == Val-1;
888}
889
890// isMinValuePlusOne - return true if this is Min+1
Chris Lattnere6794492002-08-12 21:17:25 +0000891static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +0000892 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
893 return CU->getValue() == 1;
894
895 const ConstantSInt *CS = cast<ConstantSInt>(C);
896
897 // Calculate 1111111111000000000000
898 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
899 int64_t Val = -1; // All ones
900 Val <<= TypeBits-1; // Shift over to the right spot
901 return CS->getValue() == Val+1;
902}
903
Chris Lattner35167c32004-06-09 07:59:58 +0000904// isOneBitSet - Return true if there is exactly one bit set in the specified
905// constant.
906static bool isOneBitSet(const ConstantInt *CI) {
907 uint64_t V = CI->getRawValue();
908 return V && (V & (V-1)) == 0;
909}
910
Chris Lattner8fc5af42004-09-23 21:46:38 +0000911#if 0 // Currently unused
912// isLowOnes - Return true if the constant is of the form 0+1+.
913static bool isLowOnes(const ConstantInt *CI) {
914 uint64_t V = CI->getRawValue();
915
916 // There won't be bits set in parts that the type doesn't contain.
917 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
918
919 uint64_t U = V+1; // If it is low ones, this should be a power of two.
920 return U && V && (U & V) == 0;
921}
922#endif
923
924// isHighOnes - Return true if the constant is of the form 1+0+.
925// This is the same as lowones(~X).
926static bool isHighOnes(const ConstantInt *CI) {
927 uint64_t V = ~CI->getRawValue();
928
929 // There won't be bits set in parts that the type doesn't contain.
930 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
931
932 uint64_t U = V+1; // If it is low ones, this should be a power of two.
933 return U && V && (U & V) == 0;
934}
935
936
Chris Lattner3ac7c262003-08-13 20:16:26 +0000937/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
938/// are carefully arranged to allow folding of expressions such as:
939///
940/// (A < B) | (A > B) --> (A != B)
941///
942/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
943/// represents that the comparison is true if A == B, and bit value '1' is true
944/// if A < B.
945///
946static unsigned getSetCondCode(const SetCondInst *SCI) {
947 switch (SCI->getOpcode()) {
948 // False -> 0
949 case Instruction::SetGT: return 1;
950 case Instruction::SetEQ: return 2;
951 case Instruction::SetGE: return 3;
952 case Instruction::SetLT: return 4;
953 case Instruction::SetNE: return 5;
954 case Instruction::SetLE: return 6;
955 // True -> 7
956 default:
957 assert(0 && "Invalid SetCC opcode!");
958 return 0;
959 }
960}
961
962/// getSetCCValue - This is the complement of getSetCondCode, which turns an
963/// opcode and two operands into either a constant true or false, or a brand new
964/// SetCC instruction.
965static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
966 switch (Opcode) {
967 case 0: return ConstantBool::False;
968 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
969 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
970 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
971 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
972 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
973 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
974 case 7: return ConstantBool::True;
975 default: assert(0 && "Illegal SetCCCode!"); return 0;
976 }
977}
978
979// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
980struct FoldSetCCLogical {
981 InstCombiner &IC;
982 Value *LHS, *RHS;
983 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
984 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
985 bool shouldApply(Value *V) const {
986 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
987 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
988 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
989 return false;
990 }
991 Instruction *apply(BinaryOperator &Log) const {
992 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
993 if (SCI->getOperand(0) != LHS) {
994 assert(SCI->getOperand(1) == LHS);
995 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
996 }
997
998 unsigned LHSCode = getSetCondCode(SCI);
999 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1000 unsigned Code;
1001 switch (Log.getOpcode()) {
1002 case Instruction::And: Code = LHSCode & RHSCode; break;
1003 case Instruction::Or: Code = LHSCode | RHSCode; break;
1004 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner2caaaba2003-09-22 20:33:34 +00001005 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattner3ac7c262003-08-13 20:16:26 +00001006 }
1007
1008 Value *RV = getSetCCValue(Code, LHS, RHS);
1009 if (Instruction *I = dyn_cast<Instruction>(RV))
1010 return I;
1011 // Otherwise, it's a constant boolean value...
1012 return IC.ReplaceInstUsesWith(Log, RV);
1013 }
1014};
1015
1016
Chris Lattnerba1cb382003-09-19 17:17:26 +00001017// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1018// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1019// guaranteed to be either a shift instruction or a binary operator.
1020Instruction *InstCombiner::OptAndOp(Instruction *Op,
1021 ConstantIntegral *OpRHS,
1022 ConstantIntegral *AndRHS,
1023 BinaryOperator &TheAnd) {
1024 Value *X = Op->getOperand(0);
Chris Lattnerfcf21a72004-01-12 19:47:05 +00001025 Constant *Together = 0;
1026 if (!isa<ShiftInst>(Op))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001027 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001028
Chris Lattnerba1cb382003-09-19 17:17:26 +00001029 switch (Op->getOpcode()) {
1030 case Instruction::Xor:
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001031 if (Together->isNullValue()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001032 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001033 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001034 } else if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001035 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1036 std::string OpName = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001037 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001038 InsertNewInstBefore(And, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001039 return BinaryOperator::createXor(And, Together);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001040 }
1041 break;
1042 case Instruction::Or:
1043 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001044 if (Together->isNullValue())
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001045 return BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001046 else {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001047 if (Together == AndRHS) // (X | C) & C --> C
1048 return ReplaceInstUsesWith(TheAnd, AndRHS);
1049
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001050 if (Op->hasOneUse() && Together != OpRHS) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001051 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1052 std::string Op0Name = Op->getName(); Op->setName("");
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001053 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001054 InsertNewInstBefore(Or, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001055 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001056 }
1057 }
1058 break;
1059 case Instruction::Add:
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001060 if (Op->hasOneUse()) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001061 // Adding a one to a single bit bit-field should be turned into an XOR
1062 // of the bit. First thing to check is to see if this AND is with a
1063 // single bit constant.
Chris Lattner35167c32004-06-09 07:59:58 +00001064 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001065
1066 // Clear bits that are not part of the constant.
1067 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1068
1069 // If there is only one bit set...
Chris Lattner35167c32004-06-09 07:59:58 +00001070 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerba1cb382003-09-19 17:17:26 +00001071 // Ok, at this point, we know that we are masking the result of the
1072 // ADD down to exactly one bit. If the constant we are adding has
1073 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner35167c32004-06-09 07:59:58 +00001074 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Chris Lattnerba1cb382003-09-19 17:17:26 +00001075
1076 // Check to see if any bits below the one bit set in AndRHSV are set.
1077 if ((AddRHS & (AndRHSV-1)) == 0) {
1078 // If not, the only thing that can effect the output of the AND is
1079 // the bit specified by AndRHSV. If that bit is set, the effect of
1080 // the XOR is to toggle the bit. If it is clear, then the ADD has
1081 // no effect.
1082 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1083 TheAnd.setOperand(0, X);
1084 return &TheAnd;
1085 } else {
1086 std::string Name = Op->getName(); Op->setName("");
1087 // Pull the XOR out of the AND.
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001088 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001089 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001090 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerba1cb382003-09-19 17:17:26 +00001091 }
1092 }
1093 }
1094 }
1095 break;
Chris Lattner2da29172003-09-19 19:05:02 +00001096
1097 case Instruction::Shl: {
1098 // We know that the AND will not produce any of the bits shifted in, so if
1099 // the anded constant includes them, clear them now!
1100 //
1101 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001102 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1103 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1104
1105 if (CI == ShlMask) { // Masking out bits that the shift already masks
1106 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1107 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner2da29172003-09-19 19:05:02 +00001108 TheAnd.setOperand(1, CI);
1109 return &TheAnd;
1110 }
1111 break;
1112 }
1113 case Instruction::Shr:
1114 // We know that the AND will not produce any of the bits shifted in, so if
1115 // the anded constant includes them, clear them now! This only applies to
1116 // unsigned shifts, because a signed shr may bring in set bits!
1117 //
1118 if (AndRHS->getType()->isUnsigned()) {
1119 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner7e794272004-09-24 15:21:34 +00001120 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1121 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1122
1123 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1124 return ReplaceInstUsesWith(TheAnd, Op);
1125 } else if (CI != AndRHS) {
1126 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner2da29172003-09-19 19:05:02 +00001127 return &TheAnd;
1128 }
Chris Lattner7e794272004-09-24 15:21:34 +00001129 } else { // Signed shr.
1130 // See if this is shifting in some sign extension, then masking it out
1131 // with an and.
1132 if (Op->hasOneUse()) {
1133 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1134 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1135 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1136 if (CI == ShrMask) { // Masking out bits shifted in.
1137 // Make the argument unsigned.
1138 Value *ShVal = Op->getOperand(0);
1139 ShVal = InsertCastBefore(ShVal,
1140 ShVal->getType()->getUnsignedVersion(),
1141 TheAnd);
1142 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1143 OpRHS, Op->getName()),
1144 TheAnd);
1145 return new CastInst(ShVal, Op->getType());
1146 }
1147 }
Chris Lattner2da29172003-09-19 19:05:02 +00001148 }
1149 break;
Chris Lattnerba1cb382003-09-19 17:17:26 +00001150 }
1151 return 0;
1152}
1153
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001154
Chris Lattner113f4f42002-06-25 16:13:24 +00001155Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001156 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001157 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001158
1159 // and X, X = X and X, 0 == 0
Chris Lattnere6794492002-08-12 21:17:25 +00001160 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1161 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001162
1163 // and X, -1 == X
Chris Lattner49b47ae2003-07-23 17:57:01 +00001164 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001165 if (RHS->isAllOnesValue())
1166 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001167
Chris Lattnerba1cb382003-09-19 17:17:26 +00001168 // Optimize a variety of ((val OP C1) & C2) combinations...
1169 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1170 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner33217db2003-07-23 19:36:21 +00001171 Value *X = Op0I->getOperand(0);
Chris Lattner16464b32003-07-23 19:25:52 +00001172 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerba1cb382003-09-19 17:17:26 +00001173 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1174 return Res;
Chris Lattner33217db2003-07-23 19:36:21 +00001175 }
Chris Lattner183b3362004-04-09 19:05:30 +00001176
1177 // Try to fold constant and into select arguments.
1178 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1179 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1180 return R;
Chris Lattner49b47ae2003-07-23 17:57:01 +00001181 }
1182
Chris Lattnerbb74e222003-03-10 23:06:50 +00001183 Value *Op0NotVal = dyn_castNotVal(Op0);
1184 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001185
Chris Lattner023a4832004-06-18 06:07:51 +00001186 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1187 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1188
Misha Brukman9c003d82004-07-30 12:50:08 +00001189 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerbb74e222003-03-10 23:06:50 +00001190 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001191 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1192 I.getName()+".demorgan");
Chris Lattner49b47ae2003-07-23 17:57:01 +00001193 InsertNewInstBefore(Or, I);
Chris Lattner3082c5a2003-02-18 19:28:33 +00001194 return BinaryOperator::createNot(Or);
1195 }
1196
Chris Lattner3ac7c262003-08-13 20:16:26 +00001197 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1198 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1199 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1200 return R;
1201
Chris Lattner113f4f42002-06-25 16:13:24 +00001202 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001203}
1204
1205
1206
Chris Lattner113f4f42002-06-25 16:13:24 +00001207Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001208 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001209 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001210
1211 // or X, X = X or X, 0 == X
Chris Lattnere6794492002-08-12 21:17:25 +00001212 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1213 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001214
1215 // or X, -1 == -1
Chris Lattner8f0d1562003-07-23 18:29:44 +00001216 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnere6794492002-08-12 21:17:25 +00001217 if (RHS->isAllOnesValue())
1218 return ReplaceInstUsesWith(I, Op1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001219
Chris Lattnerd4252a72004-07-30 07:50:03 +00001220 ConstantInt *C1; Value *X;
1221 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1222 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1223 std::string Op0Name = Op0->getName(); Op0->setName("");
1224 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1225 InsertNewInstBefore(Or, I);
1226 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1227 }
Chris Lattner8f0d1562003-07-23 18:29:44 +00001228
Chris Lattnerd4252a72004-07-30 07:50:03 +00001229 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1230 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1231 std::string Op0Name = Op0->getName(); Op0->setName("");
1232 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1233 InsertNewInstBefore(Or, I);
1234 return BinaryOperator::createXor(Or,
1235 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattner8f0d1562003-07-23 18:29:44 +00001236 }
Chris Lattner183b3362004-04-09 19:05:30 +00001237
1238 // Try to fold constant and into select arguments.
1239 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1240 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1241 return R;
Chris Lattner8f0d1562003-07-23 18:29:44 +00001242 }
1243
Chris Lattner812aab72003-08-12 19:11:07 +00001244 // (A & C1)|(A & C2) == A & (C1|C2)
Chris Lattnerd4252a72004-07-30 07:50:03 +00001245 Value *A, *B; ConstantInt *C1, *C2;
1246 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1247 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1248 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
Chris Lattner812aab72003-08-12 19:11:07 +00001249
Chris Lattnerd4252a72004-07-30 07:50:03 +00001250 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1251 if (A == Op1) // ~A | A == -1
1252 return ReplaceInstUsesWith(I,
1253 ConstantIntegral::getAllOnesValue(I.getType()));
1254 } else {
1255 A = 0;
1256 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001257
Chris Lattnerd4252a72004-07-30 07:50:03 +00001258 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1259 if (Op0 == B)
1260 return ReplaceInstUsesWith(I,
1261 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattner3e327a42003-03-10 23:13:59 +00001262
Misha Brukman9c003d82004-07-30 12:50:08 +00001263 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattnerd4252a72004-07-30 07:50:03 +00001264 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1265 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1266 I.getName()+".demorgan"), I);
1267 return BinaryOperator::createNot(And);
1268 }
Chris Lattner3e327a42003-03-10 23:13:59 +00001269 }
Chris Lattner3082c5a2003-02-18 19:28:33 +00001270
Chris Lattner3ac7c262003-08-13 20:16:26 +00001271 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1272 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1273 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1274 return R;
1275
Chris Lattner113f4f42002-06-25 16:13:24 +00001276 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001277}
1278
Chris Lattnerc2076352004-02-16 01:20:27 +00001279// XorSelf - Implements: X ^ X --> 0
1280struct XorSelf {
1281 Value *RHS;
1282 XorSelf(Value *rhs) : RHS(rhs) {}
1283 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1284 Instruction *apply(BinaryOperator &Xor) const {
1285 return &Xor;
1286 }
1287};
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001288
1289
Chris Lattner113f4f42002-06-25 16:13:24 +00001290Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001291 bool Changed = SimplifyCommutative(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00001292 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001293
Chris Lattnerc2076352004-02-16 01:20:27 +00001294 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1295 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1296 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattnere6794492002-08-12 21:17:25 +00001297 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc2076352004-02-16 01:20:27 +00001298 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001299
Chris Lattner97638592003-07-23 21:37:07 +00001300 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001301 // xor X, 0 == X
Chris Lattner97638592003-07-23 21:37:07 +00001302 if (RHS->isNullValue())
Chris Lattnere6794492002-08-12 21:17:25 +00001303 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001304
Chris Lattner97638592003-07-23 21:37:07 +00001305 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001306 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattner97638592003-07-23 21:37:07 +00001307 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001308 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001309 return new SetCondInst(SCI->getInverseCondition(),
1310 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnere5806662003-11-04 23:50:51 +00001311
Chris Lattner8f2f5982003-11-05 01:06:05 +00001312 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001313 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1314 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001315 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1316 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001317 ConstantInt::get(I.getType(), 1));
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001318 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001319 }
Chris Lattner023a4832004-06-18 06:07:51 +00001320
1321 // ~(~X & Y) --> (X | ~Y)
1322 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1323 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1324 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1325 Instruction *NotY =
1326 BinaryOperator::createNot(Op0I->getOperand(1),
1327 Op0I->getOperand(1)->getName()+".not");
1328 InsertNewInstBefore(NotY, I);
1329 return BinaryOperator::createOr(Op0NotVal, NotY);
1330 }
1331 }
Chris Lattner97638592003-07-23 21:37:07 +00001332
1333 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnere5806662003-11-04 23:50:51 +00001334 switch (Op0I->getOpcode()) {
1335 case Instruction::Add:
Chris Lattner0f68fa62003-11-04 23:37:10 +00001336 // ~(X-c) --> (-c-1)-X
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001337 if (RHS->isAllOnesValue()) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001338 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1339 return BinaryOperator::createSub(
1340 ConstantExpr::getSub(NegOp0CI,
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001341 ConstantInt::get(I.getType(), 1)),
Chris Lattner0f68fa62003-11-04 23:37:10 +00001342 Op0I->getOperand(0));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001343 }
Chris Lattnere5806662003-11-04 23:50:51 +00001344 break;
1345 case Instruction::And:
Chris Lattner97638592003-07-23 21:37:07 +00001346 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001347 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1348 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnere5806662003-11-04 23:50:51 +00001349 break;
1350 case Instruction::Or:
Chris Lattner97638592003-07-23 21:37:07 +00001351 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001352 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001353 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnere5806662003-11-04 23:50:51 +00001354 break;
1355 default: break;
Chris Lattner97638592003-07-23 21:37:07 +00001356 }
Chris Lattnerb8d6e402002-08-20 18:24:26 +00001357 }
Chris Lattner183b3362004-04-09 19:05:30 +00001358
1359 // Try to fold constant and into select arguments.
1360 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1361 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1362 return R;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001363 }
1364
Chris Lattnerbb74e222003-03-10 23:06:50 +00001365 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001366 if (X == Op1)
1367 return ReplaceInstUsesWith(I,
1368 ConstantIntegral::getAllOnesValue(I.getType()));
1369
Chris Lattnerbb74e222003-03-10 23:06:50 +00001370 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattner3082c5a2003-02-18 19:28:33 +00001371 if (X == Op0)
1372 return ReplaceInstUsesWith(I,
1373 ConstantIntegral::getAllOnesValue(I.getType()));
1374
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001375 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattnerb36d9082004-02-16 03:54:20 +00001376 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001377 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1378 cast<BinaryOperator>(Op1I)->swapOperands();
1379 I.swapOperands();
1380 std::swap(Op0, Op1);
1381 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1382 I.swapOperands();
1383 std::swap(Op0, Op1);
Chris Lattnerb36d9082004-02-16 03:54:20 +00001384 }
1385 } else if (Op1I->getOpcode() == Instruction::Xor) {
1386 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1387 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1388 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1389 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1390 }
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001391
1392 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001393 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001394 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1395 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001396 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner396dbfe2004-06-09 05:08:07 +00001397 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1398 Op1->getName()+".not"), I);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001399 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001400 }
Chris Lattnerb36d9082004-02-16 03:54:20 +00001401 } else if (Op0I->getOpcode() == Instruction::Xor) {
1402 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1403 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1404 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1405 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner1bbb7b62003-03-10 18:24:17 +00001406 }
1407
Chris Lattner7aa2d472004-08-01 19:42:59 +00001408 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattnerd4252a72004-07-30 07:50:03 +00001409 Value *A, *B; ConstantInt *C1, *C2;
1410 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1411 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner7aa2d472004-08-01 19:42:59 +00001412 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattnerd4252a72004-07-30 07:50:03 +00001413 return BinaryOperator::createOr(Op0, Op1);
Chris Lattner7fb29e12003-03-11 00:12:48 +00001414
Chris Lattner3ac7c262003-08-13 20:16:26 +00001415 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1416 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1417 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1418 return R;
1419
Chris Lattner113f4f42002-06-25 16:13:24 +00001420 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001421}
1422
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001423// AddOne, SubOne - Add or subtract a constant one from an integer constant...
1424static Constant *AddOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001425 return ConstantExpr::getAdd(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001426}
1427static Constant *SubOne(ConstantInt *C) {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001428 return ConstantExpr::getSub(C, ConstantInt::get(C->getType(), 1));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001429}
1430
Chris Lattner1fc23f32002-05-09 20:11:54 +00001431// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1432// true when both operands are equal...
1433//
Chris Lattner113f4f42002-06-25 16:13:24 +00001434static bool isTrueWhenEqual(Instruction &I) {
1435 return I.getOpcode() == Instruction::SetEQ ||
1436 I.getOpcode() == Instruction::SetGE ||
1437 I.getOpcode() == Instruction::SetLE;
Chris Lattner1fc23f32002-05-09 20:11:54 +00001438}
1439
Chris Lattner113f4f42002-06-25 16:13:24 +00001440Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
Chris Lattnerdcf240a2003-03-10 21:43:22 +00001441 bool Changed = SimplifyCommutative(I);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001442 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1443 const Type *Ty = Op0->getType();
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001444
1445 // setcc X, X
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001446 if (Op0 == Op1)
1447 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner1fc23f32002-05-09 20:11:54 +00001448
Chris Lattnerd07283a2003-08-13 05:38:46 +00001449 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1450 if (isa<ConstantPointerNull>(Op1) &&
1451 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001452 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1453
Chris Lattnerd07283a2003-08-13 05:38:46 +00001454
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001455 // setcc's with boolean values can always be turned into bitwise operations
1456 if (Ty == Type::BoolTy) {
Chris Lattner4456da62004-08-11 00:50:51 +00001457 switch (I.getOpcode()) {
1458 default: assert(0 && "Invalid setcc instruction!");
1459 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001460 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001461 InsertNewInstBefore(Xor, I);
Chris Lattner16930792003-11-03 04:25:02 +00001462 return BinaryOperator::createNot(Xor);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001463 }
Chris Lattner4456da62004-08-11 00:50:51 +00001464 case Instruction::SetNE:
1465 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001466
Chris Lattner4456da62004-08-11 00:50:51 +00001467 case Instruction::SetGT:
1468 std::swap(Op0, Op1); // Change setgt -> setlt
1469 // FALL THROUGH
1470 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1471 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1472 InsertNewInstBefore(Not, I);
1473 return BinaryOperator::createAnd(Not, Op1);
1474 }
1475 case Instruction::SetGE:
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001476 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner4456da62004-08-11 00:50:51 +00001477 // FALL THROUGH
1478 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1479 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1480 InsertNewInstBefore(Not, I);
1481 return BinaryOperator::createOr(Not, Op1);
1482 }
1483 }
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001484 }
1485
Chris Lattner2dd01742004-06-09 04:24:29 +00001486 // See if we are doing a comparison between a constant and an instruction that
1487 // can be folded into the comparison.
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001488 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere1e10e12004-05-25 06:32:08 +00001489 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001490 switch (LHSI->getOpcode()) {
1491 case Instruction::And:
1492 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1493 LHSI->getOperand(0)->hasOneUse()) {
1494 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1495 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1496 // happens a LOT in code produced by the C front-end, for bitfield
1497 // access.
1498 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1499 ConstantUInt *ShAmt;
1500 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1501 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1502 const Type *Ty = LHSI->getType();
1503
1504 // We can fold this as long as we can't shift unknown bits
1505 // into the mask. This can only happen with signed shift
1506 // rights, as they sign-extend.
1507 if (ShAmt) {
1508 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1509 Shift->getType()->isUnsigned();
1510 if (!CanFold) {
1511 // To test for the bad case of the signed shr, see if any
1512 // of the bits shifted in could be tested after the mask.
1513 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
Chris Lattnerd8f5e2c2004-07-21 20:14:10 +00001514 Ty->getPrimitiveSize()*8-ShAmt->getValue());
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001515 Constant *ShVal =
1516 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1517 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1518 CanFold = true;
1519 }
1520
1521 if (CanFold) {
1522 unsigned ShiftOp = Shift->getOpcode() == Instruction::Shl
1523 ? Instruction::Shr : Instruction::Shl;
1524 Constant *NewCst = ConstantExpr::get(ShiftOp, CI, ShAmt);
1525
1526 // Check to see if we are shifting out any of the bits being
1527 // compared.
1528 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1529 // If we shifted bits out, the fold is not going to work out.
1530 // As a special case, check to see if this means that the
1531 // result is always true or false now.
1532 if (I.getOpcode() == Instruction::SetEQ)
1533 return ReplaceInstUsesWith(I, ConstantBool::False);
1534 if (I.getOpcode() == Instruction::SetNE)
1535 return ReplaceInstUsesWith(I, ConstantBool::True);
1536 } else {
1537 I.setOperand(1, NewCst);
1538 LHSI->setOperand(1, ConstantExpr::get(ShiftOp, AndCST,ShAmt));
1539 LHSI->setOperand(0, Shift->getOperand(0));
1540 WorkList.push_back(Shift); // Shift is dead.
1541 AddUsesToWorkList(I);
1542 return &I;
Chris Lattner1638de42004-07-21 19:50:44 +00001543 }
1544 }
Chris Lattner35167c32004-06-09 07:59:58 +00001545 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001546 }
1547 break;
Chris Lattner1023b872004-09-27 16:18:50 +00001548 case Instruction::Shr: // shr: (setcc (shr X, ShAmt), CI)
1549 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
1550 unsigned ShAmtVal = ShAmt->getValue();
1551
1552 switch (I.getOpcode()) {
1553 default: break;
1554 case Instruction::SetEQ:
1555 case Instruction::SetNE: {
1556 // If we are comparing against bits always shifted out, the
1557 // comparison cannot succeed.
1558 Constant *Comp =
1559 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
1560
1561 if (Comp != CI) {// Comparing against a bit that we know is zero.
1562 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
1563 Constant *Cst = ConstantBool::get(IsSetNE);
1564 return ReplaceInstUsesWith(I, Cst);
1565 }
1566
1567 if (LHSI->hasOneUse() || CI->isNullValue()) {
1568 // Otherwise strength reduce the shift into an and.
1569 uint64_t Val = ~0ULL; // All ones.
1570 Val <<= ShAmtVal; // Shift over to the right spot.
1571
1572 Constant *Mask;
1573 if (CI->getType()->isUnsigned()) {
1574 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
1575 Val &= (1ULL << TypeBits)-1;
1576 Mask = ConstantUInt::get(CI->getType(), Val);
1577 } else {
1578 Mask = ConstantSInt::get(CI->getType(), Val);
1579 }
1580
1581 Instruction *AndI =
1582 BinaryOperator::createAnd(LHSI->getOperand(0),
1583 Mask, LHSI->getName()+".mask");
1584 Value *And = InsertNewInstBefore(AndI, I);
1585 return new SetCondInst(I.getOpcode(), And,
1586 ConstantExpr::getShl(CI, ShAmt));
1587 }
1588 break;
1589 }
1590 }
1591 }
1592 break;
Chris Lattner7e794272004-09-24 15:21:34 +00001593
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001594 case Instruction::Div:
1595 if (0 && isa<ConstantInt>(LHSI->getOperand(1))) {
1596 std::cerr << "COULD FOLD: " << *LHSI;
1597 std::cerr << "COULD FOLD: " << I << "\n";
1598 }
1599 break;
1600 case Instruction::Select:
1601 // If either operand of the select is a constant, we can fold the
1602 // comparison into the select arms, which will cause one to be
1603 // constant folded and the select turned into a bitwise or.
1604 Value *Op1 = 0, *Op2 = 0;
1605 if (LHSI->hasOneUse()) {
Chris Lattner35167c32004-06-09 07:59:58 +00001606 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001607 // Fold the known value into the constant operand.
1608 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
1609 // Insert a new SetCC of the other select operand.
1610 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001611 LHSI->getOperand(2), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001612 I.getName()), I);
Chris Lattner35167c32004-06-09 07:59:58 +00001613 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
Chris Lattner2dd01742004-06-09 04:24:29 +00001614 // Fold the known value into the constant operand.
1615 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
1616 // Insert a new SetCC of the other select operand.
1617 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
Chris Lattner35167c32004-06-09 07:59:58 +00001618 LHSI->getOperand(1), CI,
Chris Lattner2dd01742004-06-09 04:24:29 +00001619 I.getName()), I);
1620 }
Chris Lattner2dd01742004-06-09 04:24:29 +00001621 }
Chris Lattnere1b4d2a2004-09-23 21:52:49 +00001622
1623 if (Op1)
1624 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
1625 break;
1626 }
1627
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001628 // Simplify seteq and setne instructions...
1629 if (I.getOpcode() == Instruction::SetEQ ||
1630 I.getOpcode() == Instruction::SetNE) {
1631 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1632
Chris Lattnercfbce7c2003-07-23 17:26:36 +00001633 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001634 // operand is a constant, simplify a bit.
Chris Lattnerc992add2003-08-13 05:33:12 +00001635 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1636 switch (BO->getOpcode()) {
Chris Lattner23b47b62004-07-06 07:38:18 +00001637 case Instruction::Rem:
1638 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
1639 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
1640 BO->hasOneUse() &&
1641 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
1642 if (unsigned L2 =
1643 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
1644 const Type *UTy = BO->getType()->getUnsignedVersion();
1645 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
1646 UTy, "tmp"), I);
1647 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
1648 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
1649 RHSCst, BO->getName()), I);
1650 return BinaryOperator::create(I.getOpcode(), NewRem,
1651 Constant::getNullValue(UTy));
1652 }
1653 break;
1654
Chris Lattnerc992add2003-08-13 05:33:12 +00001655 case Instruction::Add:
Chris Lattner6e079362004-06-27 22:51:36 +00001656 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
1657 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerb121ae12004-09-21 21:35:23 +00001658 if (BO->hasOneUse())
1659 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1660 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner6e079362004-06-27 22:51:36 +00001661 } else if (CI->isNullValue()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001662 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1663 // efficiently invertible, or if the add has just this one use.
1664 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Chris Lattner6e079362004-06-27 22:51:36 +00001665
Chris Lattnerc992add2003-08-13 05:33:12 +00001666 if (Value *NegVal = dyn_castNegVal(BOp1))
1667 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1668 else if (Value *NegVal = dyn_castNegVal(BOp0))
1669 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001670 else if (BO->hasOneUse()) {
Chris Lattnerc992add2003-08-13 05:33:12 +00001671 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1672 BO->setName("");
1673 InsertNewInstBefore(Neg, I);
1674 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1675 }
1676 }
1677 break;
1678 case Instruction::Xor:
1679 // For the xor case, we can xor two constants together, eliminating
1680 // the explicit xor.
1681 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1682 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001683 ConstantExpr::getXor(CI, BOC));
Chris Lattnerc992add2003-08-13 05:33:12 +00001684
1685 // FALLTHROUGH
1686 case Instruction::Sub:
1687 // Replace (([sub|xor] A, B) != 0) with (A != B)
1688 if (CI->isNullValue())
1689 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1690 BO->getOperand(1));
1691 break;
1692
1693 case Instruction::Or:
1694 // If bits are being or'd in that are not present in the constant we
1695 // are comparing against, then the comparison could never succeed!
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001696 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001697 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001698 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001699 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00001700 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001701 break;
1702
1703 case Instruction::And:
1704 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001705 // If bits are being compared against that are and'd out, then the
1706 // comparison can never succeed!
Chris Lattnerc8e7e292004-06-10 02:12:35 +00001707 if (!ConstantExpr::getAnd(CI,
1708 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001709 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattnerc992add2003-08-13 05:33:12 +00001710
Chris Lattner35167c32004-06-09 07:59:58 +00001711 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattneree59d4b2004-06-10 02:33:20 +00001712 if (CI == BOC && isOneBitSet(CI))
Chris Lattner35167c32004-06-09 07:59:58 +00001713 return new SetCondInst(isSetNE ? Instruction::SetEQ :
1714 Instruction::SetNE, Op0,
1715 Constant::getNullValue(CI->getType()));
Chris Lattner35167c32004-06-09 07:59:58 +00001716
Chris Lattnerc992add2003-08-13 05:33:12 +00001717 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1718 // to be a signed value as appropriate.
1719 if (isSignBit(BOC)) {
1720 Value *X = BO->getOperand(0);
1721 // If 'X' is not signed, insert a cast now...
1722 if (!BOC->getType()->isSigned()) {
Chris Lattner97bfcea2004-06-17 18:16:02 +00001723 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattnerc992add2003-08-13 05:33:12 +00001724 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1725 InsertNewInstBefore(NewCI, I);
1726 X = NewCI;
1727 }
1728 return new SetCondInst(isSetNE ? Instruction::SetLT :
1729 Instruction::SetGE, X,
1730 Constant::getNullValue(X->getType()));
1731 }
Chris Lattner8fc5af42004-09-23 21:46:38 +00001732
1733 // ((X & ~7) == 0) --> X < 7
1734 if (CI->isNullValue() && isHighOnes(BOC)) {
1735 Value *X = BO->getOperand(0);
1736 Constant *NotX = ConstantExpr::getNot(BOC);
1737
1738 // If 'X' is signed, insert a cast now.
1739 if (!NotX->getType()->isSigned()) {
1740 const Type *DestTy = NotX->getType()->getUnsignedVersion();
1741 CastInst *NewCI = new CastInst(X, DestTy, X->getName()+".uns");
1742 InsertNewInstBefore(NewCI, I);
1743 X = NewCI;
1744 NotX = ConstantExpr::getCast(NotX, DestTy);
1745 }
1746
1747 return new SetCondInst(isSetNE ? Instruction::SetGE :
1748 Instruction::SetLT, X, NotX);
1749 }
1750
Chris Lattnerd492a0b2003-07-23 17:02:11 +00001751 }
Chris Lattnerc992add2003-08-13 05:33:12 +00001752 default: break;
1753 }
1754 }
Chris Lattner2b55ea32004-02-23 07:16:20 +00001755 } else { // Not a SetEQ/SetNE
1756 // If the LHS is a cast from an integral value of the same size,
1757 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
1758 Value *CastOp = Cast->getOperand(0);
1759 const Type *SrcTy = CastOp->getType();
1760 unsigned SrcTySize = SrcTy->getPrimitiveSize();
1761 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
1762 SrcTySize == Cast->getType()->getPrimitiveSize()) {
1763 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
1764 "Source and destination signednesses should differ!");
1765 if (Cast->getType()->isSigned()) {
1766 // If this is a signed comparison, check for comparisons in the
1767 // vicinity of zero.
1768 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
1769 // X < 0 => x > 127
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001770 return BinaryOperator::createSetGT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001771 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
1772 else if (I.getOpcode() == Instruction::SetGT &&
1773 cast<ConstantSInt>(CI)->getValue() == -1)
1774 // X > -1 => x < 128
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001775 return BinaryOperator::createSetLT(CastOp,
Chris Lattner2b55ea32004-02-23 07:16:20 +00001776 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
1777 } else {
1778 ConstantUInt *CUI = cast<ConstantUInt>(CI);
1779 if (I.getOpcode() == Instruction::SetLT &&
1780 CUI->getValue() == 1ULL << (SrcTySize*8-1))
1781 // X < 128 => X > -1
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001782 return BinaryOperator::createSetGT(CastOp,
1783 ConstantSInt::get(SrcTy, -1));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001784 else if (I.getOpcode() == Instruction::SetGT &&
1785 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
1786 // X > 127 => X < 0
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001787 return BinaryOperator::createSetLT(CastOp,
1788 Constant::getNullValue(SrcTy));
Chris Lattner2b55ea32004-02-23 07:16:20 +00001789 }
1790 }
1791 }
Chris Lattnere967b342003-06-04 05:10:11 +00001792 }
Chris Lattner791ac1a2003-06-01 03:35:25 +00001793
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001794 // Check to see if we are comparing against the minimum or maximum value...
Chris Lattnere6794492002-08-12 21:17:25 +00001795 if (CI->isMinValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001796 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1797 return ReplaceInstUsesWith(I, ConstantBool::False);
1798 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1799 return ReplaceInstUsesWith(I, ConstantBool::True);
1800 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001801 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001802 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001803 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001804
Chris Lattnere6794492002-08-12 21:17:25 +00001805 } else if (CI->isMaxValue()) {
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001806 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1807 return ReplaceInstUsesWith(I, ConstantBool::False);
1808 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1809 return ReplaceInstUsesWith(I, ConstantBool::True);
1810 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001811 return BinaryOperator::createSetEQ(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001812 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001813 return BinaryOperator::createSetNE(Op0, Op1);
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001814
1815 // Comparing against a value really close to min or max?
1816 } else if (isMinValuePlusOne(CI)) {
1817 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001818 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001819 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001820 return BinaryOperator::createSetNE(Op0, SubOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001821
1822 } else if (isMaxValueMinusOne(CI)) {
1823 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001824 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001825 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001826 return BinaryOperator::createSetNE(Op0, AddOne(CI));
Chris Lattner6d14f2a2002-08-09 23:47:40 +00001827 }
Chris Lattner59611142004-02-23 05:47:48 +00001828
1829 // If we still have a setle or setge instruction, turn it into the
1830 // appropriate setlt or setgt instruction. Since the border cases have
1831 // already been handled above, this requires little checking.
1832 //
1833 if (I.getOpcode() == Instruction::SetLE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001834 return BinaryOperator::createSetLT(Op0, AddOne(CI));
Chris Lattner59611142004-02-23 05:47:48 +00001835 if (I.getOpcode() == Instruction::SetGE)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001836 return BinaryOperator::createSetGT(Op0, SubOne(CI));
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001837 }
1838
Chris Lattner16930792003-11-03 04:25:02 +00001839 // Test to see if the operands of the setcc are casted versions of other
1840 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner6444c372003-11-03 05:17:03 +00001841 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1842 Value *CastOp0 = CI->getOperand(0);
1843 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner7d2a5392004-03-13 23:54:27 +00001844 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattner16930792003-11-03 04:25:02 +00001845 (I.getOpcode() == Instruction::SetEQ ||
1846 I.getOpcode() == Instruction::SetNE)) {
1847 // We keep moving the cast from the left operand over to the right
1848 // operand, where it can often be eliminated completely.
Chris Lattner6444c372003-11-03 05:17:03 +00001849 Op0 = CastOp0;
Chris Lattner16930792003-11-03 04:25:02 +00001850
1851 // If operand #1 is a cast instruction, see if we can eliminate it as
1852 // well.
Chris Lattner6444c372003-11-03 05:17:03 +00001853 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
1854 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattner16930792003-11-03 04:25:02 +00001855 Op0->getType()))
Chris Lattner6444c372003-11-03 05:17:03 +00001856 Op1 = CI2->getOperand(0);
Chris Lattner16930792003-11-03 04:25:02 +00001857
1858 // If Op1 is a constant, we can fold the cast into the constant.
1859 if (Op1->getType() != Op0->getType())
1860 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
1861 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
1862 } else {
1863 // Otherwise, cast the RHS right before the setcc
1864 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
1865 InsertNewInstBefore(cast<Instruction>(Op1), I);
1866 }
1867 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
1868 }
1869
Chris Lattner6444c372003-11-03 05:17:03 +00001870 // Handle the special case of: setcc (cast bool to X), <cst>
1871 // This comes up when you have code like
1872 // int X = A < B;
1873 // if (X) ...
1874 // For generality, we handle any zero-extension of any operand comparison
1875 // with a constant.
1876 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
1877 const Type *SrcTy = CastOp0->getType();
1878 const Type *DestTy = Op0->getType();
1879 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
1880 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
1881 // Ok, we have an expansion of operand 0 into a new type. Get the
1882 // constant value, masink off bits which are not set in the RHS. These
1883 // could be set if the destination value is signed.
1884 uint64_t ConstVal = ConstantRHS->getRawValue();
1885 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
1886
1887 // If the constant we are comparing it with has high bits set, which
1888 // don't exist in the original value, the values could never be equal,
1889 // because the source would be zero extended.
1890 unsigned SrcBits =
1891 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
Chris Lattner7c94d112003-11-05 17:31:36 +00001892 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
1893 if (ConstVal & ~((1ULL << SrcBits)-1)) {
Chris Lattner6444c372003-11-03 05:17:03 +00001894 switch (I.getOpcode()) {
1895 default: assert(0 && "Unknown comparison type!");
1896 case Instruction::SetEQ:
1897 return ReplaceInstUsesWith(I, ConstantBool::False);
1898 case Instruction::SetNE:
1899 return ReplaceInstUsesWith(I, ConstantBool::True);
1900 case Instruction::SetLT:
1901 case Instruction::SetLE:
1902 if (DestTy->isSigned() && HasSignBit)
1903 return ReplaceInstUsesWith(I, ConstantBool::False);
1904 return ReplaceInstUsesWith(I, ConstantBool::True);
1905 case Instruction::SetGT:
1906 case Instruction::SetGE:
1907 if (DestTy->isSigned() && HasSignBit)
1908 return ReplaceInstUsesWith(I, ConstantBool::True);
1909 return ReplaceInstUsesWith(I, ConstantBool::False);
1910 }
1911 }
1912
1913 // Otherwise, we can replace the setcc with a setcc of the smaller
1914 // operand value.
1915 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
1916 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
1917 }
1918 }
1919 }
Chris Lattner113f4f42002-06-25 16:13:24 +00001920 return Changed ? &I : 0;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001921}
1922
1923
1924
Chris Lattnere8d6c602003-03-10 19:16:08 +00001925Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner113f4f42002-06-25 16:13:24 +00001926 assert(I.getOperand(1)->getType() == Type::UByteTy);
1927 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001928 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001929
1930 // shl X, 0 == X and shr X, 0 == X
1931 // shl 0, X == 0 and shr 0, X == 0
1932 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattnere6794492002-08-12 21:17:25 +00001933 Op0 == Constant::getNullValue(Op0->getType()))
1934 return ReplaceInstUsesWith(I, Op0);
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001935
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001936 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1937 if (!isLeftShift)
1938 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1939 if (CSI->isAllOnesValue())
1940 return ReplaceInstUsesWith(I, CSI);
1941
Chris Lattner183b3362004-04-09 19:05:30 +00001942 // Try to fold constant and into select arguments.
1943 if (isa<Constant>(Op0))
1944 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1945 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1946 return R;
1947
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00001948 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00001949 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1950 // of a signed value.
1951 //
Chris Lattnere8d6c602003-03-10 19:16:08 +00001952 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
Chris Lattnerf5ce2542004-02-23 20:30:06 +00001953 if (CUI->getValue() >= TypeBits) {
1954 if (!Op0->getType()->isSigned() || isLeftShift)
1955 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1956 else {
1957 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
1958 return &I;
1959 }
1960 }
Chris Lattner55f3d942002-09-10 23:04:09 +00001961
Chris Lattnerede3fe02003-08-13 04:18:28 +00001962 // ((X*C1) << C2) == (X * (C1 << C2))
1963 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1964 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1965 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00001966 return BinaryOperator::createMul(BO->getOperand(0),
1967 ConstantExpr::getShl(BOOp, CUI));
Chris Lattnerede3fe02003-08-13 04:18:28 +00001968
Chris Lattner183b3362004-04-09 19:05:30 +00001969 // Try to fold constant and into select arguments.
1970 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1971 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1972 return R;
Chris Lattnerede3fe02003-08-13 04:18:28 +00001973
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001974 // If the operand is an bitwise operator with a constant RHS, and the
1975 // shift is the only use, we can pull it out of the shift.
Chris Lattnerf95d9b92003-10-15 16:48:29 +00001976 if (Op0->hasOneUse())
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00001977 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1978 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1979 bool isValid = true; // Valid only for And, Or, Xor
1980 bool highBitSet = false; // Transform if high bit of constant set?
1981
1982 switch (Op0BO->getOpcode()) {
1983 default: isValid = false; break; // Do not perform transform!
1984 case Instruction::Or:
1985 case Instruction::Xor:
1986 highBitSet = false;
1987 break;
1988 case Instruction::And:
1989 highBitSet = true;
1990 break;
1991 }
1992
1993 // If this is a signed shift right, and the high bit is modified
1994 // by the logical operation, do not perform the transformation.
1995 // The highBitSet boolean indicates the value of the high bit of
1996 // the constant which would cause it to be modified for this
1997 // operation.
1998 //
1999 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2000 uint64_t Val = Op0C->getRawValue();
2001 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2002 }
2003
2004 if (isValid) {
Chris Lattnerc1e7cc02004-01-12 19:35:11 +00002005 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002006
2007 Instruction *NewShift =
2008 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2009 Op0BO->getName());
2010 Op0BO->setName("");
2011 InsertNewInstBefore(NewShift, I);
2012
2013 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2014 NewRHS);
2015 }
2016 }
2017
Chris Lattner3204d4e2003-07-24 17:52:58 +00002018 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002019 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerab780df2003-07-24 18:38:56 +00002020 if (ConstantUInt *ShiftAmt1C =
2021 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002022 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2023 unsigned ShiftAmt2 = CUI->getValue();
2024
2025 // Check for (A << c1) << c2 and (A >> c1) >> c2
2026 if (I.getOpcode() == Op0SI->getOpcode()) {
2027 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattnerf5ce2542004-02-23 20:30:06 +00002028 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2029 Amt = Op0->getType()->getPrimitiveSize()*8;
Chris Lattner3204d4e2003-07-24 17:52:58 +00002030 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2031 ConstantUInt::get(Type::UByteTy, Amt));
2032 }
2033
Chris Lattnerab780df2003-07-24 18:38:56 +00002034 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2035 // signed types, we can only support the (A >> c1) << c2 configuration,
2036 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002037 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner3204d4e2003-07-24 17:52:58 +00002038 // Calculate bitmask for what gets shifted off the edge...
2039 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002040 if (isLeftShift)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002041 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdeaa0dd2003-08-12 21:53:41 +00002042 else
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002043 C = ConstantExpr::getShr(C, ShiftAmt1C);
Chris Lattner3204d4e2003-07-24 17:52:58 +00002044
2045 Instruction *Mask =
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002046 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2047 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner3204d4e2003-07-24 17:52:58 +00002048 InsertNewInstBefore(Mask, I);
2049
2050 // Figure out what flavor of shift we should use...
2051 if (ShiftAmt1 == ShiftAmt2)
2052 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2053 else if (ShiftAmt1 < ShiftAmt2) {
2054 return new ShiftInst(I.getOpcode(), Mask,
2055 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2056 } else {
2057 return new ShiftInst(Op0SI->getOpcode(), Mask,
2058 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2059 }
2060 }
2061 }
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002062 }
Chris Lattner2e0fb392002-10-08 16:16:40 +00002063
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002064 return 0;
2065}
2066
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002067enum CastType {
2068 Noop = 0,
2069 Truncate = 1,
2070 Signext = 2,
2071 Zeroext = 3
2072};
2073
2074/// getCastType - In the future, we will split the cast instruction into these
2075/// various types. Until then, we have to do the analysis here.
2076static CastType getCastType(const Type *Src, const Type *Dest) {
2077 assert(Src->isIntegral() && Dest->isIntegral() &&
2078 "Only works on integral types!");
2079 unsigned SrcSize = Src->getPrimitiveSize()*8;
2080 if (Src == Type::BoolTy) SrcSize = 1;
2081 unsigned DestSize = Dest->getPrimitiveSize()*8;
2082 if (Dest == Type::BoolTy) DestSize = 1;
2083
2084 if (SrcSize == DestSize) return Noop;
2085 if (SrcSize > DestSize) return Truncate;
2086 if (Src->isSigned()) return Signext;
2087 return Zeroext;
2088}
2089
Chris Lattnerf4cdbf32002-05-06 16:14:14 +00002090
Chris Lattner48a44f72002-05-02 17:06:02 +00002091// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2092// instruction.
2093//
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002094static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner11ffd592004-07-20 05:21:00 +00002095 const Type *DstTy, TargetData *TD) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002096
Chris Lattner650b6da2002-08-02 20:00:25 +00002097 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2098 // are identical and the bits don't get reinterpreted (for example
Chris Lattner1638de42004-07-21 19:50:44 +00002099 // int->float->int would not be allowed).
Misha Brukmane5838c42003-05-20 18:45:36 +00002100 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner650b6da2002-08-02 20:00:25 +00002101 return true;
Chris Lattner48a44f72002-05-02 17:06:02 +00002102
Chris Lattner4fbad962004-07-21 04:27:24 +00002103 // If we are casting between pointer and integer types, treat pointers as
2104 // integers of the appropriate size for the code below.
2105 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2106 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2107 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner11ffd592004-07-20 05:21:00 +00002108
Chris Lattner48a44f72002-05-02 17:06:02 +00002109 // Allow free casting and conversion of sizes as long as the sign doesn't
2110 // change...
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002111 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002112 CastType FirstCast = getCastType(SrcTy, MidTy);
2113 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner650b6da2002-08-02 20:00:25 +00002114
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002115 // Capture the effect of these two casts. If the result is a legal cast,
2116 // the CastType is stored here, otherwise a special code is used.
2117 static const unsigned CastResult[] = {
2118 // First cast is noop
2119 0, 1, 2, 3,
2120 // First cast is a truncate
2121 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2122 // First cast is a sign ext
Chris Lattner1638de42004-07-21 19:50:44 +00002123 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002124 // First cast is a zero ext
Chris Lattner1638de42004-07-21 19:50:44 +00002125 3, 5, 3, 3,
Chris Lattner4e2dbc62004-07-20 00:59:32 +00002126 };
2127
2128 unsigned Result = CastResult[FirstCast*4+SecondCast];
2129 switch (Result) {
2130 default: assert(0 && "Illegal table value!");
2131 case 0:
2132 case 1:
2133 case 2:
2134 case 3:
2135 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2136 // truncates, we could eliminate more casts.
2137 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2138 case 4:
2139 return false; // Not possible to eliminate this here.
2140 case 5:
Chris Lattner1638de42004-07-21 19:50:44 +00002141 // Sign or zero extend followed by truncate is always ok if the result
2142 // is a truncate or noop.
2143 CastType ResultCast = getCastType(SrcTy, DstTy);
2144 if (ResultCast == Noop || ResultCast == Truncate)
2145 return true;
2146 // Otherwise we are still growing the value, we are only safe if the
2147 // result will match the sign/zeroextendness of the result.
2148 return ResultCast == FirstCast;
Chris Lattner3732aca2002-08-15 16:15:25 +00002149 }
Chris Lattner650b6da2002-08-02 20:00:25 +00002150 }
Chris Lattner48a44f72002-05-02 17:06:02 +00002151 return false;
2152}
2153
Chris Lattner11ffd592004-07-20 05:21:00 +00002154static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002155 if (V->getType() == Ty || isa<Constant>(V)) return false;
2156 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner11ffd592004-07-20 05:21:00 +00002157 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2158 TD))
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002159 return false;
2160 return true;
2161}
2162
2163/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2164/// InsertBefore instruction. This is specialized a bit to avoid inserting
2165/// casts that are known to not do anything...
2166///
2167Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2168 Instruction *InsertBefore) {
2169 if (V->getType() == DestTy) return V;
2170 if (Constant *C = dyn_cast<Constant>(V))
2171 return ConstantExpr::getCast(C, DestTy);
2172
2173 CastInst *CI = new CastInst(V, DestTy, V->getName());
2174 InsertNewInstBefore(CI, *InsertBefore);
2175 return CI;
2176}
Chris Lattner48a44f72002-05-02 17:06:02 +00002177
2178// CastInst simplification
Chris Lattner260ab202002-04-18 17:39:14 +00002179//
Chris Lattner113f4f42002-06-25 16:13:24 +00002180Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner55d4bda2003-06-23 21:59:52 +00002181 Value *Src = CI.getOperand(0);
2182
Chris Lattner48a44f72002-05-02 17:06:02 +00002183 // If the user is casting a value to the same type, eliminate this cast
2184 // instruction...
Chris Lattner55d4bda2003-06-23 21:59:52 +00002185 if (CI.getType() == Src->getType())
2186 return ReplaceInstUsesWith(CI, Src);
Chris Lattner48a44f72002-05-02 17:06:02 +00002187
Chris Lattner48a44f72002-05-02 17:06:02 +00002188 // If casting the result of another cast instruction, try to eliminate this
2189 // one!
2190 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002191 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002192 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
Chris Lattner11ffd592004-07-20 05:21:00 +00002193 CSrc->getType(), CI.getType(), TD)) {
Chris Lattner48a44f72002-05-02 17:06:02 +00002194 // This instruction now refers directly to the cast's src operand. This
2195 // has a good chance of making CSrc dead.
Chris Lattner113f4f42002-06-25 16:13:24 +00002196 CI.setOperand(0, CSrc->getOperand(0));
2197 return &CI;
Chris Lattner48a44f72002-05-02 17:06:02 +00002198 }
2199
Chris Lattner650b6da2002-08-02 20:00:25 +00002200 // If this is an A->B->A cast, and we are dealing with integral types, try
2201 // to convert this into a logical 'and' instruction.
2202 //
2203 if (CSrc->getOperand(0)->getType() == CI.getType() &&
Chris Lattnerb0b412e2002-09-03 01:08:28 +00002204 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner650b6da2002-08-02 20:00:25 +00002205 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2206 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2207 assert(CSrc->getType() != Type::ULongTy &&
2208 "Cannot have type bigger than ulong!");
Chris Lattner196897c2003-05-26 23:41:32 +00002209 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
Chris Lattner650b6da2002-08-02 20:00:25 +00002210 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002211 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
Chris Lattner650b6da2002-08-02 20:00:25 +00002212 }
2213 }
2214
Chris Lattner03841652004-05-25 04:29:21 +00002215 // If this is a cast to bool, turn it into the appropriate setne instruction.
2216 if (CI.getType() == Type::BoolTy)
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002217 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattner03841652004-05-25 04:29:21 +00002218 Constant::getNullValue(CI.getOperand(0)->getType()));
2219
Chris Lattnerd0d51602003-06-21 23:12:02 +00002220 // If casting the result of a getelementptr instruction with no offset, turn
2221 // this into a cast of the original pointer!
2222 //
Chris Lattner55d4bda2003-06-23 21:59:52 +00002223 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattnerd0d51602003-06-21 23:12:02 +00002224 bool AllZeroOperands = true;
2225 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2226 if (!isa<Constant>(GEP->getOperand(i)) ||
2227 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2228 AllZeroOperands = false;
2229 break;
2230 }
2231 if (AllZeroOperands) {
2232 CI.setOperand(0, GEP->getOperand(0));
2233 return &CI;
2234 }
2235 }
2236
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002237 // If we are casting a malloc or alloca to a pointer to a type of the same
2238 // size, rewrite the allocation instruction to allocate the "right" type.
2239 //
2240 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerd4d987d2003-11-02 06:54:48 +00002241 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002242 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2243 // Get the type really allocated and the type casted to...
2244 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002245 const Type *CastElTy = PTy->getElementType();
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002246 if (AllocElTy->isSized() && CastElTy->isSized()) {
2247 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2248 unsigned CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner7c94d112003-11-05 17:31:36 +00002249
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002250 // If the allocation is for an even multiple of the cast type size
2251 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2252 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002253 AllocElTySize/CastElTySize);
Chris Lattner9eb9ccd2004-07-06 19:28:42 +00002254 std::string Name = AI->getName(); AI->setName("");
2255 AllocationInst *New;
2256 if (isa<MallocInst>(AI))
2257 New = new MallocInst(CastElTy, Amt, Name);
2258 else
2259 New = new AllocaInst(CastElTy, Amt, Name);
2260 InsertNewInstBefore(New, *AI);
2261 return ReplaceInstUsesWith(CI, New);
2262 }
Chris Lattnerf4ad1652003-11-02 05:57:39 +00002263 }
2264 }
2265
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002266 // If the source value is an instruction with only this use, we can attempt to
2267 // propagate the cast into the instruction. Also, only handle integral types
2268 // for now.
2269 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerf95d9b92003-10-15 16:48:29 +00002270 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002271 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2272 const Type *DestTy = CI.getType();
2273 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2274 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2275
2276 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2277 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2278
2279 switch (SrcI->getOpcode()) {
2280 case Instruction::Add:
2281 case Instruction::Mul:
2282 case Instruction::And:
2283 case Instruction::Or:
2284 case Instruction::Xor:
2285 // If we are discarding information, or just changing the sign, rewrite.
2286 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2287 // Don't insert two casts if they cannot be eliminated. We allow two
2288 // casts to be inserted if the sizes are the same. This could only be
2289 // converting signedness, which is a noop.
Chris Lattner11ffd592004-07-20 05:21:00 +00002290 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2291 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattnerdfae8be2003-07-24 17:35:25 +00002292 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2293 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2294 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2295 ->getOpcode(), Op0c, Op1c);
2296 }
2297 }
2298 break;
2299 case Instruction::Shl:
2300 // Allow changing the sign of the source operand. Do not allow changing
2301 // the size of the shift, UNLESS the shift amount is a constant. We
2302 // mush not change variable sized shifts to a smaller size, because it
2303 // is undefined to shift more bits out than exist in the value.
2304 if (DestBitSize == SrcBitSize ||
2305 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2306 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2307 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2308 }
2309 break;
2310 }
2311 }
2312
Chris Lattner260ab202002-04-18 17:39:14 +00002313 return 0;
Chris Lattnerca081252001-12-14 16:52:21 +00002314}
2315
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002316/// GetSelectFoldableOperands - We want to turn code that looks like this:
2317/// %C = or %A, %B
2318/// %D = select %cond, %C, %A
2319/// into:
2320/// %C = select %cond, %B, 0
2321/// %D = or %A, %C
2322///
2323/// Assuming that the specified instruction is an operand to the select, return
2324/// a bitmask indicating which operands of this instruction are foldable if they
2325/// equal the other incoming value of the select.
2326///
2327static unsigned GetSelectFoldableOperands(Instruction *I) {
2328 switch (I->getOpcode()) {
2329 case Instruction::Add:
2330 case Instruction::Mul:
2331 case Instruction::And:
2332 case Instruction::Or:
2333 case Instruction::Xor:
2334 return 3; // Can fold through either operand.
2335 case Instruction::Sub: // Can only fold on the amount subtracted.
2336 case Instruction::Shl: // Can only fold on the shift amount.
2337 case Instruction::Shr:
2338 return 1;
2339 default:
2340 return 0; // Cannot fold
2341 }
2342}
2343
2344/// GetSelectFoldableConstant - For the same transformation as the previous
2345/// function, return the identity constant that goes into the select.
2346static Constant *GetSelectFoldableConstant(Instruction *I) {
2347 switch (I->getOpcode()) {
2348 default: assert(0 && "This cannot happen!"); abort();
2349 case Instruction::Add:
2350 case Instruction::Sub:
2351 case Instruction::Or:
2352 case Instruction::Xor:
2353 return Constant::getNullValue(I->getType());
2354 case Instruction::Shl:
2355 case Instruction::Shr:
2356 return Constant::getNullValue(Type::UByteTy);
2357 case Instruction::And:
2358 return ConstantInt::getAllOnesValue(I->getType());
2359 case Instruction::Mul:
2360 return ConstantInt::get(I->getType(), 1);
2361 }
2362}
2363
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002364Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattner533bc492004-03-30 19:37:13 +00002365 Value *CondVal = SI.getCondition();
2366 Value *TrueVal = SI.getTrueValue();
2367 Value *FalseVal = SI.getFalseValue();
2368
2369 // select true, X, Y -> X
2370 // select false, X, Y -> Y
2371 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002372 if (C == ConstantBool::True)
Chris Lattner533bc492004-03-30 19:37:13 +00002373 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002374 else {
2375 assert(C == ConstantBool::False);
Chris Lattner533bc492004-03-30 19:37:13 +00002376 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002377 }
Chris Lattner533bc492004-03-30 19:37:13 +00002378
2379 // select C, X, X -> X
2380 if (TrueVal == FalseVal)
2381 return ReplaceInstUsesWith(SI, TrueVal);
2382
Chris Lattner1c631e82004-04-08 04:43:23 +00002383 if (SI.getType() == Type::BoolTy)
2384 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2385 if (C == ConstantBool::True) {
2386 // Change: A = select B, true, C --> A = or B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002387 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002388 } else {
2389 // Change: A = select B, false, C --> A = and !B, C
2390 Value *NotCond =
2391 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2392 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002393 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002394 }
2395 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2396 if (C == ConstantBool::False) {
2397 // Change: A = select B, C, false --> A = and B, C
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002398 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002399 } else {
2400 // Change: A = select B, C, true --> A = or !B, C
2401 Value *NotCond =
2402 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2403 "not."+CondVal->getName()), SI);
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002404 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner1c631e82004-04-08 04:43:23 +00002405 }
2406 }
2407
Chris Lattner183b3362004-04-09 19:05:30 +00002408 // Selecting between two integer constants?
2409 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2410 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2411 // select C, 1, 0 -> cast C to int
2412 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2413 return new CastInst(CondVal, SI.getType());
2414 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2415 // select C, 0, 1 -> cast !C to int
2416 Value *NotCond =
2417 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattnercf7baf32004-04-09 18:19:44 +00002418 "not."+CondVal->getName()), SI);
Chris Lattner183b3362004-04-09 19:05:30 +00002419 return new CastInst(NotCond, SI.getType());
Chris Lattnercf7baf32004-04-09 18:19:44 +00002420 }
Chris Lattner35167c32004-06-09 07:59:58 +00002421
2422 // If one of the constants is zero (we know they can't both be) and we
2423 // have a setcc instruction with zero, and we have an 'and' with the
2424 // non-constant value, eliminate this whole mess. This corresponds to
2425 // cases like this: ((X & 27) ? 27 : 0)
2426 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2427 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2428 if ((IC->getOpcode() == Instruction::SetEQ ||
2429 IC->getOpcode() == Instruction::SetNE) &&
2430 isa<ConstantInt>(IC->getOperand(1)) &&
2431 cast<Constant>(IC->getOperand(1))->isNullValue())
2432 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2433 if (ICA->getOpcode() == Instruction::And &&
2434 isa<ConstantInt>(ICA->getOperand(1)) &&
2435 (ICA->getOperand(1) == TrueValC ||
2436 ICA->getOperand(1) == FalseValC) &&
2437 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2438 // Okay, now we know that everything is set up, we just don't
2439 // know whether we have a setne or seteq and whether the true or
2440 // false val is the zero.
2441 bool ShouldNotVal = !TrueValC->isNullValue();
2442 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2443 Value *V = ICA;
2444 if (ShouldNotVal)
2445 V = InsertNewInstBefore(BinaryOperator::create(
2446 Instruction::Xor, V, ICA->getOperand(1)), SI);
2447 return ReplaceInstUsesWith(SI, V);
2448 }
Chris Lattner533bc492004-03-30 19:37:13 +00002449 }
Chris Lattner623fba12004-04-10 22:21:27 +00002450
2451 // See if we are selecting two values based on a comparison of the two values.
2452 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2453 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2454 // Transform (X == Y) ? X : Y -> Y
2455 if (SCI->getOpcode() == Instruction::SetEQ)
2456 return ReplaceInstUsesWith(SI, FalseVal);
2457 // Transform (X != Y) ? X : Y -> X
2458 if (SCI->getOpcode() == Instruction::SetNE)
2459 return ReplaceInstUsesWith(SI, TrueVal);
2460 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2461
2462 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2463 // Transform (X == Y) ? Y : X -> X
2464 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattner24cf0202004-04-11 01:39:19 +00002465 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002466 // Transform (X != Y) ? Y : X -> Y
2467 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattner24cf0202004-04-11 01:39:19 +00002468 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner623fba12004-04-10 22:21:27 +00002469 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2470 }
2471 }
Chris Lattner1c631e82004-04-08 04:43:23 +00002472
Chris Lattner56e4d3d2004-04-09 23:46:01 +00002473 // See if we can fold the select into one of our operands.
2474 if (SI.getType()->isInteger()) {
2475 // See the comment above GetSelectFoldableOperands for a description of the
2476 // transformation we are doing here.
2477 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
2478 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2479 !isa<Constant>(FalseVal))
2480 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2481 unsigned OpToFold = 0;
2482 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2483 OpToFold = 1;
2484 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2485 OpToFold = 2;
2486 }
2487
2488 if (OpToFold) {
2489 Constant *C = GetSelectFoldableConstant(TVI);
2490 std::string Name = TVI->getName(); TVI->setName("");
2491 Instruction *NewSel =
2492 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
2493 Name);
2494 InsertNewInstBefore(NewSel, SI);
2495 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2496 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
2497 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
2498 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
2499 else {
2500 assert(0 && "Unknown instruction!!");
2501 }
2502 }
2503 }
2504
2505 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
2506 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2507 !isa<Constant>(TrueVal))
2508 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2509 unsigned OpToFold = 0;
2510 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2511 OpToFold = 1;
2512 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2513 OpToFold = 2;
2514 }
2515
2516 if (OpToFold) {
2517 Constant *C = GetSelectFoldableConstant(FVI);
2518 std::string Name = FVI->getName(); FVI->setName("");
2519 Instruction *NewSel =
2520 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
2521 Name);
2522 InsertNewInstBefore(NewSel, SI);
2523 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2524 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
2525 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
2526 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
2527 else {
2528 assert(0 && "Unknown instruction!!");
2529 }
2530 }
2531 }
2532 }
Chris Lattnerb909e8b2004-03-12 05:52:32 +00002533 return 0;
2534}
2535
2536
Chris Lattner970c33a2003-06-19 17:00:31 +00002537// CallInst simplification
2538//
2539Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner51ea1272004-02-28 05:22:00 +00002540 // Intrinsics cannot occur in an invoke, so handle them here instead of in
2541 // visitCallSite.
2542 if (Function *F = CI.getCalledFunction())
2543 switch (F->getIntrinsicID()) {
2544 case Intrinsic::memmove:
2545 case Intrinsic::memcpy:
2546 case Intrinsic::memset:
2547 // memmove/cpy/set of zero bytes is a noop.
2548 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
2549 if (NumBytes->isNullValue())
2550 return EraseInstFromFunction(CI);
2551 }
2552 break;
2553 default:
2554 break;
2555 }
2556
Chris Lattneraec3d942003-10-07 22:32:43 +00002557 return visitCallSite(&CI);
Chris Lattner970c33a2003-06-19 17:00:31 +00002558}
2559
2560// InvokeInst simplification
2561//
2562Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattneraec3d942003-10-07 22:32:43 +00002563 return visitCallSite(&II);
Chris Lattner970c33a2003-06-19 17:00:31 +00002564}
2565
Chris Lattneraec3d942003-10-07 22:32:43 +00002566// visitCallSite - Improvements for call and invoke instructions.
2567//
2568Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002569 bool Changed = false;
2570
2571 // If the callee is a constexpr cast of a function, attempt to move the cast
2572 // to the arguments of the call/invoke.
Chris Lattneraec3d942003-10-07 22:32:43 +00002573 if (transformConstExprCastCall(CS)) return 0;
2574
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002575 Value *Callee = CS.getCalledValue();
2576 const PointerType *PTy = cast<PointerType>(Callee->getType());
2577 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2578 if (FTy->isVarArg()) {
2579 // See if we can optimize any arguments passed through the varargs area of
2580 // the call.
2581 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
2582 E = CS.arg_end(); I != E; ++I)
2583 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
2584 // If this cast does not effect the value passed through the varargs
2585 // area, we can eliminate the use of the cast.
2586 Value *Op = CI->getOperand(0);
2587 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
2588 *I = Op;
2589 Changed = true;
2590 }
2591 }
2592 }
Chris Lattneraec3d942003-10-07 22:32:43 +00002593
Chris Lattner75b4d1d2003-10-07 22:54:13 +00002594 return Changed ? CS.getInstruction() : 0;
Chris Lattneraec3d942003-10-07 22:32:43 +00002595}
2596
Chris Lattner970c33a2003-06-19 17:00:31 +00002597// transformConstExprCastCall - If the callee is a constexpr cast of a function,
2598// attempt to move the cast to the arguments of the call/invoke.
2599//
2600bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2601 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
2602 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattnerf3edc492004-07-18 18:59:44 +00002603 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner970c33a2003-06-19 17:00:31 +00002604 return false;
Reid Spencer87436872004-07-18 00:38:32 +00002605 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner970c33a2003-06-19 17:00:31 +00002606 Instruction *Caller = CS.getInstruction();
2607
2608 // Okay, this is a cast from a function to a different type. Unless doing so
2609 // would cause a type conversion of one of our arguments, change this call to
2610 // be a direct call with arguments casted to the appropriate types.
2611 //
2612 const FunctionType *FT = Callee->getFunctionType();
2613 const Type *OldRetTy = Caller->getType();
2614
Chris Lattner1f7942f2004-01-14 06:06:08 +00002615 // Check to see if we are changing the return type...
2616 if (OldRetTy != FT->getReturnType()) {
2617 if (Callee->isExternal() &&
2618 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
2619 !Caller->use_empty())
2620 return false; // Cannot transform this return value...
2621
2622 // If the callsite is an invoke instruction, and the return value is used by
2623 // a PHI node in a successor, we cannot change the return type of the call
2624 // because there is no place to put the cast instruction (without breaking
2625 // the critical edge). Bail out in this case.
2626 if (!Caller->use_empty())
2627 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2628 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
2629 UI != E; ++UI)
2630 if (PHINode *PN = dyn_cast<PHINode>(*UI))
2631 if (PN->getParent() == II->getNormalDest() ||
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002632 PN->getParent() == II->getUnwindDest())
Chris Lattner1f7942f2004-01-14 06:06:08 +00002633 return false;
2634 }
Chris Lattner970c33a2003-06-19 17:00:31 +00002635
2636 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
2637 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2638
2639 CallSite::arg_iterator AI = CS.arg_begin();
2640 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2641 const Type *ParamTy = FT->getParamType(i);
2642 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
2643 if (Callee->isExternal() && !isConvertible) return false;
2644 }
2645
2646 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
2647 Callee->isExternal())
2648 return false; // Do not delete arguments unless we have a function body...
2649
2650 // Okay, we decided that this is a safe thing to do: go ahead and start
2651 // inserting cast instructions as necessary...
2652 std::vector<Value*> Args;
2653 Args.reserve(NumActualArgs);
2654
2655 AI = CS.arg_begin();
2656 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2657 const Type *ParamTy = FT->getParamType(i);
2658 if ((*AI)->getType() == ParamTy) {
2659 Args.push_back(*AI);
2660 } else {
Chris Lattner1c631e82004-04-08 04:43:23 +00002661 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
2662 *Caller));
Chris Lattner970c33a2003-06-19 17:00:31 +00002663 }
2664 }
2665
2666 // If the function takes more arguments than the call was taking, add them
2667 // now...
2668 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2669 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2670
2671 // If we are removing arguments to the function, emit an obnoxious warning...
2672 if (FT->getNumParams() < NumActualArgs)
2673 if (!FT->isVarArg()) {
2674 std::cerr << "WARNING: While resolving call to function '"
2675 << Callee->getName() << "' arguments were dropped!\n";
2676 } else {
2677 // Add all of the arguments in their promoted form to the arg list...
2678 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
2679 const Type *PTy = getPromotedType((*AI)->getType());
2680 if (PTy != (*AI)->getType()) {
2681 // Must promote to pass through va_arg area!
2682 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
2683 InsertNewInstBefore(Cast, *Caller);
2684 Args.push_back(Cast);
2685 } else {
2686 Args.push_back(*AI);
2687 }
2688 }
2689 }
2690
2691 if (FT->getReturnType() == Type::VoidTy)
2692 Caller->setName(""); // Void type should not have a name...
2693
2694 Instruction *NC;
2695 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattnerfae8ab32004-02-08 21:44:31 +00002696 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner970c33a2003-06-19 17:00:31 +00002697 Args, Caller->getName(), Caller);
2698 } else {
2699 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
2700 }
2701
2702 // Insert a cast of the return type as necessary...
2703 Value *NV = NC;
2704 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
2705 if (NV->getType() != Type::VoidTy) {
2706 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattner686767f2003-10-30 00:46:41 +00002707
2708 // If this is an invoke instruction, we should insert it after the first
2709 // non-phi, instruction in the normal successor block.
2710 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2711 BasicBlock::iterator I = II->getNormalDest()->begin();
2712 while (isa<PHINode>(I)) ++I;
2713 InsertNewInstBefore(NC, *I);
2714 } else {
2715 // Otherwise, it's a call, just insert cast right after the call instr
2716 InsertNewInstBefore(NC, *Caller);
2717 }
Chris Lattner51ea1272004-02-28 05:22:00 +00002718 AddUsersToWorkList(*Caller);
Chris Lattner970c33a2003-06-19 17:00:31 +00002719 } else {
2720 NV = Constant::getNullValue(Caller->getType());
2721 }
2722 }
2723
2724 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
2725 Caller->replaceAllUsesWith(NV);
2726 Caller->getParent()->getInstList().erase(Caller);
2727 removeFromWorkList(Caller);
2728 return true;
2729}
2730
2731
Chris Lattner48a44f72002-05-02 17:06:02 +00002732
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002733// PHINode simplification
2734//
Chris Lattner113f4f42002-06-25 16:13:24 +00002735Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner91daeb52003-12-19 05:58:40 +00002736 if (Value *V = hasConstantValue(&PN))
2737 return ReplaceInstUsesWith(PN, V);
Chris Lattner4db2d222004-02-16 05:07:08 +00002738
2739 // If the only user of this instruction is a cast instruction, and all of the
2740 // incoming values are constants, change this PHI to merge together the casted
2741 // constants.
2742 if (PN.hasOneUse())
2743 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
2744 if (CI->getType() != PN.getType()) { // noop casts will be folded
2745 bool AllConstant = true;
2746 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
2747 if (!isa<Constant>(PN.getIncomingValue(i))) {
2748 AllConstant = false;
2749 break;
2750 }
2751 if (AllConstant) {
2752 // Make a new PHI with all casted values.
2753 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
2754 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
2755 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
2756 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
2757 PN.getIncomingBlock(i));
2758 }
2759
2760 // Update the cast instruction.
2761 CI->setOperand(0, New);
2762 WorkList.push_back(CI); // revisit the cast instruction to fold.
2763 WorkList.push_back(New); // Make sure to revisit the new Phi
2764 return &PN; // PN is now dead!
2765 }
2766 }
Chris Lattner91daeb52003-12-19 05:58:40 +00002767 return 0;
Chris Lattnerbbbdd852002-05-06 18:06:38 +00002768}
2769
Chris Lattner69193f92004-04-05 01:30:19 +00002770static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
2771 Instruction *InsertPoint,
2772 InstCombiner *IC) {
2773 unsigned PS = IC->getTargetData().getPointerSize();
2774 const Type *VTy = V->getType();
2775 Instruction *Cast;
2776 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
2777 // We must insert a cast to ensure we sign-extend.
2778 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
2779 V->getName()), *InsertPoint);
2780 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
2781 *InsertPoint);
2782}
2783
Chris Lattner48a44f72002-05-02 17:06:02 +00002784
Chris Lattner113f4f42002-06-25 16:13:24 +00002785Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002786 Value *PtrOp = GEP.getOperand(0);
Chris Lattner471bd762003-05-22 19:07:21 +00002787 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner113f4f42002-06-25 16:13:24 +00002788 // If so, eliminate the noop.
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002789 if (GEP.getNumOperands() == 1)
Chris Lattner5f667a62004-05-07 22:09:22 +00002790 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002791
2792 bool HasZeroPointerIndex = false;
2793 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
2794 HasZeroPointerIndex = C->isNullValue();
2795
2796 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner5f667a62004-05-07 22:09:22 +00002797 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattner48a44f72002-05-02 17:06:02 +00002798
Chris Lattner69193f92004-04-05 01:30:19 +00002799 // Eliminate unneeded casts for indices.
2800 bool MadeChange = false;
Chris Lattner2b2412d2004-04-07 18:38:20 +00002801 gep_type_iterator GTI = gep_type_begin(GEP);
2802 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
2803 if (isa<SequentialType>(*GTI)) {
2804 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
2805 Value *Src = CI->getOperand(0);
2806 const Type *SrcTy = Src->getType();
2807 const Type *DestTy = CI->getType();
2808 if (Src->getType()->isInteger()) {
2809 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
2810 // We can always eliminate a cast from ulong or long to the other.
2811 // We can always eliminate a cast from uint to int or the other on
2812 // 32-bit pointer platforms.
2813 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
2814 MadeChange = true;
2815 GEP.setOperand(i, Src);
2816 }
2817 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2818 SrcTy->getPrimitiveSize() == 4) {
2819 // We can always eliminate a cast from int to [u]long. We can
2820 // eliminate a cast from uint to [u]long iff the target is a 32-bit
2821 // pointer target.
2822 if (SrcTy->isSigned() ||
2823 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
2824 MadeChange = true;
2825 GEP.setOperand(i, Src);
2826 }
Chris Lattner69193f92004-04-05 01:30:19 +00002827 }
2828 }
2829 }
Chris Lattner2b2412d2004-04-07 18:38:20 +00002830 // If we are using a wider index than needed for this platform, shrink it
2831 // to what we need. If the incoming value needs a cast instruction,
2832 // insert it. This explicit cast can make subsequent optimizations more
2833 // obvious.
2834 Value *Op = GEP.getOperand(i);
2835 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00002836 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner44d0b952004-07-20 01:48:15 +00002837 GEP.setOperand(i, ConstantExpr::getCast(C,
2838 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner1e9ac1a2004-04-17 18:16:10 +00002839 MadeChange = true;
2840 } else {
Chris Lattner2b2412d2004-04-07 18:38:20 +00002841 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
2842 Op->getName()), GEP);
2843 GEP.setOperand(i, Op);
2844 MadeChange = true;
2845 }
Chris Lattner44d0b952004-07-20 01:48:15 +00002846
2847 // If this is a constant idx, make sure to canonicalize it to be a signed
2848 // operand, otherwise CSE and other optimizations are pessimized.
2849 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
2850 GEP.setOperand(i, ConstantExpr::getCast(CUI,
2851 CUI->getType()->getSignedVersion()));
2852 MadeChange = true;
2853 }
Chris Lattner69193f92004-04-05 01:30:19 +00002854 }
2855 if (MadeChange) return &GEP;
2856
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002857 // Combine Indices - If the source pointer to this getelementptr instruction
2858 // is a getelementptr instruction, combine the indices of the two
2859 // getelementptr instructions into a single instruction.
2860 //
Chris Lattner57c67b02004-03-25 22:59:29 +00002861 std::vector<Value*> SrcGEPOperands;
Chris Lattner5f667a62004-05-07 22:09:22 +00002862 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002863 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattner5f667a62004-05-07 22:09:22 +00002864 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner57c67b02004-03-25 22:59:29 +00002865 if (CE->getOpcode() == Instruction::GetElementPtr)
2866 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
2867 }
2868
2869 if (!SrcGEPOperands.empty()) {
Chris Lattner5f667a62004-05-07 22:09:22 +00002870 // Note that if our source is a gep chain itself that we wait for that
2871 // chain to be resolved before we perform this transformation. This
2872 // avoids us creating a TON of code in some cases.
2873 //
2874 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
2875 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
2876 return 0; // Wait until our source is folded to completion.
2877
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002878 std::vector<Value *> Indices;
Chris Lattner5f667a62004-05-07 22:09:22 +00002879
2880 // Find out whether the last index in the source GEP is a sequential idx.
2881 bool EndsWithSequential = false;
2882 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
2883 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattner8ec5f882004-05-08 22:41:42 +00002884 EndsWithSequential = !isa<StructType>(*I);
Chris Lattnerca081252001-12-14 16:52:21 +00002885
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002886 // Can we combine the two pointer arithmetics offsets?
Chris Lattner5f667a62004-05-07 22:09:22 +00002887 if (EndsWithSequential) {
Chris Lattner235af562003-03-05 22:33:14 +00002888 // Replace: gep (gep %P, long B), long A, ...
2889 // With: T = long A+B; gep %P, T, ...
2890 //
Chris Lattner5f667a62004-05-07 22:09:22 +00002891 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner69193f92004-04-05 01:30:19 +00002892 if (SO1 == Constant::getNullValue(SO1->getType())) {
2893 Sum = GO1;
2894 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
2895 Sum = SO1;
2896 } else {
2897 // If they aren't the same type, convert both to an integer of the
2898 // target's pointer size.
2899 if (SO1->getType() != GO1->getType()) {
2900 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
2901 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
2902 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
2903 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
2904 } else {
2905 unsigned PS = TD->getPointerSize();
2906 Instruction *Cast;
2907 if (SO1->getType()->getPrimitiveSize() == PS) {
2908 // Convert GO1 to SO1's type.
2909 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
2910
2911 } else if (GO1->getType()->getPrimitiveSize() == PS) {
2912 // Convert SO1 to GO1's type.
2913 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
2914 } else {
2915 const Type *PT = TD->getIntPtrType();
2916 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
2917 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
2918 }
2919 }
2920 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002921 if (isa<Constant>(SO1) && isa<Constant>(GO1))
2922 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
2923 else {
Chris Lattnerdf20a4d2004-06-10 02:07:29 +00002924 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
2925 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner5f667a62004-05-07 22:09:22 +00002926 }
Chris Lattner69193f92004-04-05 01:30:19 +00002927 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002928
2929 // Recycle the GEP we already have if possible.
2930 if (SrcGEPOperands.size() == 2) {
2931 GEP.setOperand(0, SrcGEPOperands[0]);
2932 GEP.setOperand(1, Sum);
2933 return &GEP;
2934 } else {
2935 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2936 SrcGEPOperands.end()-1);
2937 Indices.push_back(Sum);
2938 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
2939 }
Chris Lattner69193f92004-04-05 01:30:19 +00002940 } else if (isa<Constant>(*GEP.idx_begin()) &&
2941 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattner57c67b02004-03-25 22:59:29 +00002942 SrcGEPOperands.size() != 1) {
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002943 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattner57c67b02004-03-25 22:59:29 +00002944 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
2945 SrcGEPOperands.end());
Chris Lattnerae7a0d32002-08-02 19:29:35 +00002946 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
2947 }
2948
2949 if (!Indices.empty())
Chris Lattner57c67b02004-03-25 22:59:29 +00002950 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002951
Chris Lattner5f667a62004-05-07 22:09:22 +00002952 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002953 // GEP of global variable. If all of the indices for this GEP are
2954 // constants, we can promote this to a constexpr instead of an instruction.
2955
2956 // Scan for nonconstants...
2957 std::vector<Constant*> Indices;
2958 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
2959 for (; I != E && isa<Constant>(*I); ++I)
2960 Indices.push_back(cast<Constant>(*I));
2961
2962 if (I == E) { // If they are all constants...
Chris Lattnerf3edc492004-07-18 18:59:44 +00002963 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattnerc59af1d2002-08-17 22:21:59 +00002964
2965 // Replace all uses of the GEP with the new constexpr...
2966 return ReplaceInstUsesWith(GEP, CE);
2967 }
Chris Lattner5f667a62004-05-07 22:09:22 +00002968 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
Chris Lattner8d0bacb2004-02-22 05:25:17 +00002969 if (CE->getOpcode() == Instruction::Cast) {
2970 if (HasZeroPointerIndex) {
2971 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
2972 // into : GEP [10 x ubyte]* X, long 0, ...
2973 //
2974 // This occurs when the program declares an array extern like "int X[];"
2975 //
2976 Constant *X = CE->getOperand(0);
2977 const PointerType *CPTy = cast<PointerType>(CE->getType());
2978 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
2979 if (const ArrayType *XATy =
2980 dyn_cast<ArrayType>(XTy->getElementType()))
2981 if (const ArrayType *CATy =
2982 dyn_cast<ArrayType>(CPTy->getElementType()))
2983 if (CATy->getElementType() == XATy->getElementType()) {
2984 // At this point, we know that the cast source type is a pointer
2985 // to an array of the same type as the destination pointer
2986 // array. Because the array type is never stepped over (there
2987 // is a leading zero) we can fold the cast into this GEP.
2988 GEP.setOperand(0, X);
2989 return &GEP;
2990 }
2991 }
2992 }
Chris Lattnerca081252001-12-14 16:52:21 +00002993 }
2994
Chris Lattnerca081252001-12-14 16:52:21 +00002995 return 0;
2996}
2997
Chris Lattner1085bdf2002-11-04 16:18:53 +00002998Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
2999 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3000 if (AI.isArrayAllocation()) // Check C != 1
3001 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3002 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003003 AllocationInst *New = 0;
Chris Lattner1085bdf2002-11-04 16:18:53 +00003004
3005 // Create and insert the replacement instruction...
3006 if (isa<MallocInst>(AI))
Chris Lattnerabb77c92004-03-19 06:08:10 +00003007 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003008 else {
3009 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerabb77c92004-03-19 06:08:10 +00003010 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattnera2620ac2002-11-09 00:49:43 +00003011 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003012
3013 InsertNewInstBefore(New, AI);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003014
3015 // Scan to the end of the allocation instructions, to skip over a block of
3016 // allocas if possible...
3017 //
3018 BasicBlock::iterator It = New;
3019 while (isa<AllocationInst>(*It)) ++It;
3020
3021 // Now that I is pointing to the first non-allocation-inst in the block,
3022 // insert our getelementptr instruction...
3023 //
Chris Lattner69193f92004-04-05 01:30:19 +00003024 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
Chris Lattner1085bdf2002-11-04 16:18:53 +00003025 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3026
3027 // Now make everything use the getelementptr instead of the original
3028 // allocation.
Chris Lattnerabb77c92004-03-19 06:08:10 +00003029 return ReplaceInstUsesWith(AI, V);
Chris Lattner1085bdf2002-11-04 16:18:53 +00003030 }
Chris Lattnerabb77c92004-03-19 06:08:10 +00003031
3032 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3033 // Note that we only do this for alloca's, because malloc should allocate and
3034 // return a unique pointer, even for a zero byte allocation.
Chris Lattner49df6ce2004-07-02 22:55:47 +00003035 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3036 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattnerabb77c92004-03-19 06:08:10 +00003037 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3038
Chris Lattner1085bdf2002-11-04 16:18:53 +00003039 return 0;
3040}
3041
Chris Lattner8427bff2003-12-07 01:24:23 +00003042Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3043 Value *Op = FI.getOperand(0);
3044
3045 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3046 if (CastInst *CI = dyn_cast<CastInst>(Op))
3047 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3048 FI.setOperand(0, CI->getOperand(0));
3049 return &FI;
3050 }
3051
Chris Lattnerf3a36602004-02-28 04:57:37 +00003052 // If we have 'free null' delete the instruction. This can happen in stl code
3053 // when lots of inlining happens.
Chris Lattner51ea1272004-02-28 05:22:00 +00003054 if (isa<ConstantPointerNull>(Op))
3055 return EraseInstFromFunction(FI);
Chris Lattnerf3a36602004-02-28 04:57:37 +00003056
Chris Lattner8427bff2003-12-07 01:24:23 +00003057 return 0;
3058}
3059
3060
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003061/// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3062/// constantexpr, return the constant value being addressed by the constant
3063/// expression, or null if something is funny.
3064///
3065static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner69193f92004-04-05 01:30:19 +00003066 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003067 return 0; // Do not allow stepping over the value!
3068
3069 // Loop over all of the operands, tracking down which value we are
3070 // addressing...
Chris Lattnered79d8a2004-05-27 17:30:27 +00003071 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3072 for (++I; I != E; ++I)
3073 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3074 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3075 assert(CU->getValue() < STy->getNumElements() &&
3076 "Struct index out of range!");
3077 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003078 C = CS->getOperand(CU->getValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003079 } else if (isa<ConstantAggregateZero>(C)) {
3080 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3081 } else {
3082 return 0;
3083 }
3084 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3085 const ArrayType *ATy = cast<ArrayType>(*I);
3086 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3087 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
Alkis Evlogimenos83243722004-08-04 08:44:43 +00003088 C = CA->getOperand(CI->getRawValue());
Chris Lattnered79d8a2004-05-27 17:30:27 +00003089 else if (isa<ConstantAggregateZero>(C))
3090 C = Constant::getNullValue(ATy->getElementType());
3091 else
3092 return 0;
3093 } else {
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003094 return 0;
Chris Lattnered79d8a2004-05-27 17:30:27 +00003095 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003096 return C;
3097}
3098
Chris Lattner35e24772004-07-13 01:49:43 +00003099static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3100 User *CI = cast<User>(LI.getOperand(0));
3101
3102 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3103 if (const PointerType *SrcTy =
3104 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3105 const Type *SrcPTy = SrcTy->getElementType();
3106 if (SrcPTy->isSized() && DestPTy->isSized() &&
3107 IC.getTargetData().getTypeSize(SrcPTy) ==
3108 IC.getTargetData().getTypeSize(DestPTy) &&
3109 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3110 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3111 // Okay, we are casting from one integer or pointer type to another of
3112 // the same size. Instead of casting the pointer before the load, cast
3113 // the result of the loaded value.
3114 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003115 CI->getName(),
3116 LI.isVolatile()),LI);
Chris Lattner35e24772004-07-13 01:49:43 +00003117 // Now cast the result of the load.
3118 return new CastInst(NewLoad, LI.getType());
3119 }
3120 }
3121 return 0;
3122}
3123
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003124/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattnere6f13092004-09-19 19:18:10 +00003125/// from this value cannot trap. If it is not obviously safe to load from the
3126/// specified pointer, we do a quick local scan of the basic block containing
3127/// ScanFrom, to determine if the address is already accessed.
3128static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3129 // If it is an alloca or global variable, it is always safe to load from.
3130 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3131
3132 // Otherwise, be a little bit agressive by scanning the local block where we
3133 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003134 // from/to. If so, the previous load or store would have already trapped,
3135 // so there is no harm doing an extra load (also, CSE will later eliminate
3136 // the load entirely).
Chris Lattnere6f13092004-09-19 19:18:10 +00003137 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3138
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003139 while (BBI != E) {
Chris Lattnere6f13092004-09-19 19:18:10 +00003140 --BBI;
3141
3142 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3143 if (LI->getOperand(0) == V) return true;
3144 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3145 if (SI->getOperand(1) == V) return true;
3146
Alkis Evlogimenosd59cebf2004-09-20 06:42:58 +00003147 }
Chris Lattnere6f13092004-09-19 19:18:10 +00003148 return false;
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003149}
3150
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003151Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3152 Value *Op = LI.getOperand(0);
Chris Lattner7e8af382004-01-12 04:13:56 +00003153
Chris Lattner6679e462004-04-14 03:28:36 +00003154 if (Constant *C = dyn_cast<Constant>(Op))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003155 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
Chris Lattner6679e462004-04-14 03:28:36 +00003156 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003157
3158 // Instcombine load (constant global) into the value loaded...
3159 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Chris Lattnerbdb0ce02003-07-22 21:46:59 +00003160 if (GV->isConstant() && !GV->isExternal())
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003161 return ReplaceInstUsesWith(LI, GV->getInitializer());
3162
3163 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3164 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
Chris Lattner35e24772004-07-13 01:49:43 +00003165 if (CE->getOpcode() == Instruction::GetElementPtr) {
Reid Spencer87436872004-07-18 00:38:32 +00003166 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3167 if (GV->isConstant() && !GV->isExternal())
3168 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3169 return ReplaceInstUsesWith(LI, V);
Chris Lattner35e24772004-07-13 01:49:43 +00003170 } else if (CE->getOpcode() == Instruction::Cast) {
3171 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3172 return Res;
3173 }
Chris Lattnere228ee52004-04-08 20:39:49 +00003174
3175 // load (cast X) --> cast (load X) iff safe
Chris Lattner35e24772004-07-13 01:49:43 +00003176 if (CastInst *CI = dyn_cast<CastInst>(Op))
3177 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3178 return Res;
Chris Lattnere228ee52004-04-08 20:39:49 +00003179
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003180 if (!LI.isVolatile() && Op->hasOneUse()) {
3181 // Change select and PHI nodes to select values instead of addresses: this
3182 // helps alias analysis out a lot, allows many others simplifications, and
3183 // exposes redundancy in the code.
3184 //
3185 // Note that we cannot do the transformation unless we know that the
3186 // introduced loads cannot trap! Something like this is valid as long as
3187 // the condition is always false: load (select bool %C, int* null, int* %G),
3188 // but it would not be valid if we transformed it to load from null
3189 // unconditionally.
3190 //
3191 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3192 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattnere6f13092004-09-19 19:18:10 +00003193 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3194 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003195 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner42618552004-09-20 10:15:10 +00003196 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003197 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner42618552004-09-20 10:15:10 +00003198 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003199 return new SelectInst(SI->getCondition(), V1, V2);
3200 }
3201
Chris Lattnerbdcf41a2004-09-23 15:46:00 +00003202 // load (select (cond, null, P)) -> load P
3203 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3204 if (C->isNullValue()) {
3205 LI.setOperand(0, SI->getOperand(2));
3206 return &LI;
3207 }
3208
3209 // load (select (cond, P, null)) -> load P
3210 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3211 if (C->isNullValue()) {
3212 LI.setOperand(0, SI->getOperand(1));
3213 return &LI;
3214 }
3215
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003216 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3217 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner42618552004-09-20 10:15:10 +00003218 bool Safe = PN->getParent() == LI.getParent();
3219
3220 // Scan all of the instructions between the PHI and the load to make
3221 // sure there are no instructions that might possibly alter the value
3222 // loaded from the PHI.
3223 if (Safe) {
3224 BasicBlock::iterator I = &LI;
3225 for (--I; !isa<PHINode>(I); --I)
3226 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3227 Safe = false;
3228 break;
3229 }
3230 }
3231
3232 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattnere6f13092004-09-19 19:18:10 +00003233 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner42618552004-09-20 10:15:10 +00003234 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003235 Safe = false;
Chris Lattner42618552004-09-20 10:15:10 +00003236
Chris Lattnerf62ea8e2004-09-19 18:43:46 +00003237 if (Safe) {
3238 // Create the PHI.
3239 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3240 InsertNewInstBefore(NewPN, *PN);
3241 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3242
3243 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3244 BasicBlock *BB = PN->getIncomingBlock(i);
3245 Value *&TheLoad = LoadMap[BB];
3246 if (TheLoad == 0) {
3247 Value *InVal = PN->getIncomingValue(i);
3248 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3249 InVal->getName()+".val"),
3250 *BB->getTerminator());
3251 }
3252 NewPN->addIncoming(TheLoad, BB);
3253 }
3254 return ReplaceInstUsesWith(LI, NewPN);
3255 }
3256 }
3257 }
Chris Lattner0f1d8a32003-06-26 05:06:25 +00003258 return 0;
3259}
3260
3261
Chris Lattner9eef8a72003-06-04 04:46:00 +00003262Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3263 // Change br (not X), label True, label False to: br X, label False, True
Chris Lattnerd4252a72004-07-30 07:50:03 +00003264 Value *X;
3265 BasicBlock *TrueDest;
3266 BasicBlock *FalseDest;
3267 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3268 !isa<Constant>(X)) {
3269 // Swap Destinations and condition...
3270 BI.setCondition(X);
3271 BI.setSuccessor(0, FalseDest);
3272 BI.setSuccessor(1, TrueDest);
3273 return &BI;
3274 }
3275
3276 // Cannonicalize setne -> seteq
3277 Instruction::BinaryOps Op; Value *Y;
3278 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3279 TrueDest, FalseDest)))
3280 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3281 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3282 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3283 std::string Name = I->getName(); I->setName("");
3284 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3285 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattnere967b342003-06-04 05:10:11 +00003286 // Swap Destinations and condition...
Chris Lattnerd4252a72004-07-30 07:50:03 +00003287 BI.setCondition(NewSCC);
Chris Lattnere967b342003-06-04 05:10:11 +00003288 BI.setSuccessor(0, FalseDest);
3289 BI.setSuccessor(1, TrueDest);
Chris Lattnerd4252a72004-07-30 07:50:03 +00003290 removeFromWorkList(I);
3291 I->getParent()->getInstList().erase(I);
3292 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattnere967b342003-06-04 05:10:11 +00003293 return &BI;
3294 }
Chris Lattnerd4252a72004-07-30 07:50:03 +00003295
Chris Lattner9eef8a72003-06-04 04:46:00 +00003296 return 0;
3297}
Chris Lattner1085bdf2002-11-04 16:18:53 +00003298
Chris Lattner4c9c20a2004-07-03 00:26:11 +00003299Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3300 Value *Cond = SI.getCondition();
3301 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3302 if (I->getOpcode() == Instruction::Add)
3303 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3304 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3305 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3306 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3307 AddRHS));
3308 SI.setOperand(0, I->getOperand(0));
3309 WorkList.push_back(I);
3310 return &SI;
3311 }
3312 }
3313 return 0;
3314}
3315
Chris Lattnerca081252001-12-14 16:52:21 +00003316
Chris Lattner99f48c62002-09-02 04:59:56 +00003317void InstCombiner::removeFromWorkList(Instruction *I) {
3318 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3319 WorkList.end());
3320}
3321
Chris Lattner113f4f42002-06-25 16:13:24 +00003322bool InstCombiner::runOnFunction(Function &F) {
Chris Lattner260ab202002-04-18 17:39:14 +00003323 bool Changed = false;
Chris Lattnerf4ad1652003-11-02 05:57:39 +00003324 TD = &getAnalysis<TargetData>();
Chris Lattnerca081252001-12-14 16:52:21 +00003325
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003326 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3327 WorkList.push_back(&*i);
Chris Lattner2d3a7a62004-04-27 15:13:33 +00003328
Chris Lattnerca081252001-12-14 16:52:21 +00003329
3330 while (!WorkList.empty()) {
3331 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3332 WorkList.pop_back();
3333
Misha Brukman632df282002-10-29 23:06:16 +00003334 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner99f48c62002-09-02 04:59:56 +00003335 // Check to see if we can DIE the instruction...
3336 if (isInstructionTriviallyDead(I)) {
3337 // Add operands to the worklist...
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003338 if (I->getNumOperands() < 4)
Chris Lattner51ea1272004-02-28 05:22:00 +00003339 AddUsesToWorkList(*I);
Chris Lattner99f48c62002-09-02 04:59:56 +00003340 ++NumDeadInst;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003341
3342 I->getParent()->getInstList().erase(I);
3343 removeFromWorkList(I);
3344 continue;
3345 }
Chris Lattner99f48c62002-09-02 04:59:56 +00003346
Misha Brukman632df282002-10-29 23:06:16 +00003347 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner99f48c62002-09-02 04:59:56 +00003348 if (Constant *C = ConstantFoldInstruction(I)) {
3349 // Add operands to the worklist...
Chris Lattner51ea1272004-02-28 05:22:00 +00003350 AddUsesToWorkList(*I);
Chris Lattnerc6509f42002-12-05 22:41:53 +00003351 ReplaceInstUsesWith(*I, C);
3352
Chris Lattner99f48c62002-09-02 04:59:56 +00003353 ++NumConstProp;
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003354 I->getParent()->getInstList().erase(I);
Chris Lattner800aaaf2003-10-07 15:17:02 +00003355 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003356 continue;
Chris Lattner99f48c62002-09-02 04:59:56 +00003357 }
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003358
Chris Lattnerca081252001-12-14 16:52:21 +00003359 // Now that we have an instruction, try combining it to simplify it...
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003360 if (Instruction *Result = visit(*I)) {
Chris Lattner0b18c1d2002-05-10 15:38:35 +00003361 ++NumCombined;
Chris Lattner260ab202002-04-18 17:39:14 +00003362 // Should we replace the old instruction with a new one?
Chris Lattner053c0932002-05-14 15:24:07 +00003363 if (Result != I) {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003364 DEBUG(std::cerr << "IC: Old = " << *I
3365 << " New = " << *Result);
3366
Chris Lattner396dbfe2004-06-09 05:08:07 +00003367 // Everything uses the new instruction now.
3368 I->replaceAllUsesWith(Result);
3369
3370 // Push the new instruction and any users onto the worklist.
3371 WorkList.push_back(Result);
3372 AddUsersToWorkList(*Result);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003373
3374 // Move the name to the new instruction first...
3375 std::string OldName = I->getName(); I->setName("");
Chris Lattner950fc782003-10-07 22:58:41 +00003376 Result->setName(OldName);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003377
3378 // Insert the new instruction into the basic block...
3379 BasicBlock *InstParent = I->getParent();
3380 InstParent->getInstList().insert(I, Result);
3381
Chris Lattner63d75af2004-05-01 23:27:23 +00003382 // Make sure that we reprocess all operands now that we reduced their
3383 // use counts.
Chris Lattnerb643a9e2004-05-01 23:19:52 +00003384 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3385 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3386 WorkList.push_back(OpI);
3387
Chris Lattner396dbfe2004-06-09 05:08:07 +00003388 // Instructions can end up on the worklist more than once. Make sure
3389 // we do not process an instruction that has been deleted.
3390 removeFromWorkList(I);
Chris Lattnere8ed4ef2003-10-06 17:11:01 +00003391
3392 // Erase the old instruction.
3393 InstParent->getInstList().erase(I);
Chris Lattner113f4f42002-06-25 16:13:24 +00003394 } else {
Chris Lattner7d2a5392004-03-13 23:54:27 +00003395 DEBUG(std::cerr << "IC: MOD = " << *I);
3396
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003397 // If the instruction was modified, it's possible that it is now dead.
3398 // if so, remove it.
Chris Lattner63d75af2004-05-01 23:27:23 +00003399 if (isInstructionTriviallyDead(I)) {
3400 // Make sure we process all operands now that we are reducing their
3401 // use counts.
3402 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3403 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3404 WorkList.push_back(OpI);
3405
3406 // Instructions may end up in the worklist more than once. Erase all
3407 // occurrances of this instruction.
Chris Lattner99f48c62002-09-02 04:59:56 +00003408 removeFromWorkList(I);
Chris Lattner63d75af2004-05-01 23:27:23 +00003409 I->getParent()->getInstList().erase(I);
Chris Lattner396dbfe2004-06-09 05:08:07 +00003410 } else {
3411 WorkList.push_back(Result);
3412 AddUsersToWorkList(*Result);
Chris Lattnerae7a0d32002-08-02 19:29:35 +00003413 }
Chris Lattner053c0932002-05-14 15:24:07 +00003414 }
Chris Lattner260ab202002-04-18 17:39:14 +00003415 Changed = true;
Chris Lattnerca081252001-12-14 16:52:21 +00003416 }
3417 }
3418
Chris Lattner260ab202002-04-18 17:39:14 +00003419 return Changed;
Chris Lattner04805fa2002-02-26 21:46:54 +00003420}
3421
Brian Gaeke38b79e82004-07-27 17:43:21 +00003422FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattner260ab202002-04-18 17:39:14 +00003423 return new InstCombiner();
Chris Lattner04805fa2002-02-26 21:46:54 +00003424}
Brian Gaeke960707c2003-11-11 22:41:34 +00003425