blob: 0ac849d44cc82fb379d8273cf4b89a7ce0d2f6fa [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-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 Lattnerdf17af12003-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 Lattner2cd91962003-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 Lattnere92d2f42003-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 Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattnerb3d59702005-07-07 20:40:38 +000051#include "llvm/ADT/DepthFirstIterator.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000057
Chris Lattnerdd841ae2002-04-18 17:39:14 +000058namespace {
Chris Lattnera92f6962002-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");
Chris Lattnerea1c4542004-12-08 23:43:58 +000062 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000063
Chris Lattnerf57b8452002-04-27 06:56:12 +000064 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000065 public InstVisitor<InstCombiner, Instruction*> {
66 // Worklist of all of the instructions that need to be simplified.
67 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000068 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000069
Chris Lattner7bcc0e72004-02-28 05:22:00 +000070 /// AddUsersToWorkList - When an instruction is simplified, add all users of
71 /// the instruction to the work lists because they might get more simplified
72 /// now.
73 ///
74 void AddUsersToWorkList(Instruction &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000075 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000076 UI != UE; ++UI)
77 WorkList.push_back(cast<Instruction>(*UI));
78 }
79
Chris Lattner7bcc0e72004-02-28 05:22:00 +000080 /// AddUsesToWorkList - When an instruction is simplified, add operands to
81 /// the work lists because they might get more simplified now.
82 ///
83 void AddUsesToWorkList(Instruction &I) {
84 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
85 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
86 WorkList.push_back(Op);
87 }
88
Chris Lattner62b14df2002-09-02 04:59:56 +000089 // removeFromWorkList - remove all instances of I from the worklist.
90 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000091 public:
Chris Lattner7e708292002-06-25 16:13:24 +000092 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000093
Chris Lattner97e52e42002-04-28 21:27:06 +000094 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000095 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000096 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000097 }
98
Chris Lattner28977af2004-04-05 01:30:19 +000099 TargetData &getTargetData() const { return *TD; }
100
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000101 // Visitation implementation - Implement instruction combining for different
102 // instruction types. The semantics are as follows:
103 // Return Value:
104 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000105 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000106 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000107 //
Chris Lattner7e708292002-06-25 16:13:24 +0000108 Instruction *visitAdd(BinaryOperator &I);
109 Instruction *visitSub(BinaryOperator &I);
110 Instruction *visitMul(BinaryOperator &I);
111 Instruction *visitDiv(BinaryOperator &I);
112 Instruction *visitRem(BinaryOperator &I);
113 Instruction *visitAnd(BinaryOperator &I);
114 Instruction *visitOr (BinaryOperator &I);
115 Instruction *visitXor(BinaryOperator &I);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000116 Instruction *visitSetCondInst(SetCondInst &I);
117 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
118
Chris Lattner574da9b2005-01-13 20:14:25 +0000119 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000121 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000122 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000123 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
124 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000125 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000126 Instruction *visitCallInst(CallInst &CI);
127 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000128 Instruction *visitPHINode(PHINode &PN);
129 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000130 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000131 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000132 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000133 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000134 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000135 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000136
137 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000138 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000139
Chris Lattner9fe38862003-06-19 17:00:31 +0000140 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000141 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000142 bool transformConstExprCastCall(CallSite CS);
143
Chris Lattner28977af2004-04-05 01:30:19 +0000144 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000145 // InsertNewInstBefore - insert an instruction New before instruction Old
146 // in the program. Add the new instruction to the worklist.
147 //
Chris Lattner955f3312004-09-28 21:48:02 +0000148 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000149 assert(New && New->getParent() == 0 &&
150 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000151 BasicBlock *BB = Old.getParent();
152 BB->getInstList().insert(&Old, New); // Insert inst
153 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000154 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000155 }
156
Chris Lattner0c967662004-09-24 15:21:34 +0000157 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
158 /// This also adds the cast to the worklist. Finally, this returns the
159 /// cast.
160 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
161 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000162
Chris Lattner0c967662004-09-24 15:21:34 +0000163 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
164 WorkList.push_back(C);
165 return C;
166 }
167
Chris Lattner8b170942002-08-09 23:47:40 +0000168 // ReplaceInstUsesWith - This method is to be used when an instruction is
169 // found to be dead, replacable with another preexisting expression. Here
170 // we add all uses of I to the worklist, replace all uses of I with the new
171 // value, then return I, so that the inst combiner will know that I was
172 // modified.
173 //
174 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000175 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000176 if (&I != V) {
177 I.replaceAllUsesWith(V);
178 return &I;
179 } else {
180 // If we are replacing the instruction with itself, this must be in a
181 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000182 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000183 return &I;
184 }
Chris Lattner8b170942002-08-09 23:47:40 +0000185 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000186
187 // EraseInstFromFunction - When dealing with an instruction that has side
188 // effects or produces a void value, we can't rely on DCE to delete the
189 // instruction. Instead, visit methods should return the value returned by
190 // this function.
191 Instruction *EraseInstFromFunction(Instruction &I) {
192 assert(I.use_empty() && "Cannot erase instruction that is used!");
193 AddUsesToWorkList(I);
194 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000195 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000196 return 0; // Don't do anything with FI
197 }
198
199
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000200 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000201 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
202 /// InsertBefore instruction. This is specialized a bit to avoid inserting
203 /// casts that are known to not do anything...
204 ///
205 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
206 Instruction *InsertBefore);
207
Chris Lattnerc8802d22003-03-11 00:12:48 +0000208 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000209 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000210 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000211
Chris Lattner4e998b22004-09-29 05:07:12 +0000212
213 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
214 // PHI node as operand #0, see if we can fold the instruction into the PHI
215 // (which is only possible if all operands to the PHI are constants).
216 Instruction *FoldOpIntoPhi(Instruction &I);
217
Chris Lattnerbac32862004-11-14 19:13:23 +0000218 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
219 // operator and they all are only used by the PHI, PHI together their
220 // inputs, and do the operation once, to the result of the PHI.
221 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
222
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000223 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
224 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000225
226 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
227 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000228 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
229 bool Inside, Instruction &IB);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000230 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000231
Chris Lattnera6275cc2002-07-26 21:12:46 +0000232 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000233}
234
Chris Lattner4f98c562003-03-10 21:43:22 +0000235// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000236// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000237static unsigned getComplexity(Value *V) {
238 if (isa<Instruction>(V)) {
239 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000240 return 3;
241 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000242 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000243 if (isa<Argument>(V)) return 3;
244 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000245}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000246
Chris Lattnerc8802d22003-03-11 00:12:48 +0000247// isOnlyUse - Return true if this instruction will be deleted if we stop using
248// it.
249static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000250 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000251}
252
Chris Lattner4cb170c2004-02-23 06:38:22 +0000253// getPromotedType - Return the specified type promoted as it would be to pass
254// though a va_arg area...
255static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000256 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000257 case Type::SByteTyID:
258 case Type::ShortTyID: return Type::IntTy;
259 case Type::UByteTyID:
260 case Type::UShortTyID: return Type::UIntTy;
261 case Type::FloatTyID: return Type::DoubleTy;
262 default: return Ty;
263 }
264}
265
Chris Lattnereed48272005-09-13 00:40:14 +0000266/// isCast - If the specified operand is a CastInst or a constant expr cast,
267/// return the operand value, otherwise return null.
268static Value *isCast(Value *V) {
269 if (CastInst *I = dyn_cast<CastInst>(V))
270 return I->getOperand(0);
271 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
272 if (CE->getOpcode() == Instruction::Cast)
273 return CE->getOperand(0);
274 return 0;
275}
276
Chris Lattner4f98c562003-03-10 21:43:22 +0000277// SimplifyCommutative - This performs a few simplifications for commutative
278// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000279//
Chris Lattner4f98c562003-03-10 21:43:22 +0000280// 1. Order operands such that they are listed from right (least complex) to
281// left (most complex). This puts constants before unary operators before
282// binary operators.
283//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000284// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
285// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000286//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000287bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000288 bool Changed = false;
289 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
290 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000291
Chris Lattner4f98c562003-03-10 21:43:22 +0000292 if (!I.isAssociative()) return Changed;
293 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000294 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
295 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
296 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000297 Constant *Folded = ConstantExpr::get(I.getOpcode(),
298 cast<Constant>(I.getOperand(1)),
299 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000300 I.setOperand(0, Op->getOperand(0));
301 I.setOperand(1, Folded);
302 return true;
303 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
304 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
305 isOnlyUse(Op) && isOnlyUse(Op1)) {
306 Constant *C1 = cast<Constant>(Op->getOperand(1));
307 Constant *C2 = cast<Constant>(Op1->getOperand(1));
308
309 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000310 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000311 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
312 Op1->getOperand(0),
313 Op1->getName(), &I);
314 WorkList.push_back(New);
315 I.setOperand(0, New);
316 I.setOperand(1, Folded);
317 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000318 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000319 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000320 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000321}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000322
Chris Lattner8d969642003-03-10 23:06:50 +0000323// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
324// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000325//
Chris Lattner8d969642003-03-10 23:06:50 +0000326static inline Value *dyn_castNegVal(Value *V) {
327 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000328 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000329
Chris Lattner0ce85802004-12-14 20:08:06 +0000330 // Constants can be considered to be negated values if they can be folded.
331 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
332 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000333 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000334}
335
Chris Lattner8d969642003-03-10 23:06:50 +0000336static inline Value *dyn_castNotVal(Value *V) {
337 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000338 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000339
340 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000341 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000342 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000343 return 0;
344}
345
Chris Lattnerc8802d22003-03-11 00:12:48 +0000346// dyn_castFoldableMul - If this value is a multiply that can be folded into
347// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000348// non-constant operand of the multiply, and set CST to point to the multiplier.
349// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000350//
Chris Lattner50af16a2004-11-13 19:50:12 +0000351static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000352 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000353 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000354 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000355 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000356 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000357 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000358 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000359 // The multiplier is really 1 << CST.
360 Constant *One = ConstantInt::get(V->getType(), 1);
361 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
362 return I->getOperand(0);
363 }
364 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000365 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000366}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000367
Chris Lattner574da9b2005-01-13 20:14:25 +0000368/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
369/// expression, return it.
370static User *dyn_castGetElementPtr(Value *V) {
371 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
372 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
373 if (CE->getOpcode() == Instruction::GetElementPtr)
374 return cast<User>(V);
375 return false;
376}
377
Chris Lattner955f3312004-09-28 21:48:02 +0000378// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000379static ConstantInt *AddOne(ConstantInt *C) {
380 return cast<ConstantInt>(ConstantExpr::getAdd(C,
381 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000382}
Chris Lattnera96879a2004-09-29 17:40:11 +0000383static ConstantInt *SubOne(ConstantInt *C) {
384 return cast<ConstantInt>(ConstantExpr::getSub(C,
385 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000386}
387
Chris Lattner5931c542005-09-24 23:43:33 +0000388/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
389/// this predicate to simplify operations downstream. V and Mask are known to
390/// be the same type.
391static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask) {
392 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
393 // we cannot optimize based on the assumption that it is zero without changing
394 // to to an explicit zero. If we don't change it to zero, other code could
395 // optimized based on the contradictory assumption that it is non-zero.
396 // Because instcombine aggressively folds operations with undef args anyway,
397 // this won't lose us code quality.
398 if (Mask->isNullValue())
399 return true;
400 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
401 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
402
403 if (Instruction *I = dyn_cast<Instruction>(V)) {
404 switch (I->getOpcode()) {
405 case Instruction::And:
406 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
407 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
408 if (ConstantExpr::getAnd(CI, Mask)->isNullValue())
409 return true;
410 break;
411 case Instruction::Or:
412 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
413 return MaskedValueIsZero(I->getOperand(1), Mask) &&
414 MaskedValueIsZero(I->getOperand(0), Mask);
415 case Instruction::Select:
416 // If the T and F values are MaskedValueIsZero, the result is also zero.
417 return MaskedValueIsZero(I->getOperand(2), Mask) &&
418 MaskedValueIsZero(I->getOperand(1), Mask);
419 case Instruction::Cast: {
420 const Type *SrcTy = I->getOperand(0)->getType();
421 if (SrcTy == Type::BoolTy)
422 return (Mask->getRawValue() & 1) == 0;
423
424 if (SrcTy->isInteger()) {
425 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
426 if (SrcTy->isUnsigned() && // Only handle zero ext.
427 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
428 return true;
429
430 // If this is a noop cast, recurse.
431 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
432 SrcTy->getSignedVersion() == I->getType()) {
433 Constant *NewMask =
434 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
435 return MaskedValueIsZero(I->getOperand(0),
436 cast<ConstantIntegral>(NewMask));
437 }
438 }
439 break;
440 }
441 case Instruction::Shl:
442 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
443 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
444 return MaskedValueIsZero(I->getOperand(0),
445 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)));
446 break;
447 case Instruction::Shr:
448 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
449 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
450 if (I->getType()->isUnsigned()) {
451 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
452 C1 = ConstantExpr::getShr(C1, SA);
453 C1 = ConstantExpr::getAnd(C1, Mask);
454 if (C1->isNullValue())
455 return true;
456 }
457 break;
458 }
459 }
460
461 return false;
462}
463
Chris Lattner955f3312004-09-28 21:48:02 +0000464// isTrueWhenEqual - Return true if the specified setcondinst instruction is
465// true when both operands are equal...
466//
467static bool isTrueWhenEqual(Instruction &I) {
468 return I.getOpcode() == Instruction::SetEQ ||
469 I.getOpcode() == Instruction::SetGE ||
470 I.getOpcode() == Instruction::SetLE;
471}
Chris Lattner564a7272003-08-13 19:01:45 +0000472
473/// AssociativeOpt - Perform an optimization on an associative operator. This
474/// function is designed to check a chain of associative operators for a
475/// potential to apply a certain optimization. Since the optimization may be
476/// applicable if the expression was reassociated, this checks the chain, then
477/// reassociates the expression as necessary to expose the optimization
478/// opportunity. This makes use of a special Functor, which must define
479/// 'shouldApply' and 'apply' methods.
480///
481template<typename Functor>
482Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
483 unsigned Opcode = Root.getOpcode();
484 Value *LHS = Root.getOperand(0);
485
486 // Quick check, see if the immediate LHS matches...
487 if (F.shouldApply(LHS))
488 return F.apply(Root);
489
490 // Otherwise, if the LHS is not of the same opcode as the root, return.
491 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +0000492 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000493 // Should we apply this transform to the RHS?
494 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
495
496 // If not to the RHS, check to see if we should apply to the LHS...
497 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
498 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
499 ShouldApply = true;
500 }
501
502 // If the functor wants to apply the optimization to the RHS of LHSI,
503 // reassociate the expression from ((? op A) op B) to (? op (A op B))
504 if (ShouldApply) {
505 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +0000506
Chris Lattner564a7272003-08-13 19:01:45 +0000507 // Now all of the instructions are in the current basic block, go ahead
508 // and perform the reassociation.
509 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
510
511 // First move the selected RHS to the LHS of the root...
512 Root.setOperand(0, LHSI->getOperand(1));
513
514 // Make what used to be the LHS of the root be the user of the root...
515 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +0000516 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +0000517 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
518 return 0;
519 }
Chris Lattner65725312004-04-16 18:08:07 +0000520 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +0000521 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +0000522 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
523 BasicBlock::iterator ARI = &Root; ++ARI;
524 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
525 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +0000526
527 // Now propagate the ExtraOperand down the chain of instructions until we
528 // get to LHSI.
529 while (TmpLHSI != LHSI) {
530 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +0000531 // Move the instruction to immediately before the chain we are
532 // constructing to avoid breaking dominance properties.
533 NextLHSI->getParent()->getInstList().remove(NextLHSI);
534 BB->getInstList().insert(ARI, NextLHSI);
535 ARI = NextLHSI;
536
Chris Lattner564a7272003-08-13 19:01:45 +0000537 Value *NextOp = NextLHSI->getOperand(1);
538 NextLHSI->setOperand(1, ExtraOperand);
539 TmpLHSI = NextLHSI;
540 ExtraOperand = NextOp;
541 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000542
Chris Lattner564a7272003-08-13 19:01:45 +0000543 // Now that the instructions are reassociated, have the functor perform
544 // the transformation...
545 return F.apply(Root);
546 }
Misha Brukmanfd939082005-04-21 23:48:37 +0000547
Chris Lattner564a7272003-08-13 19:01:45 +0000548 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
549 }
550 return 0;
551}
552
553
554// AddRHS - Implements: X + X --> X << 1
555struct AddRHS {
556 Value *RHS;
557 AddRHS(Value *rhs) : RHS(rhs) {}
558 bool shouldApply(Value *LHS) const { return LHS == RHS; }
559 Instruction *apply(BinaryOperator &Add) const {
560 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
561 ConstantInt::get(Type::UByteTy, 1));
562 }
563};
564
565// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
566// iff C1&C2 == 0
567struct AddMaskingAnd {
568 Constant *C2;
569 AddMaskingAnd(Constant *c) : C2(c) {}
570 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000571 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +0000572 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000573 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +0000574 }
575 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +0000576 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +0000577 }
578};
579
Chris Lattner6e7ba452005-01-01 16:22:27 +0000580static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +0000581 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +0000582 if (isa<CastInst>(I)) {
583 if (Constant *SOC = dyn_cast<Constant>(SO))
584 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +0000585
Chris Lattner6e7ba452005-01-01 16:22:27 +0000586 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
587 SO->getName() + ".cast"), I);
588 }
589
Chris Lattner2eefe512004-04-09 19:05:30 +0000590 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +0000591 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
592 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +0000593
Chris Lattner2eefe512004-04-09 19:05:30 +0000594 if (Constant *SOC = dyn_cast<Constant>(SO)) {
595 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +0000596 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
597 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +0000598 }
599
600 Value *Op0 = SO, *Op1 = ConstOperand;
601 if (!ConstIsRHS)
602 std::swap(Op0, Op1);
603 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +0000604 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
605 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
606 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
607 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +0000608 else {
Chris Lattner2eefe512004-04-09 19:05:30 +0000609 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +0000610 abort();
611 }
Chris Lattner6e7ba452005-01-01 16:22:27 +0000612 return IC->InsertNewInstBefore(New, I);
613}
614
615// FoldOpIntoSelect - Given an instruction with a select as one operand and a
616// constant as the other operand, try to fold the binary operator into the
617// select arguments. This also works for Cast instructions, which obviously do
618// not have a second operand.
619static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
620 InstCombiner *IC) {
621 // Don't modify shared select instructions
622 if (!SI->hasOneUse()) return 0;
623 Value *TV = SI->getOperand(1);
624 Value *FV = SI->getOperand(2);
625
626 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +0000627 // Bool selects with constant operands can be folded to logical ops.
628 if (SI->getType() == Type::BoolTy) return 0;
629
Chris Lattner6e7ba452005-01-01 16:22:27 +0000630 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
631 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
632
633 return new SelectInst(SI->getCondition(), SelectTrueVal,
634 SelectFalseVal);
635 }
636 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +0000637}
638
Chris Lattner4e998b22004-09-29 05:07:12 +0000639
640/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
641/// node as operand #0, see if we can fold the instruction into the PHI (which
642/// is only possible if all operands to the PHI are constants).
643Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
644 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +0000645 unsigned NumPHIValues = PN->getNumIncomingValues();
646 if (!PN->hasOneUse() || NumPHIValues == 0 ||
647 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +0000648
649 // Check to see if all of the operands of the PHI are constants. If not, we
650 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +0000651 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +0000652 if (!isa<Constant>(PN->getIncomingValue(i)))
653 return 0;
654
655 // Okay, we can do the transformation: create the new PHI node.
656 PHINode *NewPN = new PHINode(I.getType(), I.getName());
657 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +0000658 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +0000659 InsertNewInstBefore(NewPN, *PN);
660
661 // Next, add all of the operands to the PHI.
662 if (I.getNumOperands() == 2) {
663 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +0000664 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000665 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
666 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
667 PN->getIncomingBlock(i));
668 }
669 } else {
670 assert(isa<CastInst>(I) && "Unary op should be a cast!");
671 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +0000672 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +0000673 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
674 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
675 PN->getIncomingBlock(i));
676 }
677 }
678 return ReplaceInstUsesWith(I, NewPN);
679}
680
Chris Lattner7e708292002-06-25 16:13:24 +0000681Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000682 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +0000683 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000684
Chris Lattner66331a42004-04-10 22:01:55 +0000685 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +0000686 // X + undef -> undef
687 if (isa<UndefValue>(RHS))
688 return ReplaceInstUsesWith(I, RHS);
689
Chris Lattner66331a42004-04-10 22:01:55 +0000690 // X + 0 --> X
691 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
692 RHSC->isNullValue())
693 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +0000694
Chris Lattner66331a42004-04-10 22:01:55 +0000695 // X + (signbit) --> X ^ signbit
696 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000697 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattner66331a42004-04-10 22:01:55 +0000698 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
Chris Lattnerf1580922004-11-05 04:45:43 +0000699 if (Val == (1ULL << (NumBits-1)))
Chris Lattner48595f12004-06-10 02:07:29 +0000700 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +0000701 }
Chris Lattner4e998b22004-09-29 05:07:12 +0000702
703 if (isa<PHINode>(LHS))
704 if (Instruction *NV = FoldOpIntoPhi(I))
705 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +0000706
707 ConstantInt *XorRHS;
708 Value *XorLHS;
709 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
710 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
711 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
712 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
713
714 uint64_t C0080Val = 1ULL << 31;
715 int64_t CFF80Val = -C0080Val;
716 unsigned Size = 32;
717 do {
718 if (TySizeBits > Size) {
719 bool Found = false;
720 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
721 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
722 if (RHSSExt == CFF80Val) {
723 if (XorRHS->getZExtValue() == C0080Val)
724 Found = true;
725 } else if (RHSZExt == C0080Val) {
726 if (XorRHS->getSExtValue() == CFF80Val)
727 Found = true;
728 }
729 if (Found) {
730 // This is a sign extend if the top bits are known zero.
731 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
732 Mask = ConstantExpr::getShl(Mask,
733 ConstantInt::get(Type::UByteTy, 64-TySizeBits-Size));
734 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
735 Size = 0; // Not a sign ext, but can't be any others either.
736 goto FoundSExt;
737 }
738 }
739 Size >>= 1;
740 C0080Val >>= Size;
741 CFF80Val >>= Size;
742 } while (Size >= 8);
743
744FoundSExt:
745 const Type *MiddleType = 0;
746 switch (Size) {
747 default: break;
748 case 32: MiddleType = Type::IntTy; break;
749 case 16: MiddleType = Type::ShortTy; break;
750 case 8: MiddleType = Type::SByteTy; break;
751 }
752 if (MiddleType) {
753 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
754 InsertNewInstBefore(NewTrunc, I);
755 return new CastInst(NewTrunc, I.getType());
756 }
757 }
Chris Lattner66331a42004-04-10 22:01:55 +0000758 }
Chris Lattnerb35dde12002-05-06 16:49:18 +0000759
Chris Lattner564a7272003-08-13 19:01:45 +0000760 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +0000761 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +0000762 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +0000763
764 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
765 if (RHSI->getOpcode() == Instruction::Sub)
766 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
767 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
768 }
769 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
770 if (LHSI->getOpcode() == Instruction::Sub)
771 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
772 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
773 }
Robert Bocchino71698282004-07-27 21:02:21 +0000774 }
Chris Lattnere92d2f42003-08-13 04:18:28 +0000775
Chris Lattner5c4afb92002-05-08 22:46:53 +0000776 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +0000777 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000778 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000779
780 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +0000781 if (!isa<Constant>(RHS))
782 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +0000783 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000784
Misha Brukmanfd939082005-04-21 23:48:37 +0000785
Chris Lattner50af16a2004-11-13 19:50:12 +0000786 ConstantInt *C2;
787 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
788 if (X == RHS) // X*C + X --> X * (C+1)
789 return BinaryOperator::createMul(RHS, AddOne(C2));
790
791 // X*C1 + X*C2 --> X * (C1+C2)
792 ConstantInt *C1;
793 if (X == dyn_castFoldableMul(RHS, C1))
794 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +0000795 }
796
797 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +0000798 if (dyn_castFoldableMul(RHS, C2) == LHS)
799 return BinaryOperator::createMul(LHS, AddOne(C2));
800
Chris Lattnerad3448c2003-02-18 19:57:07 +0000801
Chris Lattner564a7272003-08-13 19:01:45 +0000802 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000803 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +0000804 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +0000805
Chris Lattner6b032052003-10-02 15:11:26 +0000806 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000807 Value *X;
808 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
809 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
810 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +0000811 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000812
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000813 // (X & FF00) + xx00 -> (X+xx00) & FF00
814 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
815 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
816 if (Anded == CRHS) {
817 // See if all bits from the first bit set in the Add RHS up are included
818 // in the mask. First, get the rightmost bit.
819 uint64_t AddRHSV = CRHS->getRawValue();
820
821 // Form a mask of all bits from the lowest bit added through the top.
822 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattnerf52d6812005-04-24 17:46:05 +0000823 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000824
825 // See if the and mask includes all of these bits.
826 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +0000827
Chris Lattnerb99d6b12004-10-08 05:07:56 +0000828 if (AddRHSHighBits == AddRHSHighBitsAnd) {
829 // Okay, the xform is safe. Insert the new add pronto.
830 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
831 LHS->getName()), I);
832 return BinaryOperator::createAnd(NewAdd, C2);
833 }
834 }
835 }
836
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000837 // Try to fold constant add into select arguments.
838 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000839 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000840 return R;
Chris Lattner6b032052003-10-02 15:11:26 +0000841 }
842
Chris Lattner7e708292002-06-25 16:13:24 +0000843 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000844}
845
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000846// isSignBit - Return true if the value represented by the constant only has the
847// highest order bit set.
848static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000849 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +0000850 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +0000851}
852
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000853/// RemoveNoopCast - Strip off nonconverting casts from the value.
854///
855static Value *RemoveNoopCast(Value *V) {
856 if (CastInst *CI = dyn_cast<CastInst>(V)) {
857 const Type *CTy = CI->getType();
858 const Type *OpTy = CI->getOperand(0)->getType();
859 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +0000860 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000861 return RemoveNoopCast(CI->getOperand(0));
862 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
863 return RemoveNoopCast(CI->getOperand(0));
864 }
865 return V;
866}
867
Chris Lattner7e708292002-06-25 16:13:24 +0000868Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000869 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +0000870
Chris Lattner233f7dc2002-08-12 21:17:25 +0000871 if (Op0 == Op1) // sub X, X -> 0
872 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000873
Chris Lattner233f7dc2002-08-12 21:17:25 +0000874 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +0000875 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +0000876 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +0000877
Chris Lattnere87597f2004-10-16 18:11:37 +0000878 if (isa<UndefValue>(Op0))
879 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
880 if (isa<UndefValue>(Op1))
881 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
882
Chris Lattnerd65460f2003-11-05 01:06:05 +0000883 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
884 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +0000885 if (C->isAllOnesValue())
886 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +0000887
Chris Lattnerd65460f2003-11-05 01:06:05 +0000888 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +0000889 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +0000890 if (match(Op1, m_Not(m_Value(X))))
891 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +0000892 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +0000893 // -((uint)X >> 31) -> ((int)X >> 31)
894 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000895 if (C->isNullValue()) {
896 Value *NoopCastedRHS = RemoveNoopCast(Op1);
897 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +0000898 if (SI->getOpcode() == Instruction::Shr)
899 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
900 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000901 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +0000902 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000903 else
Chris Lattner5dd04022004-06-17 18:16:02 +0000904 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +0000905 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +0000906 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +0000907 // Ok, the transformation is safe. Insert a cast of the incoming
908 // value, then the new shift, then the new cast.
909 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
910 SI->getOperand(0)->getName());
911 Value *InV = InsertNewInstBefore(FirstCast, I);
912 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
913 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000914 if (NewShift->getType() == I.getType())
915 return NewShift;
916 else {
917 InV = InsertNewInstBefore(NewShift, I);
918 return new CastInst(NewShift, I.getType());
919 }
Chris Lattner9c290672004-03-12 23:53:13 +0000920 }
921 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +0000922 }
Chris Lattner2eefe512004-04-09 19:05:30 +0000923
924 // Try to fold constant sub into select arguments.
925 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +0000926 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +0000927 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +0000928
929 if (isa<PHINode>(Op0))
930 if (Instruction *NV = FoldOpIntoPhi(I))
931 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +0000932 }
933
Chris Lattner43d84d62005-04-07 16:15:25 +0000934 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
935 if (Op1I->getOpcode() == Instruction::Add &&
936 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +0000937 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +0000938 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +0000939 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +0000940 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +0000941 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
942 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
943 // C1-(X+C2) --> (C1-C2)-X
944 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
945 Op1I->getOperand(0));
946 }
Chris Lattner43d84d62005-04-07 16:15:25 +0000947 }
948
Chris Lattnerfd059242003-10-15 16:48:29 +0000949 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000950 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
951 // is not used by anyone else...
952 //
Chris Lattner0517e722004-02-02 20:09:56 +0000953 if (Op1I->getOpcode() == Instruction::Sub &&
954 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +0000955 // Swap the two operands of the subexpr...
956 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
957 Op1I->setOperand(0, IIOp1);
958 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +0000959
Chris Lattnera2881962003-02-18 19:28:33 +0000960 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +0000961 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +0000962 }
963
964 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
965 //
966 if (Op1I->getOpcode() == Instruction::And &&
967 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
968 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
969
Chris Lattnerf523d062004-06-09 05:08:07 +0000970 Value *NewNot =
971 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +0000972 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +0000973 }
Chris Lattnerad3448c2003-02-18 19:57:07 +0000974
Chris Lattner91ccc152004-10-06 15:08:25 +0000975 // -(X sdiv C) -> (X sdiv -C)
976 if (Op1I->getOpcode() == Instruction::Div)
977 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +0000978 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +0000979 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +0000980 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +0000981 ConstantExpr::getNeg(DivRHS));
982
Chris Lattnerad3448c2003-02-18 19:57:07 +0000983 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +0000984 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +0000985 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +0000986 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +0000987 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +0000988 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +0000989 }
Chris Lattner40371712002-05-09 01:29:19 +0000990 }
Chris Lattner43d84d62005-04-07 16:15:25 +0000991 }
Chris Lattnera2881962003-02-18 19:28:33 +0000992
Chris Lattner7edc8c22005-04-07 17:14:51 +0000993 if (!Op0->getType()->isFloatingPoint())
994 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
995 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000996 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
997 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
998 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
999 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00001000 } else if (Op0I->getOpcode() == Instruction::Sub) {
1001 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1002 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001003 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001004
Chris Lattner50af16a2004-11-13 19:50:12 +00001005 ConstantInt *C1;
1006 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1007 if (X == Op1) { // X*C - X --> X * (C-1)
1008 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1009 return BinaryOperator::createMul(Op1, CP1);
1010 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001011
Chris Lattner50af16a2004-11-13 19:50:12 +00001012 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1013 if (X == dyn_castFoldableMul(Op1, C2))
1014 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1015 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001016 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001017}
1018
Chris Lattner4cb170c2004-02-23 06:38:22 +00001019/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1020/// really just returns true if the most significant (sign) bit is set.
1021static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1022 if (RHS->getType()->isSigned()) {
1023 // True if source is LHS < 0 or LHS <= -1
1024 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1025 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1026 } else {
1027 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1028 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1029 // the size of the integer type.
1030 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +00001031 return RHSC->getValue() ==
1032 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001033 if (Opcode == Instruction::SetGT)
1034 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00001035 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001036 }
1037 return false;
1038}
1039
Chris Lattner7e708292002-06-25 16:13:24 +00001040Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001041 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00001042 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001043
Chris Lattnere87597f2004-10-16 18:11:37 +00001044 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1045 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1046
Chris Lattner233f7dc2002-08-12 21:17:25 +00001047 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00001048 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1049 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001050
1051 // ((X << C1)*C2) == (X * (C2 << C1))
1052 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1053 if (SI->getOpcode() == Instruction::Shl)
1054 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001055 return BinaryOperator::createMul(SI->getOperand(0),
1056 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001057
Chris Lattner515c97c2003-09-11 22:24:54 +00001058 if (CI->isNullValue())
1059 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1060 if (CI->equalsInt(1)) // X * 1 == X
1061 return ReplaceInstUsesWith(I, Op0);
1062 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00001063 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001064
Chris Lattner515c97c2003-09-11 22:24:54 +00001065 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001066 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1067 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00001068 return new ShiftInst(Instruction::Shl, Op0,
1069 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001070 }
Robert Bocchino71698282004-07-27 21:02:21 +00001071 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001072 if (Op1F->isNullValue())
1073 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00001074
Chris Lattnera2881962003-02-18 19:28:33 +00001075 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1076 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1077 if (Op1F->getValue() == 1.0)
1078 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1079 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001080
1081 // Try to fold constant mul into select arguments.
1082 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001083 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001084 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001085
1086 if (isa<PHINode>(Op0))
1087 if (Instruction *NV = FoldOpIntoPhi(I))
1088 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001089 }
1090
Chris Lattnera4f445b2003-03-10 23:23:04 +00001091 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1092 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001093 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001094
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001095 // If one of the operands of the multiply is a cast from a boolean value, then
1096 // we know the bool is either zero or one, so this is a 'masking' multiply.
1097 // See if we can simplify things based on how the boolean was originally
1098 // formed.
1099 CastInst *BoolCast = 0;
1100 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1101 if (CI->getOperand(0)->getType() == Type::BoolTy)
1102 BoolCast = CI;
1103 if (!BoolCast)
1104 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1105 if (CI->getOperand(0)->getType() == Type::BoolTy)
1106 BoolCast = CI;
1107 if (BoolCast) {
1108 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1109 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1110 const Type *SCOpTy = SCIOp0->getType();
1111
Chris Lattner4cb170c2004-02-23 06:38:22 +00001112 // If the setcc is true iff the sign bit of X is set, then convert this
1113 // multiply into a shift/and combination.
1114 if (isa<ConstantInt>(SCIOp1) &&
1115 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001116 // Shift the X value right to turn it into "all signbits".
1117 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00001118 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001119 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001120 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00001121 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1122 SCIOp0->getName()), I);
1123 }
1124
1125 Value *V =
1126 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1127 BoolCast->getOperand(0)->getName()+
1128 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001129
1130 // If the multiply type is not the same as the source type, sign extend
1131 // or truncate to the multiply type.
1132 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001133 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001134
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001135 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001136 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001137 }
1138 }
1139 }
1140
Chris Lattner7e708292002-06-25 16:13:24 +00001141 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001142}
1143
Chris Lattner7e708292002-06-25 16:13:24 +00001144Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001145 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001146
Chris Lattner857e8cd2004-12-12 21:48:58 +00001147 if (isa<UndefValue>(Op0)) // undef / X -> 0
1148 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1149 if (isa<UndefValue>(Op1))
1150 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1151
1152 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001153 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001154 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001155 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001156
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001157 // div X, -1 == -X
1158 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001159 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001160
Chris Lattner857e8cd2004-12-12 21:48:58 +00001161 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001162 if (LHS->getOpcode() == Instruction::Div)
1163 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001164 // (X / C1) / C2 -> X / (C1*C2)
1165 return BinaryOperator::createDiv(LHS->getOperand(0),
1166 ConstantExpr::getMul(RHS, LHSRHS));
1167 }
1168
Chris Lattnera2881962003-02-18 19:28:33 +00001169 // Check to see if this is an unsigned division with an exact power of 2,
1170 // if so, convert to a right shift.
1171 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1172 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001173 if (isPowerOf2_64(Val)) {
1174 uint64_t C = Log2_64(Val);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001175 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001176 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001177 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001178
Chris Lattnera052f822004-10-09 02:50:40 +00001179 // -X/C -> X/-C
1180 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001181 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001182 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1183
Chris Lattner857e8cd2004-12-12 21:48:58 +00001184 if (!RHS->isNullValue()) {
1185 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001186 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001187 return R;
1188 if (isa<PHINode>(Op0))
1189 if (Instruction *NV = FoldOpIntoPhi(I))
1190 return NV;
1191 }
Chris Lattnera2881962003-02-18 19:28:33 +00001192 }
1193
Chris Lattner857e8cd2004-12-12 21:48:58 +00001194 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1195 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1196 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1197 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1198 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1199 if (STO->getValue() == 0) { // Couldn't be this argument.
1200 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001201 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001202 } else if (SFO->getValue() == 0) {
Chris Lattnerf9c775c2005-06-16 04:55:52 +00001203 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001204 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001205 }
1206
Chris Lattnerbf70b832005-04-08 04:03:26 +00001207 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001208 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1209 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattnerbf70b832005-04-08 04:03:26 +00001210 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1211 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1212 TC, SI->getName()+".t");
1213 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001214
Chris Lattnerbf70b832005-04-08 04:03:26 +00001215 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1216 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1217 FC, SI->getName()+".f");
1218 FSI = InsertNewInstBefore(FSI, I);
1219 return new SelectInst(SI->getOperand(0), TSI, FSI);
1220 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001221 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001222
Chris Lattnera2881962003-02-18 19:28:33 +00001223 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001224 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001225 if (LHS->equalsInt(0))
1226 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1227
Chris Lattner3f5b8772002-05-06 16:14:14 +00001228 return 0;
1229}
1230
1231
Chris Lattner7e708292002-06-25 16:13:24 +00001232Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001233 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner5b73c082004-07-06 07:01:22 +00001234 if (I.getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001235 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00001236 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00001237 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00001238 // X % -Y -> X % Y
1239 AddUsesToWorkList(I);
1240 I.setOperand(1, RHSNeg);
1241 return &I;
1242 }
1243
Chris Lattner857e8cd2004-12-12 21:48:58 +00001244 if (isa<UndefValue>(Op0)) // undef % X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00001245 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner857e8cd2004-12-12 21:48:58 +00001246 if (isa<UndefValue>(Op1))
1247 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Chris Lattnere87597f2004-10-16 18:11:37 +00001248
Chris Lattner857e8cd2004-12-12 21:48:58 +00001249 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001250 if (RHS->equalsInt(1)) // X % 1 == 0
1251 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1252
1253 // Check to see if this is an unsigned remainder with an exact power of 2,
1254 // if so, convert to a bitwise and.
1255 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1256 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
Chris Lattner546516c2004-05-07 15:35:56 +00001257 if (!(Val & (Val-1))) // Power of 2
Chris Lattner857e8cd2004-12-12 21:48:58 +00001258 return BinaryOperator::createAnd(Op0,
1259 ConstantUInt::get(I.getType(), Val-1));
1260
1261 if (!RHS->isNullValue()) {
1262 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001263 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001264 return R;
1265 if (isa<PHINode>(Op0))
1266 if (Instruction *NV = FoldOpIntoPhi(I))
1267 return NV;
1268 }
Chris Lattnera2881962003-02-18 19:28:33 +00001269 }
1270
Chris Lattner857e8cd2004-12-12 21:48:58 +00001271 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1272 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1273 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1274 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1275 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1276 if (STO->getValue() == 0) { // Couldn't be this argument.
1277 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001278 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001279 } else if (SFO->getValue() == 0) {
1280 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001281 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001282 }
1283
1284 if (!(STO->getValue() & (STO->getValue()-1)) &&
1285 !(SFO->getValue() & (SFO->getValue()-1))) {
1286 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1287 SubOne(STO), SI->getName()+".t"), I);
1288 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1289 SubOne(SFO), SI->getName()+".f"), I);
1290 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1291 }
1292 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001293
Chris Lattnera2881962003-02-18 19:28:33 +00001294 // 0 % X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001295 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001296 if (LHS->equalsInt(0))
Chris Lattner233f7dc2002-08-12 21:17:25 +00001297 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1298
Chris Lattner3f5b8772002-05-06 16:14:14 +00001299 return 0;
1300}
1301
Chris Lattner8b170942002-08-09 23:47:40 +00001302// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001303static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001304 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1305 // Calculate -1 casted to the right type...
Chris Lattner484d3cf2005-04-24 06:59:08 +00001306 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001307 uint64_t Val = ~0ULL; // All ones
1308 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1309 return CU->getValue() == Val-1;
1310 }
1311
1312 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001313
Chris Lattner8b170942002-08-09 23:47:40 +00001314 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00001315 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001316 int64_t Val = INT64_MAX; // All ones
1317 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1318 return CS->getValue() == Val-1;
1319}
1320
1321// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001322static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001323 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1324 return CU->getValue() == 1;
1325
1326 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001327
1328 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00001329 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001330 int64_t Val = -1; // All ones
1331 Val <<= TypeBits-1; // Shift over to the right spot
1332 return CS->getValue() == Val+1;
1333}
1334
Chris Lattner457dd822004-06-09 07:59:58 +00001335// isOneBitSet - Return true if there is exactly one bit set in the specified
1336// constant.
1337static bool isOneBitSet(const ConstantInt *CI) {
1338 uint64_t V = CI->getRawValue();
1339 return V && (V & (V-1)) == 0;
1340}
1341
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001342#if 0 // Currently unused
1343// isLowOnes - Return true if the constant is of the form 0+1+.
1344static bool isLowOnes(const ConstantInt *CI) {
1345 uint64_t V = CI->getRawValue();
1346
1347 // There won't be bits set in parts that the type doesn't contain.
1348 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1349
1350 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1351 return U && V && (U & V) == 0;
1352}
1353#endif
1354
1355// isHighOnes - Return true if the constant is of the form 1+0+.
1356// This is the same as lowones(~X).
1357static bool isHighOnes(const ConstantInt *CI) {
1358 uint64_t V = ~CI->getRawValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00001359 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00001360
1361 // There won't be bits set in parts that the type doesn't contain.
1362 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1363
1364 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1365 return U && V && (U & V) == 0;
1366}
1367
1368
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001369/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1370/// are carefully arranged to allow folding of expressions such as:
1371///
1372/// (A < B) | (A > B) --> (A != B)
1373///
1374/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1375/// represents that the comparison is true if A == B, and bit value '1' is true
1376/// if A < B.
1377///
1378static unsigned getSetCondCode(const SetCondInst *SCI) {
1379 switch (SCI->getOpcode()) {
1380 // False -> 0
1381 case Instruction::SetGT: return 1;
1382 case Instruction::SetEQ: return 2;
1383 case Instruction::SetGE: return 3;
1384 case Instruction::SetLT: return 4;
1385 case Instruction::SetNE: return 5;
1386 case Instruction::SetLE: return 6;
1387 // True -> 7
1388 default:
1389 assert(0 && "Invalid SetCC opcode!");
1390 return 0;
1391 }
1392}
1393
1394/// getSetCCValue - This is the complement of getSetCondCode, which turns an
1395/// opcode and two operands into either a constant true or false, or a brand new
1396/// SetCC instruction.
1397static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1398 switch (Opcode) {
1399 case 0: return ConstantBool::False;
1400 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1401 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1402 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1403 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1404 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1405 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1406 case 7: return ConstantBool::True;
1407 default: assert(0 && "Illegal SetCCCode!"); return 0;
1408 }
1409}
1410
1411// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1412struct FoldSetCCLogical {
1413 InstCombiner &IC;
1414 Value *LHS, *RHS;
1415 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1416 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1417 bool shouldApply(Value *V) const {
1418 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1419 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1420 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1421 return false;
1422 }
1423 Instruction *apply(BinaryOperator &Log) const {
1424 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1425 if (SCI->getOperand(0) != LHS) {
1426 assert(SCI->getOperand(1) == LHS);
1427 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1428 }
1429
1430 unsigned LHSCode = getSetCondCode(SCI);
1431 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1432 unsigned Code;
1433 switch (Log.getOpcode()) {
1434 case Instruction::And: Code = LHSCode & RHSCode; break;
1435 case Instruction::Or: Code = LHSCode | RHSCode; break;
1436 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00001437 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001438 }
1439
1440 Value *RV = getSetCCValue(Code, LHS, RHS);
1441 if (Instruction *I = dyn_cast<Instruction>(RV))
1442 return I;
1443 // Otherwise, it's a constant boolean value...
1444 return IC.ReplaceInstUsesWith(Log, RV);
1445 }
1446};
1447
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001448// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1449// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1450// guaranteed to be either a shift instruction or a binary operator.
1451Instruction *InstCombiner::OptAndOp(Instruction *Op,
1452 ConstantIntegral *OpRHS,
1453 ConstantIntegral *AndRHS,
1454 BinaryOperator &TheAnd) {
1455 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00001456 Constant *Together = 0;
1457 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00001458 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00001459
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001460 switch (Op->getOpcode()) {
1461 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001462 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001463 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1464 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00001465 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001466 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001467 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001468 }
1469 break;
1470 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00001471 if (Together == AndRHS) // (X | C) & C --> C
1472 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001473
Chris Lattner6e7ba452005-01-01 16:22:27 +00001474 if (Op->hasOneUse() && Together != OpRHS) {
1475 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1476 std::string Op0Name = Op->getName(); Op->setName("");
1477 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1478 InsertNewInstBefore(Or, TheAnd);
1479 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001480 }
1481 break;
1482 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00001483 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001484 // Adding a one to a single bit bit-field should be turned into an XOR
1485 // of the bit. First thing to check is to see if this AND is with a
1486 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00001487 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001488
1489 // Clear bits that are not part of the constant.
Chris Lattnerf52d6812005-04-24 17:46:05 +00001490 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001491
1492 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00001493 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001494 // Ok, at this point, we know that we are masking the result of the
1495 // ADD down to exactly one bit. If the constant we are adding has
1496 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00001497 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001498
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001499 // Check to see if any bits below the one bit set in AndRHSV are set.
1500 if ((AddRHS & (AndRHSV-1)) == 0) {
1501 // If not, the only thing that can effect the output of the AND is
1502 // the bit specified by AndRHSV. If that bit is set, the effect of
1503 // the XOR is to toggle the bit. If it is clear, then the ADD has
1504 // no effect.
1505 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1506 TheAnd.setOperand(0, X);
1507 return &TheAnd;
1508 } else {
1509 std::string Name = Op->getName(); Op->setName("");
1510 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00001511 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001512 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00001513 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001514 }
1515 }
1516 }
1517 }
1518 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00001519
1520 case Instruction::Shl: {
1521 // We know that the AND will not produce any of the bits shifted in, so if
1522 // the anded constant includes them, clear them now!
1523 //
1524 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001525 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1526 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00001527
Chris Lattner0c967662004-09-24 15:21:34 +00001528 if (CI == ShlMask) { // Masking out bits that the shift already masks
1529 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1530 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00001531 TheAnd.setOperand(1, CI);
1532 return &TheAnd;
1533 }
1534 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00001535 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001536 case Instruction::Shr:
1537 // We know that the AND will not produce any of the bits shifted in, so if
1538 // the anded constant includes them, clear them now! This only applies to
1539 // unsigned shifts, because a signed shr may bring in set bits!
1540 //
1541 if (AndRHS->getType()->isUnsigned()) {
1542 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00001543 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1544 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1545
1546 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1547 return ReplaceInstUsesWith(TheAnd, Op);
1548 } else if (CI != AndRHS) {
1549 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00001550 return &TheAnd;
1551 }
Chris Lattner0c967662004-09-24 15:21:34 +00001552 } else { // Signed shr.
1553 // See if this is shifting in some sign extension, then masking it out
1554 // with an and.
1555 if (Op->hasOneUse()) {
1556 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1557 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1558 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00001559 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00001560 // Make the argument unsigned.
1561 Value *ShVal = Op->getOperand(0);
1562 ShVal = InsertCastBefore(ShVal,
1563 ShVal->getType()->getUnsignedVersion(),
1564 TheAnd);
1565 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1566 OpRHS, Op->getName()),
1567 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00001568 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1569 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1570 TheAnd.getName()),
1571 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00001572 return new CastInst(ShVal, Op->getType());
1573 }
1574 }
Chris Lattner62a355c2003-09-19 19:05:02 +00001575 }
1576 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001577 }
1578 return 0;
1579}
1580
Chris Lattner8b170942002-08-09 23:47:40 +00001581
Chris Lattnera96879a2004-09-29 17:40:11 +00001582/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1583/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1584/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1585/// insert new instructions.
1586Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1587 bool Inside, Instruction &IB) {
1588 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1589 "Lo is not <= Hi in range emission code!");
1590 if (Inside) {
1591 if (Lo == Hi) // Trivially false.
1592 return new SetCondInst(Instruction::SetNE, V, V);
1593 if (cast<ConstantIntegral>(Lo)->isMinValue())
1594 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00001595
Chris Lattnera96879a2004-09-29 17:40:11 +00001596 Constant *AddCST = ConstantExpr::getNeg(Lo);
1597 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1598 InsertNewInstBefore(Add, IB);
1599 // Convert to unsigned for the comparison.
1600 const Type *UnsType = Add->getType()->getUnsignedVersion();
1601 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1602 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1603 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1604 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1605 }
1606
1607 if (Lo == Hi) // Trivially true.
1608 return new SetCondInst(Instruction::SetEQ, V, V);
1609
1610 Hi = SubOne(cast<ConstantInt>(Hi));
1611 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1612 return new SetCondInst(Instruction::SetGT, V, Hi);
1613
1614 // Emit X-Lo > Hi-Lo-1
1615 Constant *AddCST = ConstantExpr::getNeg(Lo);
1616 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1617 InsertNewInstBefore(Add, IB);
1618 // Convert to unsigned for the comparison.
1619 const Type *UnsType = Add->getType()->getUnsignedVersion();
1620 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1621 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1622 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1623 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1624}
1625
Chris Lattner7203e152005-09-18 07:22:02 +00001626// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1627// any number of 0s on either side. The 1s are allowed to wrap from LSB to
1628// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1629// not, since all 1s are not contiguous.
1630static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1631 uint64_t V = Val->getRawValue();
1632 if (!isShiftedMask_64(V)) return false;
1633
1634 // look for the first zero bit after the run of ones
1635 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1636 // look for the first non-zero bit
1637 ME = 64-CountLeadingZeros_64(V);
1638 return true;
1639}
1640
1641
1642
1643/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1644/// where isSub determines whether the operator is a sub. If we can fold one of
1645/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00001646///
1647/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1648/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1649/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1650///
1651/// return (A +/- B).
1652///
1653Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1654 ConstantIntegral *Mask, bool isSub,
1655 Instruction &I) {
1656 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1657 if (!LHSI || LHSI->getNumOperands() != 2 ||
1658 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1659
1660 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1661
1662 switch (LHSI->getOpcode()) {
1663 default: return 0;
1664 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00001665 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1666 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1667 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1668 break;
1669
1670 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1671 // part, we don't need any explicit masks to take them out of A. If that
1672 // is all N is, ignore it.
1673 unsigned MB, ME;
1674 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1675 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1676 Mask = ConstantExpr::getUShr(Mask,
1677 ConstantInt::get(Type::UByteTy,
1678 (64-MB+1)));
1679 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1680 break;
1681 }
1682 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00001683 return 0;
1684 case Instruction::Or:
1685 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00001686 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1687 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1688 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00001689 break;
1690 return 0;
1691 }
1692
1693 Instruction *New;
1694 if (isSub)
1695 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1696 else
1697 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1698 return InsertNewInstBefore(New, I);
1699}
1700
Chris Lattnera96879a2004-09-29 17:40:11 +00001701
Chris Lattner7e708292002-06-25 16:13:24 +00001702Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001703 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001704 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001705
Chris Lattnere87597f2004-10-16 18:11:37 +00001706 if (isa<UndefValue>(Op1)) // X & undef -> 0
1707 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1708
Chris Lattner6e7ba452005-01-01 16:22:27 +00001709 // and X, X = X
1710 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00001711 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001712
Chris Lattner6e7ba452005-01-01 16:22:27 +00001713 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnerad1e3022005-01-23 20:26:55 +00001714 // and X, -1 == X
1715 if (AndRHS->isAllOnesValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00001716 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001717
Chris Lattner6e7ba452005-01-01 16:22:27 +00001718 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1719 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1720
1721 // If the mask is not masking out any bits, there is no reason to do the
1722 // and in the first place.
Misha Brukmanfd939082005-04-21 23:48:37 +00001723 ConstantIntegral *NotAndRHS =
Chris Lattnerad1e3022005-01-23 20:26:55 +00001724 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
Misha Brukmanfd939082005-04-21 23:48:37 +00001725 if (MaskedValueIsZero(Op0, NotAndRHS))
Chris Lattnerad1e3022005-01-23 20:26:55 +00001726 return ReplaceInstUsesWith(I, Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001727
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001728 // Optimize a variety of ((val OP C1) & C2) combinations...
1729 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1730 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001731 Value *Op0LHS = Op0I->getOperand(0);
1732 Value *Op0RHS = Op0I->getOperand(1);
1733 switch (Op0I->getOpcode()) {
1734 case Instruction::Xor:
1735 case Instruction::Or:
1736 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1737 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1738 if (MaskedValueIsZero(Op0LHS, AndRHS))
Misha Brukmanfd939082005-04-21 23:48:37 +00001739 return BinaryOperator::createAnd(Op0RHS, AndRHS);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001740 if (MaskedValueIsZero(Op0RHS, AndRHS))
Misha Brukmanfd939082005-04-21 23:48:37 +00001741 return BinaryOperator::createAnd(Op0LHS, AndRHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00001742
1743 // If the mask is only needed on one incoming arm, push it up.
1744 if (Op0I->hasOneUse()) {
1745 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1746 // Not masking anything out for the LHS, move to RHS.
1747 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1748 Op0RHS->getName()+".masked");
1749 InsertNewInstBefore(NewRHS, I);
1750 return BinaryOperator::create(
1751 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00001752 }
Chris Lattnerad1e3022005-01-23 20:26:55 +00001753 if (!isa<Constant>(NotAndRHS) &&
1754 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1755 // Not masking anything out for the RHS, move to LHS.
1756 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1757 Op0LHS->getName()+".masked");
1758 InsertNewInstBefore(NewLHS, I);
1759 return BinaryOperator::create(
1760 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1761 }
1762 }
1763
Chris Lattner6e7ba452005-01-01 16:22:27 +00001764 break;
1765 case Instruction::And:
1766 // (X & V) & C2 --> 0 iff (V & C2) == 0
1767 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1768 MaskedValueIsZero(Op0RHS, AndRHS))
1769 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1770 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00001771 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00001772 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1773 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1774 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1775 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1776 return BinaryOperator::createAnd(V, AndRHS);
1777 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1778 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00001779 break;
1780
1781 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00001782 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1783 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1784 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1785 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1786 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00001787 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001788 }
1789
Chris Lattner58403262003-07-23 19:25:52 +00001790 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001791 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00001792 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001793 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1794 const Type *SrcTy = CI->getOperand(0)->getType();
1795
Chris Lattner2b83af22005-08-07 07:03:10 +00001796 // If this is an integer truncation or change from signed-to-unsigned, and
1797 // if the source is an and/or with immediate, transform it. This
1798 // frequently occurs for bitfield accesses.
1799 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1800 if (SrcTy->getPrimitiveSizeInBits() >=
1801 I.getType()->getPrimitiveSizeInBits() &&
1802 CastOp->getNumOperands() == 2)
1803 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1804 if (CastOp->getOpcode() == Instruction::And) {
1805 // Change: and (cast (and X, C1) to T), C2
1806 // into : and (cast X to T), trunc(C1)&C2
1807 // This will folds the two ands together, which may allow other
1808 // simplifications.
1809 Instruction *NewCast =
1810 new CastInst(CastOp->getOperand(0), I.getType(),
1811 CastOp->getName()+".shrunk");
1812 NewCast = InsertNewInstBefore(NewCast, I);
1813
1814 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1815 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1816 return BinaryOperator::createAnd(NewCast, C3);
1817 } else if (CastOp->getOpcode() == Instruction::Or) {
1818 // Change: and (cast (or X, C1) to T), C2
1819 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1820 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1821 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1822 return ReplaceInstUsesWith(I, AndRHS);
1823 }
1824 }
1825
1826
Chris Lattner6e7ba452005-01-01 16:22:27 +00001827 // If this is an integer sign or zero extension instruction.
1828 if (SrcTy->isIntegral() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00001829 SrcTy->getPrimitiveSizeInBits() <
1830 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001831
1832 if (SrcTy->isUnsigned()) {
1833 // See if this and is clearing out bits that are known to be zero
1834 // anyway (due to the zero extension).
1835 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1836 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1837 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1838 if (Result == Mask) // The "and" isn't doing anything, remove it.
1839 return ReplaceInstUsesWith(I, CI);
1840 if (Result != AndRHS) { // Reduce the and RHS constant.
1841 I.setOperand(1, Result);
1842 return &I;
1843 }
1844
1845 } else {
1846 if (CI->hasOneUse() && SrcTy->isInteger()) {
1847 // We can only do this if all of the sign bits brought in are masked
1848 // out. Compute this by first getting 0000011111, then inverting
1849 // it.
1850 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1851 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1852 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1853 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1854 // If the and is clearing all of the sign bits, change this to a
1855 // zero extension cast. To do this, cast the cast input to
1856 // unsigned, then to the requested size.
1857 Value *CastOp = CI->getOperand(0);
1858 Instruction *NC =
1859 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1860 CI->getName()+".uns");
1861 NC = InsertNewInstBefore(NC, I);
1862 // Finally, insert a replacement for CI.
1863 NC = new CastInst(NC, CI->getType(), CI->getName());
1864 CI->setName("");
1865 NC = InsertNewInstBefore(NC, I);
1866 WorkList.push_back(CI); // Delete CI later.
1867 I.setOperand(0, NC);
1868 return &I; // The AND operand was modified.
1869 }
1870 }
1871 }
1872 }
Chris Lattner06782f82003-07-23 19:36:21 +00001873 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001874
1875 // Try to fold constant and into select arguments.
1876 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001877 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001878 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001879 if (isa<PHINode>(Op0))
1880 if (Instruction *NV = FoldOpIntoPhi(I))
1881 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001882 }
1883
Chris Lattner8d969642003-03-10 23:06:50 +00001884 Value *Op0NotVal = dyn_castNotVal(Op0);
1885 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001886
Chris Lattner5b62aa72004-06-18 06:07:51 +00001887 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1888 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1889
Misha Brukmancb6267b2004-07-30 12:50:08 +00001890 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00001891 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00001892 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1893 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00001894 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00001895 return BinaryOperator::createNot(Or);
1896 }
1897
Chris Lattner955f3312004-09-28 21:48:02 +00001898 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1899 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00001900 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1901 return R;
1902
Chris Lattner955f3312004-09-28 21:48:02 +00001903 Value *LHSVal, *RHSVal;
1904 ConstantInt *LHSCst, *RHSCst;
1905 Instruction::BinaryOps LHSCC, RHSCC;
1906 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1907 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1908 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1909 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00001910 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00001911 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1912 // Ensure that the larger constant is on the RHS.
1913 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1914 SetCondInst *LHS = cast<SetCondInst>(Op0);
1915 if (cast<ConstantBool>(Cmp)->getValue()) {
1916 std::swap(LHS, RHS);
1917 std::swap(LHSCst, RHSCst);
1918 std::swap(LHSCC, RHSCC);
1919 }
1920
1921 // At this point, we know we have have two setcc instructions
1922 // comparing a value against two constants and and'ing the result
1923 // together. Because of the above check, we know that we only have
1924 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1925 // FoldSetCCLogical check above), that the two constants are not
1926 // equal.
1927 assert(LHSCst != RHSCst && "Compares not folded above?");
1928
1929 switch (LHSCC) {
1930 default: assert(0 && "Unknown integer condition code!");
1931 case Instruction::SetEQ:
1932 switch (RHSCC) {
1933 default: assert(0 && "Unknown integer condition code!");
1934 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1935 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1936 return ReplaceInstUsesWith(I, ConstantBool::False);
1937 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1938 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1939 return ReplaceInstUsesWith(I, LHS);
1940 }
1941 case Instruction::SetNE:
1942 switch (RHSCC) {
1943 default: assert(0 && "Unknown integer condition code!");
1944 case Instruction::SetLT:
1945 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1946 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1947 break; // (X != 13 & X < 15) -> no change
1948 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1949 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1950 return ReplaceInstUsesWith(I, RHS);
1951 case Instruction::SetNE:
1952 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1953 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1954 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1955 LHSVal->getName()+".off");
1956 InsertNewInstBefore(Add, I);
1957 const Type *UnsType = Add->getType()->getUnsignedVersion();
1958 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1959 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1960 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1961 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1962 }
1963 break; // (X != 13 & X != 15) -> no change
1964 }
1965 break;
1966 case Instruction::SetLT:
1967 switch (RHSCC) {
1968 default: assert(0 && "Unknown integer condition code!");
1969 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1970 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1971 return ReplaceInstUsesWith(I, ConstantBool::False);
1972 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1973 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1974 return ReplaceInstUsesWith(I, LHS);
1975 }
1976 case Instruction::SetGT:
1977 switch (RHSCC) {
1978 default: assert(0 && "Unknown integer condition code!");
1979 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1980 return ReplaceInstUsesWith(I, LHS);
1981 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1982 return ReplaceInstUsesWith(I, RHS);
1983 case Instruction::SetNE:
1984 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1985 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1986 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00001987 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1988 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00001989 }
1990 }
1991 }
1992 }
1993
Chris Lattner7e708292002-06-25 16:13:24 +00001994 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00001995}
1996
Chris Lattner7e708292002-06-25 16:13:24 +00001997Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001998 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001999 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002000
Chris Lattnere87597f2004-10-16 18:11:37 +00002001 if (isa<UndefValue>(Op1))
2002 return ReplaceInstUsesWith(I, // X | undef -> -1
2003 ConstantIntegral::getAllOnesValue(I.getType()));
2004
Chris Lattner3f5b8772002-05-06 16:14:14 +00002005 // or X, X = X or X, 0 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00002006 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2007 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002008
2009 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002010 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00002011 // If X is known to only contain bits that already exist in RHS, just
2012 // replace this instruction with RHS directly.
2013 if (MaskedValueIsZero(Op0,
2014 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2015 return ReplaceInstUsesWith(I, RHS);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002016
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002017 ConstantInt *C1; Value *X;
2018 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2019 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002020 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2021 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002022 InsertNewInstBefore(Or, I);
2023 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2024 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002025
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002026 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2027 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2028 std::string Op0Name = Op0->getName(); Op0->setName("");
2029 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2030 InsertNewInstBefore(Or, I);
2031 return BinaryOperator::createXor(Or,
2032 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002033 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002034
2035 // Try to fold constant and into select arguments.
2036 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002037 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002038 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002039 if (isa<PHINode>(Op0))
2040 if (Instruction *NV = FoldOpIntoPhi(I))
2041 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002042 }
2043
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002044 Value *A, *B; ConstantInt *C1, *C2;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002045
2046 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2047 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2048 return ReplaceInstUsesWith(I, Op1);
2049 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2050 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2051 return ReplaceInstUsesWith(I, Op0);
2052
Chris Lattner6e4c6492005-05-09 04:58:36 +00002053 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2054 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2055 MaskedValueIsZero(Op1, C1)) {
2056 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2057 Op0->setName("");
2058 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2059 }
2060
2061 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2062 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2063 MaskedValueIsZero(Op0, C1)) {
2064 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2065 Op0->setName("");
2066 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2067 }
2068
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002069 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002070 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002071 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2072
2073 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2074 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2075
2076
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002077 // If we have: ((V + N) & C1) | (V & C2)
2078 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2079 // replace with V+N.
2080 if (C1 == ConstantExpr::getNot(C2)) {
2081 Value *V1, *V2;
2082 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2083 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2084 // Add commutes, try both ways.
2085 if (V1 == B && MaskedValueIsZero(V2, C2))
2086 return ReplaceInstUsesWith(I, A);
2087 if (V2 == B && MaskedValueIsZero(V1, C2))
2088 return ReplaceInstUsesWith(I, A);
2089 }
2090 // Or commutes, try both ways.
2091 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2092 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2093 // Add commutes, try both ways.
2094 if (V1 == A && MaskedValueIsZero(V2, C1))
2095 return ReplaceInstUsesWith(I, B);
2096 if (V2 == A && MaskedValueIsZero(V1, C1))
2097 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002098 }
2099 }
2100 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002101
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002102 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2103 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00002104 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002105 ConstantIntegral::getAllOnesValue(I.getType()));
2106 } else {
2107 A = 0;
2108 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002109 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002110 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2111 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00002112 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002113 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00002114
Misha Brukmancb6267b2004-07-30 12:50:08 +00002115 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002116 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2117 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2118 I.getName()+".demorgan"), I);
2119 return BinaryOperator::createNot(And);
2120 }
Chris Lattnera27231a2003-03-10 23:13:59 +00002121 }
Chris Lattnera2881962003-02-18 19:28:33 +00002122
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002123 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002124 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002125 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2126 return R;
2127
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002128 Value *LHSVal, *RHSVal;
2129 ConstantInt *LHSCst, *RHSCst;
2130 Instruction::BinaryOps LHSCC, RHSCC;
2131 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2132 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2133 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2134 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002135 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002136 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2137 // Ensure that the larger constant is on the RHS.
2138 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2139 SetCondInst *LHS = cast<SetCondInst>(Op0);
2140 if (cast<ConstantBool>(Cmp)->getValue()) {
2141 std::swap(LHS, RHS);
2142 std::swap(LHSCst, RHSCst);
2143 std::swap(LHSCC, RHSCC);
2144 }
2145
2146 // At this point, we know we have have two setcc instructions
2147 // comparing a value against two constants and or'ing the result
2148 // together. Because of the above check, we know that we only have
2149 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2150 // FoldSetCCLogical check above), that the two constants are not
2151 // equal.
2152 assert(LHSCst != RHSCst && "Compares not folded above?");
2153
2154 switch (LHSCC) {
2155 default: assert(0 && "Unknown integer condition code!");
2156 case Instruction::SetEQ:
2157 switch (RHSCC) {
2158 default: assert(0 && "Unknown integer condition code!");
2159 case Instruction::SetEQ:
2160 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2161 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2162 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2163 LHSVal->getName()+".off");
2164 InsertNewInstBefore(Add, I);
2165 const Type *UnsType = Add->getType()->getUnsignedVersion();
2166 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2167 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2168 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2169 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2170 }
2171 break; // (X == 13 | X == 15) -> no change
2172
Chris Lattner240d6f42005-04-19 06:04:18 +00002173 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2174 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002175 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2176 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2177 return ReplaceInstUsesWith(I, RHS);
2178 }
2179 break;
2180 case Instruction::SetNE:
2181 switch (RHSCC) {
2182 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002183 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2184 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2185 return ReplaceInstUsesWith(I, LHS);
2186 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00002187 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002188 return ReplaceInstUsesWith(I, ConstantBool::True);
2189 }
2190 break;
2191 case Instruction::SetLT:
2192 switch (RHSCC) {
2193 default: assert(0 && "Unknown integer condition code!");
2194 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2195 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00002196 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2197 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002198 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2199 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2200 return ReplaceInstUsesWith(I, RHS);
2201 }
2202 break;
2203 case Instruction::SetGT:
2204 switch (RHSCC) {
2205 default: assert(0 && "Unknown integer condition code!");
2206 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2207 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2208 return ReplaceInstUsesWith(I, LHS);
2209 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2210 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2211 return ReplaceInstUsesWith(I, ConstantBool::True);
2212 }
2213 }
2214 }
2215 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002216
Chris Lattner7e708292002-06-25 16:13:24 +00002217 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002218}
2219
Chris Lattnerc317d392004-02-16 01:20:27 +00002220// XorSelf - Implements: X ^ X --> 0
2221struct XorSelf {
2222 Value *RHS;
2223 XorSelf(Value *rhs) : RHS(rhs) {}
2224 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2225 Instruction *apply(BinaryOperator &Xor) const {
2226 return &Xor;
2227 }
2228};
Chris Lattner3f5b8772002-05-06 16:14:14 +00002229
2230
Chris Lattner7e708292002-06-25 16:13:24 +00002231Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002232 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002233 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002234
Chris Lattnere87597f2004-10-16 18:11:37 +00002235 if (isa<UndefValue>(Op1))
2236 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2237
Chris Lattnerc317d392004-02-16 01:20:27 +00002238 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2239 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2240 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00002241 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00002242 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002243
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002244 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner8b170942002-08-09 23:47:40 +00002245 // xor X, 0 == X
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002246 if (RHS->isNullValue())
Chris Lattner233f7dc2002-08-12 21:17:25 +00002247 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8b170942002-08-09 23:47:40 +00002248
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002249 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00002250 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002251 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00002252 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00002253 return new SetCondInst(SCI->getInverseCondition(),
2254 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002255
Chris Lattnerd65460f2003-11-05 01:06:05 +00002256 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002257 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2258 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00002259 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2260 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002261 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00002262 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002263 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00002264
2265 // ~(~X & Y) --> (X | ~Y)
2266 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2267 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2268 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2269 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00002270 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00002271 Op0I->getOperand(1)->getName()+".not");
2272 InsertNewInstBefore(NotY, I);
2273 return BinaryOperator::createOr(Op0NotVal, NotY);
2274 }
2275 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002276
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002277 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002278 switch (Op0I->getOpcode()) {
2279 case Instruction::Add:
Chris Lattner689d24b2003-11-04 23:37:10 +00002280 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002281 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00002282 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2283 return BinaryOperator::createSub(
2284 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002285 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00002286 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002287 }
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002288 break;
2289 case Instruction::And:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002290 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
Chris Lattner48595f12004-06-10 02:07:29 +00002291 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2292 return BinaryOperator::createOr(Op0, RHS);
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002293 break;
2294 case Instruction::Or:
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002295 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
Chris Lattner48595f12004-06-10 02:07:29 +00002296 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
Chris Lattner448c3232004-06-10 02:12:35 +00002297 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002298 break;
2299 default: break;
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002300 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002301 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002302
2303 // Try to fold constant and into select arguments.
2304 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002305 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002306 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002307 if (isa<PHINode>(Op0))
2308 if (Instruction *NV = FoldOpIntoPhi(I))
2309 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002310 }
2311
Chris Lattner8d969642003-03-10 23:06:50 +00002312 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002313 if (X == Op1)
2314 return ReplaceInstUsesWith(I,
2315 ConstantIntegral::getAllOnesValue(I.getType()));
2316
Chris Lattner8d969642003-03-10 23:06:50 +00002317 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002318 if (X == Op0)
2319 return ReplaceInstUsesWith(I,
2320 ConstantIntegral::getAllOnesValue(I.getType()));
2321
Chris Lattnercb40a372003-03-10 18:24:17 +00002322 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00002323 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002324 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2325 cast<BinaryOperator>(Op1I)->swapOperands();
2326 I.swapOperands();
2327 std::swap(Op0, Op1);
2328 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2329 I.swapOperands();
2330 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002331 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002332 } else if (Op1I->getOpcode() == Instruction::Xor) {
2333 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2334 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2335 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2336 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2337 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002338
2339 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00002340 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002341 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2342 cast<BinaryOperator>(Op0I)->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00002343 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattnerf523d062004-06-09 05:08:07 +00002344 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2345 Op1->getName()+".not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002346 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00002347 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002348 } else if (Op0I->getOpcode() == Instruction::Xor) {
2349 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2350 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2351 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2352 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattnercb40a372003-03-10 18:24:17 +00002353 }
2354
Chris Lattner14840892004-08-01 19:42:59 +00002355 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002356 Value *A, *B; ConstantInt *C1, *C2;
2357 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2358 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
Chris Lattner14840892004-08-01 19:42:59 +00002359 ConstantExpr::getAnd(C1, C2)->isNullValue())
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002360 return BinaryOperator::createOr(Op0, Op1);
Chris Lattnerc8802d22003-03-11 00:12:48 +00002361
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002362 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2363 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2364 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2365 return R;
2366
Chris Lattner7e708292002-06-25 16:13:24 +00002367 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002368}
2369
Chris Lattnera96879a2004-09-29 17:40:11 +00002370/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2371/// overflowed for this type.
2372static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2373 ConstantInt *In2) {
2374 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2375 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2376}
2377
2378static bool isPositive(ConstantInt *C) {
2379 return cast<ConstantSInt>(C)->getValue() >= 0;
2380}
2381
2382/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2383/// overflowed for this type.
2384static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2385 ConstantInt *In2) {
2386 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2387
2388 if (In1->getType()->isUnsigned())
2389 return cast<ConstantUInt>(Result)->getValue() <
2390 cast<ConstantUInt>(In1)->getValue();
2391 if (isPositive(In1) != isPositive(In2))
2392 return false;
2393 if (isPositive(In1))
2394 return cast<ConstantSInt>(Result)->getValue() <
2395 cast<ConstantSInt>(In1)->getValue();
2396 return cast<ConstantSInt>(Result)->getValue() >
2397 cast<ConstantSInt>(In1)->getValue();
2398}
2399
Chris Lattner574da9b2005-01-13 20:14:25 +00002400/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2401/// code necessary to compute the offset from the base pointer (without adding
2402/// in the base pointer). Return the result as a signed integer of intptr size.
2403static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2404 TargetData &TD = IC.getTargetData();
2405 gep_type_iterator GTI = gep_type_begin(GEP);
2406 const Type *UIntPtrTy = TD.getIntPtrType();
2407 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2408 Value *Result = Constant::getNullValue(SIntPtrTy);
2409
2410 // Build a mask for high order bits.
2411 uint64_t PtrSizeMask = ~0ULL;
2412 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2413
Chris Lattner574da9b2005-01-13 20:14:25 +00002414 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2415 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00002416 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00002417 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2418 SIntPtrTy);
2419 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2420 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002421 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00002422 Scale = ConstantExpr::getMul(OpC, Scale);
2423 if (Constant *RC = dyn_cast<Constant>(Result))
2424 Result = ConstantExpr::getAdd(RC, Scale);
2425 else {
2426 // Emit an add instruction.
2427 Result = IC.InsertNewInstBefore(
2428 BinaryOperator::createAdd(Result, Scale,
2429 GEP->getName()+".offs"), I);
2430 }
2431 }
2432 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00002433 // Convert to correct type.
2434 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2435 Op->getName()+".c"), I);
2436 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002437 // We'll let instcombine(mul) convert this to a shl if possible.
2438 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2439 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00002440
2441 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00002442 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00002443 GEP->getName()+".offs"), I);
2444 }
2445 }
2446 return Result;
2447}
2448
2449/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2450/// else. At this point we know that the GEP is on the LHS of the comparison.
2451Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2452 Instruction::BinaryOps Cond,
2453 Instruction &I) {
2454 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00002455
2456 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2457 if (isa<PointerType>(CI->getOperand(0)->getType()))
2458 RHS = CI->getOperand(0);
2459
Chris Lattner574da9b2005-01-13 20:14:25 +00002460 Value *PtrBase = GEPLHS->getOperand(0);
2461 if (PtrBase == RHS) {
2462 // As an optimization, we don't actually have to compute the actual value of
2463 // OFFSET if this is a seteq or setne comparison, just return whether each
2464 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002465 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2466 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002467 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2468 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00002469 bool EmitIt = true;
2470 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2471 if (isa<UndefValue>(C)) // undef index -> undef.
2472 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2473 if (C->isNullValue())
2474 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00002475 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2476 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00002477 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00002478 return ReplaceInstUsesWith(I, // No comparison is needed here.
2479 ConstantBool::get(Cond == Instruction::SetNE));
2480 }
2481
2482 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00002483 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00002484 new SetCondInst(Cond, GEPLHS->getOperand(i),
2485 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2486 if (InVal == 0)
2487 InVal = Comp;
2488 else {
2489 InVal = InsertNewInstBefore(InVal, I);
2490 InsertNewInstBefore(Comp, I);
2491 if (Cond == Instruction::SetNE) // True if any are unequal
2492 InVal = BinaryOperator::createOr(InVal, Comp);
2493 else // True if all are equal
2494 InVal = BinaryOperator::createAnd(InVal, Comp);
2495 }
2496 }
2497 }
2498
2499 if (InVal)
2500 return InVal;
2501 else
2502 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2503 ConstantBool::get(Cond == Instruction::SetEQ));
2504 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002505
2506 // Only lower this if the setcc is the only user of the GEP or if we expect
2507 // the result to fold to a constant!
2508 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2509 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2510 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2511 return new SetCondInst(Cond, Offset,
2512 Constant::getNullValue(Offset->getType()));
2513 }
2514 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00002515 // If the base pointers are different, but the indices are the same, just
2516 // compare the base pointer.
2517 if (PtrBase != GEPRHS->getOperand(0)) {
2518 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00002519 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00002520 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00002521 if (IndicesTheSame)
2522 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2523 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2524 IndicesTheSame = false;
2525 break;
2526 }
2527
2528 // If all indices are the same, just compare the base pointers.
2529 if (IndicesTheSame)
2530 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2531 GEPRHS->getOperand(0));
2532
2533 // Otherwise, the base pointers are different and the indices are
2534 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00002535 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00002536 }
Chris Lattner574da9b2005-01-13 20:14:25 +00002537
Chris Lattnere9d782b2005-01-13 22:25:21 +00002538 // If one of the GEPs has all zero indices, recurse.
2539 bool AllZeros = true;
2540 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2541 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2542 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2543 AllZeros = false;
2544 break;
2545 }
2546 if (AllZeros)
2547 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2548 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002549
2550 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00002551 AllZeros = true;
2552 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2553 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2554 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2555 AllZeros = false;
2556 break;
2557 }
2558 if (AllZeros)
2559 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2560
Chris Lattner4401c9c2005-01-14 00:20:05 +00002561 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2562 // If the GEPs only differ by one index, compare it.
2563 unsigned NumDifferences = 0; // Keep track of # differences.
2564 unsigned DiffOperand = 0; // The operand that differs.
2565 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2566 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00002567 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2568 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002569 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00002570 NumDifferences = 2;
2571 break;
2572 } else {
2573 if (NumDifferences++) break;
2574 DiffOperand = i;
2575 }
2576 }
2577
2578 if (NumDifferences == 0) // SAME GEP?
2579 return ReplaceInstUsesWith(I, // No comparison is needed here.
2580 ConstantBool::get(Cond == Instruction::SetEQ));
2581 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00002582 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2583 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00002584
2585 // Convert the operands to signed values to make sure to perform a
2586 // signed comparison.
2587 const Type *NewTy = LHSV->getType()->getSignedVersion();
2588 if (LHSV->getType() != NewTy)
2589 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2590 LHSV->getName()), I);
2591 if (RHSV->getType() != NewTy)
2592 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2593 RHSV->getName()), I);
2594 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00002595 }
2596 }
2597
Chris Lattner574da9b2005-01-13 20:14:25 +00002598 // Only lower this if the setcc is the only user of the GEP or if we expect
2599 // the result to fold to a constant!
2600 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2601 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2602 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2603 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2604 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2605 return new SetCondInst(Cond, L, R);
2606 }
2607 }
2608 return 0;
2609}
2610
2611
Chris Lattner484d3cf2005-04-24 06:59:08 +00002612Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002613 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00002614 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2615 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00002616
2617 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00002618 if (Op0 == Op1)
2619 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00002620
Chris Lattnere87597f2004-10-16 18:11:37 +00002621 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2622 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2623
Chris Lattner711b3402004-11-14 07:33:16 +00002624 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2625 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00002626 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2627 isa<ConstantPointerNull>(Op0)) &&
2628 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00002629 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00002630 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2631
2632 // setcc's with boolean values can always be turned into bitwise operations
2633 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00002634 switch (I.getOpcode()) {
2635 default: assert(0 && "Invalid setcc instruction!");
2636 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00002637 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00002638 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00002639 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00002640 }
Chris Lattner5dbef222004-08-11 00:50:51 +00002641 case Instruction::SetNE:
2642 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00002643
Chris Lattner5dbef222004-08-11 00:50:51 +00002644 case Instruction::SetGT:
2645 std::swap(Op0, Op1); // Change setgt -> setlt
2646 // FALL THROUGH
2647 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2648 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2649 InsertNewInstBefore(Not, I);
2650 return BinaryOperator::createAnd(Not, Op1);
2651 }
2652 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00002653 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00002654 // FALL THROUGH
2655 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2656 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2657 InsertNewInstBefore(Not, I);
2658 return BinaryOperator::createOr(Not, Op1);
2659 }
2660 }
Chris Lattner8b170942002-08-09 23:47:40 +00002661 }
2662
Chris Lattner2be51ae2004-06-09 04:24:29 +00002663 // See if we are doing a comparison between a constant and an instruction that
2664 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00002665 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002666 // Check to see if we are comparing against the minimum or maximum value...
2667 if (CI->isMinValue()) {
2668 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2669 return ReplaceInstUsesWith(I, ConstantBool::False);
2670 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2671 return ReplaceInstUsesWith(I, ConstantBool::True);
2672 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2673 return BinaryOperator::createSetEQ(Op0, Op1);
2674 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2675 return BinaryOperator::createSetNE(Op0, Op1);
2676
2677 } else if (CI->isMaxValue()) {
2678 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2679 return ReplaceInstUsesWith(I, ConstantBool::False);
2680 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2681 return ReplaceInstUsesWith(I, ConstantBool::True);
2682 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2683 return BinaryOperator::createSetEQ(Op0, Op1);
2684 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2685 return BinaryOperator::createSetNE(Op0, Op1);
2686
2687 // Comparing against a value really close to min or max?
2688 } else if (isMinValuePlusOne(CI)) {
2689 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2690 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2691 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2692 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2693
2694 } else if (isMaxValueMinusOne(CI)) {
2695 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2696 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2697 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2698 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2699 }
2700
2701 // If we still have a setle or setge instruction, turn it into the
2702 // appropriate setlt or setgt instruction. Since the border cases have
2703 // already been handled above, this requires little checking.
2704 //
2705 if (I.getOpcode() == Instruction::SetLE)
2706 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2707 if (I.getOpcode() == Instruction::SetGE)
2708 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2709
Chris Lattner3c6a0d42004-05-25 06:32:08 +00002710 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00002711 switch (LHSI->getOpcode()) {
2712 case Instruction::And:
2713 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2714 LHSI->getOperand(0)->hasOneUse()) {
2715 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2716 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2717 // happens a LOT in code produced by the C front-end, for bitfield
2718 // access.
2719 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2720 ConstantUInt *ShAmt;
2721 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2722 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2723 const Type *Ty = LHSI->getType();
Misha Brukmanfd939082005-04-21 23:48:37 +00002724
Chris Lattner648e3bc2004-09-23 21:52:49 +00002725 // We can fold this as long as we can't shift unknown bits
2726 // into the mask. This can only happen with signed shift
2727 // rights, as they sign-extend.
2728 if (ShAmt) {
2729 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattner0cba71b2004-09-28 17:54:07 +00002730 Shift->getType()->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00002731 if (!CanFold) {
2732 // To test for the bad case of the signed shr, see if any
2733 // of the bits shifted in could be tested after the mask.
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00002734 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2735 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2736
2737 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00002738 Constant *ShVal =
Chris Lattner648e3bc2004-09-23 21:52:49 +00002739 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2740 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2741 CanFold = true;
2742 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002743
Chris Lattner648e3bc2004-09-23 21:52:49 +00002744 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00002745 Constant *NewCst;
2746 if (Shift->getOpcode() == Instruction::Shl)
2747 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2748 else
2749 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00002750
Chris Lattner648e3bc2004-09-23 21:52:49 +00002751 // Check to see if we are shifting out any of the bits being
2752 // compared.
2753 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2754 // If we shifted bits out, the fold is not going to work out.
2755 // As a special case, check to see if this means that the
2756 // result is always true or false now.
2757 if (I.getOpcode() == Instruction::SetEQ)
2758 return ReplaceInstUsesWith(I, ConstantBool::False);
2759 if (I.getOpcode() == Instruction::SetNE)
2760 return ReplaceInstUsesWith(I, ConstantBool::True);
2761 } else {
2762 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00002763 Constant *NewAndCST;
2764 if (Shift->getOpcode() == Instruction::Shl)
2765 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2766 else
2767 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2768 LHSI->setOperand(1, NewAndCST);
Chris Lattner648e3bc2004-09-23 21:52:49 +00002769 LHSI->setOperand(0, Shift->getOperand(0));
2770 WorkList.push_back(Shift); // Shift is dead.
2771 AddUsesToWorkList(I);
2772 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00002773 }
2774 }
Chris Lattner457dd822004-06-09 07:59:58 +00002775 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00002776 }
2777 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00002778
Chris Lattner18d19ca2004-09-28 18:22:15 +00002779 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2780 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2781 switch (I.getOpcode()) {
2782 default: break;
2783 case Instruction::SetEQ:
2784 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00002785 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2786
2787 // Check that the shift amount is in range. If not, don't perform
2788 // undefined shifts. When the shift is visited it will be
2789 // simplified.
2790 if (ShAmt->getValue() >= TypeBits)
2791 break;
2792
Chris Lattner18d19ca2004-09-28 18:22:15 +00002793 // If we are comparing against bits always shifted out, the
2794 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00002795 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00002796 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2797 if (Comp != CI) {// Comparing against a bit that we know is zero.
2798 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2799 Constant *Cst = ConstantBool::get(IsSetNE);
2800 return ReplaceInstUsesWith(I, Cst);
2801 }
2802
2803 if (LHSI->hasOneUse()) {
2804 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00002805 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00002806 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2807
2808 Constant *Mask;
2809 if (CI->getType()->isUnsigned()) {
2810 Mask = ConstantUInt::get(CI->getType(), Val);
2811 } else if (ShAmtVal != 0) {
2812 Mask = ConstantSInt::get(CI->getType(), Val);
2813 } else {
2814 Mask = ConstantInt::getAllOnesValue(CI->getType());
2815 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002816
Chris Lattner18d19ca2004-09-28 18:22:15 +00002817 Instruction *AndI =
2818 BinaryOperator::createAnd(LHSI->getOperand(0),
2819 Mask, LHSI->getName()+".mask");
2820 Value *And = InsertNewInstBefore(AndI, I);
2821 return new SetCondInst(I.getOpcode(), And,
2822 ConstantExpr::getUShr(CI, ShAmt));
2823 }
2824 }
2825 }
2826 }
2827 break;
2828
Chris Lattner83c4ec02004-09-27 19:29:18 +00002829 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00002830 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00002831 switch (I.getOpcode()) {
2832 default: break;
2833 case Instruction::SetEQ:
2834 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00002835
2836 // Check that the shift amount is in range. If not, don't perform
2837 // undefined shifts. When the shift is visited it will be
2838 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00002839 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnere17a1282005-06-15 20:53:31 +00002840 if (ShAmt->getValue() >= TypeBits)
2841 break;
2842
Chris Lattnerf63f6472004-09-27 16:18:50 +00002843 // If we are comparing against bits always shifted out, the
2844 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00002845 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00002846 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00002847
Chris Lattnerf63f6472004-09-27 16:18:50 +00002848 if (Comp != CI) {// Comparing against a bit that we know is zero.
2849 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2850 Constant *Cst = ConstantBool::get(IsSetNE);
2851 return ReplaceInstUsesWith(I, Cst);
2852 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002853
Chris Lattnerf63f6472004-09-27 16:18:50 +00002854 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00002855 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00002856
Chris Lattnerf63f6472004-09-27 16:18:50 +00002857 // Otherwise strength reduce the shift into an and.
2858 uint64_t Val = ~0ULL; // All ones.
2859 Val <<= ShAmtVal; // Shift over to the right spot.
2860
2861 Constant *Mask;
2862 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00002863 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00002864 Mask = ConstantUInt::get(CI->getType(), Val);
2865 } else {
2866 Mask = ConstantSInt::get(CI->getType(), Val);
2867 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002868
Chris Lattnerf63f6472004-09-27 16:18:50 +00002869 Instruction *AndI =
2870 BinaryOperator::createAnd(LHSI->getOperand(0),
2871 Mask, LHSI->getName()+".mask");
2872 Value *And = InsertNewInstBefore(AndI, I);
2873 return new SetCondInst(I.getOpcode(), And,
2874 ConstantExpr::getShl(CI, ShAmt));
2875 }
2876 break;
2877 }
2878 }
2879 }
2880 break;
Chris Lattner0c967662004-09-24 15:21:34 +00002881
Chris Lattnera96879a2004-09-29 17:40:11 +00002882 case Instruction::Div:
2883 // Fold: (div X, C1) op C2 -> range check
2884 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2885 // Fold this div into the comparison, producing a range check.
2886 // Determine, based on the divide type, what the range is being
2887 // checked. If there is an overflow on the low or high side, remember
2888 // it, otherwise compute the range [low, hi) bounding the new value.
2889 bool LoOverflow = false, HiOverflow = 0;
2890 ConstantInt *LoBound = 0, *HiBound = 0;
2891
2892 ConstantInt *Prod;
2893 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2894
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002895 Instruction::BinaryOps Opcode = I.getOpcode();
2896
Chris Lattnera96879a2004-09-29 17:40:11 +00002897 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2898 } else if (LHSI->getType()->isUnsigned()) { // udiv
2899 LoBound = Prod;
2900 LoOverflow = ProdOV;
2901 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2902 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2903 if (CI->isNullValue()) { // (X / pos) op 0
2904 // Can't overflow.
2905 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2906 HiBound = DivRHS;
2907 } else if (isPositive(CI)) { // (X / pos) op pos
2908 LoBound = Prod;
2909 LoOverflow = ProdOV;
2910 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2911 } else { // (X / pos) op neg
2912 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2913 LoOverflow = AddWithOverflow(LoBound, Prod,
2914 cast<ConstantInt>(DivRHSH));
2915 HiBound = Prod;
2916 HiOverflow = ProdOV;
2917 }
2918 } else { // Divisor is < 0.
2919 if (CI->isNullValue()) { // (X / neg) op 0
2920 LoBound = AddOne(DivRHS);
2921 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00002922 if (HiBound == DivRHS)
2923 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00002924 } else if (isPositive(CI)) { // (X / neg) op pos
2925 HiOverflow = LoOverflow = ProdOV;
2926 if (!LoOverflow)
2927 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2928 HiBound = AddOne(Prod);
2929 } else { // (X / neg) op neg
2930 LoBound = Prod;
2931 LoOverflow = HiOverflow = ProdOV;
2932 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2933 }
Chris Lattner340a05f2004-10-08 19:15:44 +00002934
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002935 // Dividing by a negate swaps the condition.
2936 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00002937 }
2938
2939 if (LoBound) {
2940 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00002941 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00002942 default: assert(0 && "Unhandled setcc opcode!");
2943 case Instruction::SetEQ:
2944 if (LoOverflow && HiOverflow)
2945 return ReplaceInstUsesWith(I, ConstantBool::False);
2946 else if (HiOverflow)
2947 return new SetCondInst(Instruction::SetGE, X, LoBound);
2948 else if (LoOverflow)
2949 return new SetCondInst(Instruction::SetLT, X, HiBound);
2950 else
2951 return InsertRangeTest(X, LoBound, HiBound, true, I);
2952 case Instruction::SetNE:
2953 if (LoOverflow && HiOverflow)
2954 return ReplaceInstUsesWith(I, ConstantBool::True);
2955 else if (HiOverflow)
2956 return new SetCondInst(Instruction::SetLT, X, LoBound);
2957 else if (LoOverflow)
2958 return new SetCondInst(Instruction::SetGE, X, HiBound);
2959 else
2960 return InsertRangeTest(X, LoBound, HiBound, false, I);
2961 case Instruction::SetLT:
2962 if (LoOverflow)
2963 return ReplaceInstUsesWith(I, ConstantBool::False);
2964 return new SetCondInst(Instruction::SetLT, X, LoBound);
2965 case Instruction::SetGT:
2966 if (HiOverflow)
2967 return ReplaceInstUsesWith(I, ConstantBool::False);
2968 return new SetCondInst(Instruction::SetGE, X, HiBound);
2969 }
2970 }
2971 }
2972 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00002973 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002974
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002975 // Simplify seteq and setne instructions...
2976 if (I.getOpcode() == Instruction::SetEQ ||
2977 I.getOpcode() == Instruction::SetNE) {
2978 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2979
Chris Lattner00b1a7e2003-07-23 17:26:36 +00002980 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00002981 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00002982 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2983 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00002984 case Instruction::Rem:
2985 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2986 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2987 BO->hasOneUse() &&
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002988 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
2989 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
2990 if (isPowerOf2_64(V)) {
2991 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00002992 const Type *UTy = BO->getType()->getUnsignedVersion();
2993 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2994 UTy, "tmp"), I);
2995 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2996 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2997 RHSCst, BO->getName()), I);
2998 return BinaryOperator::create(I.getOpcode(), NewRem,
2999 Constant::getNullValue(UTy));
3000 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003001 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003002 break;
Chris Lattner3571b722004-07-06 07:38:18 +00003003
Chris Lattner934754b2003-08-13 05:33:12 +00003004 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00003005 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3006 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00003007 if (BO->hasOneUse())
3008 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3009 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00003010 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003011 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3012 // efficiently invertible, or if the add has just this one use.
3013 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003014
Chris Lattner934754b2003-08-13 05:33:12 +00003015 if (Value *NegVal = dyn_castNegVal(BOp1))
3016 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3017 else if (Value *NegVal = dyn_castNegVal(BOp0))
3018 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00003019 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003020 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3021 BO->setName("");
3022 InsertNewInstBefore(Neg, I);
3023 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3024 }
3025 }
3026 break;
3027 case Instruction::Xor:
3028 // For the xor case, we can xor two constants together, eliminating
3029 // the explicit xor.
3030 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3031 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003032 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00003033
3034 // FALLTHROUGH
3035 case Instruction::Sub:
3036 // Replace (([sub|xor] A, B) != 0) with (A != B)
3037 if (CI->isNullValue())
3038 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3039 BO->getOperand(1));
3040 break;
3041
3042 case Instruction::Or:
3043 // If bits are being or'd in that are not present in the constant we
3044 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00003045 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00003046 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00003047 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003048 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003049 }
Chris Lattner934754b2003-08-13 05:33:12 +00003050 break;
3051
3052 case Instruction::And:
3053 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003054 // If bits are being compared against that are and'd out, then the
3055 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00003056 if (!ConstantExpr::getAnd(CI,
3057 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003058 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00003059
Chris Lattner457dd822004-06-09 07:59:58 +00003060 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00003061 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00003062 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3063 Instruction::SetNE, Op0,
3064 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00003065
Chris Lattner934754b2003-08-13 05:33:12 +00003066 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3067 // to be a signed value as appropriate.
3068 if (isSignBit(BOC)) {
3069 Value *X = BO->getOperand(0);
3070 // If 'X' is not signed, insert a cast now...
3071 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00003072 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00003073 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00003074 }
3075 return new SetCondInst(isSetNE ? Instruction::SetLT :
3076 Instruction::SetGE, X,
3077 Constant::getNullValue(X->getType()));
3078 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003079
Chris Lattner83c4ec02004-09-27 19:29:18 +00003080 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003081 if (CI->isNullValue() && isHighOnes(BOC)) {
3082 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003083 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003084
3085 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00003086 if (NegX->getType()->isSigned()) {
3087 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3088 X = InsertCastBefore(X, DestTy, I);
3089 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003090 }
3091
3092 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00003093 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003094 }
3095
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003096 }
Chris Lattner934754b2003-08-13 05:33:12 +00003097 default: break;
3098 }
3099 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003100 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00003101 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003102 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3103 Value *CastOp = Cast->getOperand(0);
3104 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00003105 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003106 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003107 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003108 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003109 "Source and destination signednesses should differ!");
3110 if (Cast->getType()->isSigned()) {
3111 // If this is a signed comparison, check for comparisons in the
3112 // vicinity of zero.
3113 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3114 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00003115 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003116 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003117 else if (I.getOpcode() == Instruction::SetGT &&
3118 cast<ConstantSInt>(CI)->getValue() == -1)
3119 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00003120 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003121 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003122 } else {
3123 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3124 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003125 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003126 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00003127 return BinaryOperator::createSetGT(CastOp,
3128 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003129 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003130 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003131 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00003132 return BinaryOperator::createSetLT(CastOp,
3133 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003134 }
3135 }
3136 }
Chris Lattner40f5d702003-06-04 05:10:11 +00003137 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003138 }
3139
Chris Lattner6970b662005-04-23 15:31:55 +00003140 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3141 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3142 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3143 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00003144 case Instruction::GetElementPtr:
3145 if (RHSC->isNullValue()) {
3146 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3147 bool isAllZeros = true;
3148 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3149 if (!isa<Constant>(LHSI->getOperand(i)) ||
3150 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3151 isAllZeros = false;
3152 break;
3153 }
3154 if (isAllZeros)
3155 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3156 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3157 }
3158 break;
3159
Chris Lattner6970b662005-04-23 15:31:55 +00003160 case Instruction::PHI:
3161 if (Instruction *NV = FoldOpIntoPhi(I))
3162 return NV;
3163 break;
3164 case Instruction::Select:
3165 // If either operand of the select is a constant, we can fold the
3166 // comparison into the select arms, which will cause one to be
3167 // constant folded and the select turned into a bitwise or.
3168 Value *Op1 = 0, *Op2 = 0;
3169 if (LHSI->hasOneUse()) {
3170 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3171 // Fold the known value into the constant operand.
3172 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3173 // Insert a new SetCC of the other select operand.
3174 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3175 LHSI->getOperand(2), RHSC,
3176 I.getName()), I);
3177 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3178 // Fold the known value into the constant operand.
3179 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3180 // Insert a new SetCC of the other select operand.
3181 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3182 LHSI->getOperand(1), RHSC,
3183 I.getName()), I);
3184 }
3185 }
Jeff Cohen9d809302005-04-23 21:38:35 +00003186
Chris Lattner6970b662005-04-23 15:31:55 +00003187 if (Op1)
3188 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3189 break;
3190 }
3191 }
3192
Chris Lattner574da9b2005-01-13 20:14:25 +00003193 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3194 if (User *GEP = dyn_castGetElementPtr(Op0))
3195 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3196 return NI;
3197 if (User *GEP = dyn_castGetElementPtr(Op1))
3198 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3199 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3200 return NI;
3201
Chris Lattnerde90b762003-11-03 04:25:02 +00003202 // Test to see if the operands of the setcc are casted versions of other
3203 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00003204 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3205 Value *CastOp0 = CI->getOperand(0);
3206 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00003207 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00003208 (I.getOpcode() == Instruction::SetEQ ||
3209 I.getOpcode() == Instruction::SetNE)) {
3210 // We keep moving the cast from the left operand over to the right
3211 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00003212 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00003213
Chris Lattnerde90b762003-11-03 04:25:02 +00003214 // If operand #1 is a cast instruction, see if we can eliminate it as
3215 // well.
Chris Lattner68708052003-11-03 05:17:03 +00003216 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3217 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00003218 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00003219 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003220
Chris Lattnerde90b762003-11-03 04:25:02 +00003221 // If Op1 is a constant, we can fold the cast into the constant.
3222 if (Op1->getType() != Op0->getType())
3223 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3224 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3225 } else {
3226 // Otherwise, cast the RHS right before the setcc
3227 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3228 InsertNewInstBefore(cast<Instruction>(Op1), I);
3229 }
3230 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3231 }
3232
Chris Lattner68708052003-11-03 05:17:03 +00003233 // Handle the special case of: setcc (cast bool to X), <cst>
3234 // This comes up when you have code like
3235 // int X = A < B;
3236 // if (X) ...
3237 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00003238 // with a constant or another cast from the same type.
3239 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3240 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3241 return R;
Chris Lattner68708052003-11-03 05:17:03 +00003242 }
Chris Lattner7e708292002-06-25 16:13:24 +00003243 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003244}
3245
Chris Lattner484d3cf2005-04-24 06:59:08 +00003246// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3247// We only handle extending casts so far.
3248//
3249Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3250 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3251 const Type *SrcTy = LHSCIOp->getType();
3252 const Type *DestTy = SCI.getOperand(0)->getType();
3253 Value *RHSCIOp;
3254
3255 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00003256 return 0;
3257
Chris Lattner484d3cf2005-04-24 06:59:08 +00003258 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3259 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3260 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3261
3262 // Is this a sign or zero extension?
3263 bool isSignSrc = SrcTy->isSigned();
3264 bool isSignDest = DestTy->isSigned();
3265
3266 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3267 // Not an extension from the same type?
3268 RHSCIOp = CI->getOperand(0);
3269 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3270 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3271 // Compute the constant that would happen if we truncated to SrcTy then
3272 // reextended to DestTy.
3273 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3274
3275 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3276 RHSCIOp = Res;
3277 } else {
3278 // If the value cannot be represented in the shorter type, we cannot emit
3279 // a simple comparison.
3280 if (SCI.getOpcode() == Instruction::SetEQ)
3281 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3282 if (SCI.getOpcode() == Instruction::SetNE)
3283 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3284
Chris Lattner484d3cf2005-04-24 06:59:08 +00003285 // Evaluate the comparison for LT.
3286 Value *Result;
3287 if (DestTy->isSigned()) {
3288 // We're performing a signed comparison.
3289 if (isSignSrc) {
3290 // Signed extend and signed comparison.
3291 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3292 Result = ConstantBool::False;
3293 else
3294 Result = ConstantBool::True; // X < (large) --> true
3295 } else {
3296 // Unsigned extend and signed comparison.
3297 if (cast<ConstantSInt>(CI)->getValue() < 0)
3298 Result = ConstantBool::False;
3299 else
3300 Result = ConstantBool::True;
3301 }
3302 } else {
3303 // We're performing an unsigned comparison.
3304 if (!isSignSrc) {
3305 // Unsigned extend & compare -> always true.
3306 Result = ConstantBool::True;
3307 } else {
3308 // We're performing an unsigned comp with a sign extended value.
3309 // This is true if the input is >= 0. [aka >s -1]
3310 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3311 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3312 NegOne, SCI.getName()), SCI);
3313 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00003314 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003315
Jeff Cohen00b168892005-07-27 06:12:32 +00003316 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00003317 if (SCI.getOpcode() == Instruction::SetLT) {
3318 return ReplaceInstUsesWith(SCI, Result);
3319 } else {
3320 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3321 if (Constant *CI = dyn_cast<Constant>(Result))
3322 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3323 else
3324 return BinaryOperator::createNot(Result);
3325 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00003326 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00003327 } else {
3328 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00003329 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003330
Chris Lattner8d7089e2005-06-16 03:00:08 +00003331 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00003332 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3333}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003334
Chris Lattnerea340052003-03-10 19:16:08 +00003335Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00003336 assert(I.getOperand(1)->getType() == Type::UByteTy);
3337 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003338 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003339
3340 // shl X, 0 == X and shr X, 0 == X
3341 // shl 0, X == 0 and shr 0, X == 0
3342 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00003343 Op0 == Constant::getNullValue(Op0->getType()))
3344 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003345
Chris Lattnere87597f2004-10-16 18:11:37 +00003346 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3347 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00003348 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00003349 else // undef << X -> 0 AND undef >>u X -> 0
3350 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3351 }
3352 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00003353 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00003354 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3355 else
3356 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3357 }
3358
Chris Lattnerdf17af12003-08-12 21:53:41 +00003359 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3360 if (!isLeftShift)
3361 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3362 if (CSI->isAllOnesValue())
3363 return ReplaceInstUsesWith(I, CSI);
3364
Chris Lattner2eefe512004-04-09 19:05:30 +00003365 // Try to fold constant and into select arguments.
3366 if (isa<Constant>(Op0))
3367 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003368 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003369 return R;
3370
Chris Lattner120347e2005-05-08 17:34:56 +00003371 // See if we can turn a signed shr into an unsigned shr.
3372 if (!isLeftShift && I.getType()->isSigned()) {
3373 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3374 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3375 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3376 I.getName()), I);
3377 return new CastInst(V, I.getType());
3378 }
3379 }
Jeff Cohen00b168892005-07-27 06:12:32 +00003380
Chris Lattner3f5b8772002-05-06 16:14:14 +00003381 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003382 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3383 // of a signed value.
3384 //
Chris Lattner484d3cf2005-04-24 06:59:08 +00003385 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner8adac752004-02-23 20:30:06 +00003386 if (CUI->getValue() >= TypeBits) {
3387 if (!Op0->getType()->isSigned() || isLeftShift)
3388 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3389 else {
3390 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3391 return &I;
3392 }
3393 }
Chris Lattnerf2836082002-09-10 23:04:09 +00003394
Chris Lattnere92d2f42003-08-13 04:18:28 +00003395 // ((X*C1) << C2) == (X * (C1 << C2))
3396 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3397 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3398 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00003399 return BinaryOperator::createMul(BO->getOperand(0),
3400 ConstantExpr::getShl(BOOp, CUI));
Misha Brukmanfd939082005-04-21 23:48:37 +00003401
Chris Lattner2eefe512004-04-09 19:05:30 +00003402 // Try to fold constant and into select arguments.
3403 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003404 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003405 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003406 if (isa<PHINode>(Op0))
3407 if (Instruction *NV = FoldOpIntoPhi(I))
3408 return NV;
Chris Lattnere92d2f42003-08-13 04:18:28 +00003409
Chris Lattner6e7ba452005-01-01 16:22:27 +00003410 if (Op0->hasOneUse()) {
3411 // If this is a SHL of a sign-extending cast, see if we can turn the input
3412 // into a zero extending cast (a simple strength reduction).
3413 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3414 const Type *SrcTy = CI->getOperand(0)->getType();
3415 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003416 SrcTy->getPrimitiveSizeInBits() <
3417 CI->getType()->getPrimitiveSizeInBits()) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00003418 // We can change it to a zero extension if we are shifting out all of
3419 // the sign extended bits. To check this, form a mask of all of the
3420 // sign extend bits, then shift them left and see if we have anything
3421 // left.
3422 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3423 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3424 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3425 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3426 // If the shift is nuking all of the sign bits, change this to a
3427 // zero extension cast. To do this, cast the cast input to
3428 // unsigned, then to the requested size.
3429 Value *CastOp = CI->getOperand(0);
3430 Instruction *NC =
3431 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3432 CI->getName()+".uns");
3433 NC = InsertNewInstBefore(NC, I);
3434 // Finally, insert a replacement for CI.
3435 NC = new CastInst(NC, CI->getType(), CI->getName());
3436 CI->setName("");
3437 NC = InsertNewInstBefore(NC, I);
3438 WorkList.push_back(CI); // Delete CI later.
3439 I.setOperand(0, NC);
3440 return &I; // The SHL operand was modified.
3441 }
3442 }
3443 }
3444
Chris Lattner11021cb2005-09-18 05:12:10 +00003445 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3446 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003447 Value *V1, *V2, *V3;
3448 ConstantInt *CC;
Chris Lattner11021cb2005-09-18 05:12:10 +00003449 switch (Op0BO->getOpcode()) {
3450 default: break;
3451 case Instruction::Add:
3452 case Instruction::And:
3453 case Instruction::Or:
3454 case Instruction::Xor:
3455 // These operators commute.
3456 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003457 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3458 match(Op0BO->getOperand(1),
3459 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3460 Instruction *YS = new ShiftInst(Instruction::Shl,
3461 Op0BO->getOperand(0), CUI,
3462 Op0BO->getName());
3463 InsertNewInstBefore(YS, I); // (Y << C)
3464 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3465 V1,
3466 Op0BO->getOperand(1)->getName());
3467 InsertNewInstBefore(X, I); // (X + (Y << C))
3468 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3469 C2 = ConstantExpr::getShl(C2, CUI);
3470 return BinaryOperator::createAnd(X, C2);
3471 }
3472
3473 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3474 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3475 match(Op0BO->getOperand(1),
3476 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3477 m_ConstantInt(CC))) && V2 == CUI &&
3478 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3479 Instruction *YS = new ShiftInst(Instruction::Shl,
3480 Op0BO->getOperand(0), CUI,
3481 Op0BO->getName());
3482 InsertNewInstBefore(YS, I); // (Y << C)
3483 Instruction *XM =
3484 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3485 V1->getName()+".mask");
3486 InsertNewInstBefore(XM, I); // X & (CC << C)
3487
3488 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3489 }
3490
3491 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00003492 case Instruction::Sub:
3493 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00003494 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3495 match(Op0BO->getOperand(0),
3496 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3497 Instruction *YS = new ShiftInst(Instruction::Shl,
3498 Op0BO->getOperand(1), CUI,
3499 Op0BO->getName());
3500 InsertNewInstBefore(YS, I); // (Y << C)
3501 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3502 V1,
3503 Op0BO->getOperand(0)->getName());
3504 InsertNewInstBefore(X, I); // (X + (Y << C))
3505 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3506 C2 = ConstantExpr::getShl(C2, CUI);
3507 return BinaryOperator::createAnd(X, C2);
3508 }
3509
3510 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3511 match(Op0BO->getOperand(0),
3512 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3513 m_ConstantInt(CC))) && V2 == CUI &&
3514 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3515 Instruction *YS = new ShiftInst(Instruction::Shl,
3516 Op0BO->getOperand(1), CUI,
3517 Op0BO->getName());
3518 InsertNewInstBefore(YS, I); // (Y << C)
3519 Instruction *XM =
3520 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3521 V1->getName()+".mask");
3522 InsertNewInstBefore(XM, I); // X & (CC << C)
3523
3524 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3525 }
3526
Chris Lattner11021cb2005-09-18 05:12:10 +00003527 break;
3528 }
3529
3530
3531 // If the operand is an bitwise operator with a constant RHS, and the
3532 // shift is the only use, we can pull it out of the shift.
Chris Lattnerdf17af12003-08-12 21:53:41 +00003533 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3534 bool isValid = true; // Valid only for And, Or, Xor
3535 bool highBitSet = false; // Transform if high bit of constant set?
3536
3537 switch (Op0BO->getOpcode()) {
3538 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00003539 case Instruction::Add:
3540 isValid = isLeftShift;
3541 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00003542 case Instruction::Or:
3543 case Instruction::Xor:
3544 highBitSet = false;
3545 break;
3546 case Instruction::And:
3547 highBitSet = true;
3548 break;
3549 }
3550
3551 // If this is a signed shift right, and the high bit is modified
3552 // by the logical operation, do not perform the transformation.
3553 // The highBitSet boolean indicates the value of the high bit of
3554 // the constant which would cause it to be modified for this
3555 // operation.
3556 //
3557 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3558 uint64_t Val = Op0C->getRawValue();
3559 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3560 }
3561
3562 if (isValid) {
Chris Lattner7c4049c2004-01-12 19:35:11 +00003563 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003564
3565 Instruction *NewShift =
3566 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3567 Op0BO->getName());
3568 Op0BO->setName("");
3569 InsertNewInstBefore(NewShift, I);
3570
3571 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3572 NewRHS);
3573 }
3574 }
Chris Lattner11021cb2005-09-18 05:12:10 +00003575 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00003576 }
Chris Lattnerdf17af12003-08-12 21:53:41 +00003577
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003578 // If this is a shift of a shift, see if we can fold the two together...
Chris Lattnerdf17af12003-08-12 21:53:41 +00003579 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattner943c7132003-07-24 18:38:56 +00003580 if (ConstantUInt *ShiftAmt1C =
3581 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003582 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3583 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003584
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003585 // Check for (A << c1) << c2 and (A >> c1) >> c2
3586 if (I.getOpcode() == Op0SI->getOpcode()) {
3587 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
Chris Lattner484d3cf2005-04-24 06:59:08 +00003588 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3589 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003590 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3591 ConstantUInt::get(Type::UByteTy, Amt));
3592 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003593
Chris Lattner943c7132003-07-24 18:38:56 +00003594 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3595 // signed types, we can only support the (A >> c1) << c2 configuration,
3596 // because it can not turn an arbitrary bit of A into a sign bit.
Chris Lattnerdf17af12003-08-12 21:53:41 +00003597 if (I.getType()->isUnsigned() || isLeftShift) {
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003598 // Calculate bitmask for what gets shifted off the edge...
3599 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00003600 if (isLeftShift)
Chris Lattner48595f12004-06-10 02:07:29 +00003601 C = ConstantExpr::getShl(C, ShiftAmt1C);
Chris Lattnerdf17af12003-08-12 21:53:41 +00003602 else
Chris Lattner48595f12004-06-10 02:07:29 +00003603 C = ConstantExpr::getShr(C, ShiftAmt1C);
Misha Brukmanfd939082005-04-21 23:48:37 +00003604
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003605 Instruction *Mask =
Chris Lattner48595f12004-06-10 02:07:29 +00003606 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3607 Op0SI->getOperand(0)->getName()+".mask");
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003608 InsertNewInstBefore(Mask, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00003609
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003610 // Figure out what flavor of shift we should use...
3611 if (ShiftAmt1 == ShiftAmt2)
3612 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3613 else if (ShiftAmt1 < ShiftAmt2) {
3614 return new ShiftInst(I.getOpcode(), Mask,
3615 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3616 } else {
3617 return new ShiftInst(Op0SI->getOpcode(), Mask,
3618 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3619 }
Chris Lattner5931c542005-09-24 23:43:33 +00003620 } else {
3621 // We can handle signed (X << C1) >> C2 if it's a sign extend. In
3622 // this case, C1 == C2 and C1 is 8, 16, or 32.
3623 if (ShiftAmt1 == ShiftAmt2) {
3624 const Type *SExtType = 0;
3625 switch (ShiftAmt1) {
3626 case 8 : SExtType = Type::SByteTy; break;
3627 case 16: SExtType = Type::ShortTy; break;
3628 case 32: SExtType = Type::IntTy; break;
3629 }
3630
3631 if (SExtType) {
3632 Instruction *NewTrunc = new CastInst(Op0SI->getOperand(0),
3633 SExtType, "sext");
3634 InsertNewInstBefore(NewTrunc, I);
3635 return new CastInst(NewTrunc, I.getType());
3636 }
3637 }
Chris Lattner08fd7ab2003-07-24 17:52:58 +00003638 }
3639 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003640 }
Chris Lattner6eaeb572002-10-08 16:16:40 +00003641
Chris Lattner3f5b8772002-05-06 16:14:14 +00003642 return 0;
3643}
3644
Chris Lattnerbee7e762004-07-20 00:59:32 +00003645enum CastType {
3646 Noop = 0,
3647 Truncate = 1,
3648 Signext = 2,
3649 Zeroext = 3
3650};
3651
3652/// getCastType - In the future, we will split the cast instruction into these
3653/// various types. Until then, we have to do the analysis here.
3654static CastType getCastType(const Type *Src, const Type *Dest) {
3655 assert(Src->isIntegral() && Dest->isIntegral() &&
3656 "Only works on integral types!");
Chris Lattner484d3cf2005-04-24 06:59:08 +00003657 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3658 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattnerbee7e762004-07-20 00:59:32 +00003659
3660 if (SrcSize == DestSize) return Noop;
3661 if (SrcSize > DestSize) return Truncate;
3662 if (Src->isSigned()) return Signext;
3663 return Zeroext;
3664}
3665
Chris Lattner3f5b8772002-05-06 16:14:14 +00003666
Chris Lattnera1be5662002-05-02 17:06:02 +00003667// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3668// instruction.
3669//
Chris Lattner24c8e382003-07-24 17:35:25 +00003670static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
Chris Lattner59a20772004-07-20 05:21:00 +00003671 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003672
Chris Lattner8fd217c2002-08-02 20:00:25 +00003673 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanfd939082005-04-21 23:48:37 +00003674 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00003675 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00003676 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00003677 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00003678
Chris Lattnere8a7e592004-07-21 04:27:24 +00003679 // If we are casting between pointer and integer types, treat pointers as
3680 // integers of the appropriate size for the code below.
3681 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3682 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3683 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00003684
Chris Lattnera1be5662002-05-02 17:06:02 +00003685 // Allow free casting and conversion of sizes as long as the sign doesn't
3686 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00003687 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00003688 CastType FirstCast = getCastType(SrcTy, MidTy);
3689 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00003690
Chris Lattnerbee7e762004-07-20 00:59:32 +00003691 // Capture the effect of these two casts. If the result is a legal cast,
3692 // the CastType is stored here, otherwise a special code is used.
3693 static const unsigned CastResult[] = {
3694 // First cast is noop
3695 0, 1, 2, 3,
3696 // First cast is a truncate
3697 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3698 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003699 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00003700 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00003701 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00003702 };
3703
3704 unsigned Result = CastResult[FirstCast*4+SecondCast];
3705 switch (Result) {
3706 default: assert(0 && "Illegal table value!");
3707 case 0:
3708 case 1:
3709 case 2:
3710 case 3:
3711 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3712 // truncates, we could eliminate more casts.
3713 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3714 case 4:
3715 return false; // Not possible to eliminate this here.
3716 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00003717 // Sign or zero extend followed by truncate is always ok if the result
3718 // is a truncate or noop.
3719 CastType ResultCast = getCastType(SrcTy, DstTy);
3720 if (ResultCast == Noop || ResultCast == Truncate)
3721 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00003722 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner5eb91942004-07-21 19:50:44 +00003723 // result will match the sign/zeroextendness of the result.
3724 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00003725 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00003726 }
Chris Lattnera1be5662002-05-02 17:06:02 +00003727 return false;
3728}
3729
Chris Lattner59a20772004-07-20 05:21:00 +00003730static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00003731 if (V->getType() == Ty || isa<Constant>(V)) return false;
3732 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00003733 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3734 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00003735 return false;
3736 return true;
3737}
3738
3739/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3740/// InsertBefore instruction. This is specialized a bit to avoid inserting
3741/// casts that are known to not do anything...
3742///
3743Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3744 Instruction *InsertBefore) {
3745 if (V->getType() == DestTy) return V;
3746 if (Constant *C = dyn_cast<Constant>(V))
3747 return ConstantExpr::getCast(C, DestTy);
3748
3749 CastInst *CI = new CastInst(V, DestTy, V->getName());
3750 InsertNewInstBefore(CI, *InsertBefore);
3751 return CI;
3752}
Chris Lattnera1be5662002-05-02 17:06:02 +00003753
3754// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003755//
Chris Lattner7e708292002-06-25 16:13:24 +00003756Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00003757 Value *Src = CI.getOperand(0);
3758
Chris Lattnera1be5662002-05-02 17:06:02 +00003759 // If the user is casting a value to the same type, eliminate this cast
3760 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00003761 if (CI.getType() == Src->getType())
3762 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00003763
Chris Lattnere87597f2004-10-16 18:11:37 +00003764 if (isa<UndefValue>(Src)) // cast undef -> undef
3765 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3766
Chris Lattnera1be5662002-05-02 17:06:02 +00003767 // If casting the result of another cast instruction, try to eliminate this
3768 // one!
3769 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00003770 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3771 Value *A = CSrc->getOperand(0);
3772 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3773 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00003774 // This instruction now refers directly to the cast's src operand. This
3775 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00003776 CI.setOperand(0, CSrc->getOperand(0));
3777 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00003778 }
3779
Chris Lattner8fd217c2002-08-02 20:00:25 +00003780 // If this is an A->B->A cast, and we are dealing with integral types, try
3781 // to convert this into a logical 'and' instruction.
3782 //
Misha Brukmanfd939082005-04-21 23:48:37 +00003783 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00003784 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00003785 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00003786 CSrc->getType()->getPrimitiveSizeInBits() <
3787 CI.getType()->getPrimitiveSizeInBits()&&
3788 A->getType()->getPrimitiveSizeInBits() ==
3789 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00003790 assert(CSrc->getType() != Type::ULongTy &&
3791 "Cannot have type bigger than ulong!");
Chris Lattnerf52d6812005-04-24 17:46:05 +00003792 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
Chris Lattner6e7ba452005-01-01 16:22:27 +00003793 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3794 AndValue);
3795 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3796 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3797 if (And->getType() != CI.getType()) {
3798 And->setName(CSrc->getName()+".mask");
3799 InsertNewInstBefore(And, CI);
3800 And = new CastInst(And, CI.getType());
3801 }
3802 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00003803 }
3804 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003805
Chris Lattnera710ddc2004-05-25 04:29:21 +00003806 // If this is a cast to bool, turn it into the appropriate setne instruction.
3807 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00003808 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00003809 Constant::getNullValue(CI.getOperand(0)->getType()));
3810
Chris Lattner797249b2003-06-21 23:12:02 +00003811 // If casting the result of a getelementptr instruction with no offset, turn
3812 // this into a cast of the original pointer!
3813 //
Chris Lattner79d35b32003-06-23 21:59:52 +00003814 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00003815 bool AllZeroOperands = true;
3816 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3817 if (!isa<Constant>(GEP->getOperand(i)) ||
3818 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3819 AllZeroOperands = false;
3820 break;
3821 }
3822 if (AllZeroOperands) {
3823 CI.setOperand(0, GEP->getOperand(0));
3824 return &CI;
3825 }
3826 }
3827
Chris Lattnerbc61e662003-11-02 05:57:39 +00003828 // If we are casting a malloc or alloca to a pointer to a type of the same
3829 // size, rewrite the allocation instruction to allocate the "right" type.
3830 //
3831 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerfc07a342003-11-02 06:54:48 +00003832 if (AI->hasOneUse() && !AI->isArrayAllocation())
Chris Lattnerbc61e662003-11-02 05:57:39 +00003833 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
3834 // Get the type really allocated and the type casted to...
3835 const Type *AllocElTy = AI->getAllocatedType();
Chris Lattnerbc61e662003-11-02 05:57:39 +00003836 const Type *CastElTy = PTy->getElementType();
Chris Lattnerfae10102004-07-06 19:28:42 +00003837 if (AllocElTy->isSized() && CastElTy->isSized()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003838 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3839 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner1bcc70d2003-11-05 17:31:36 +00003840
Chris Lattnerfae10102004-07-06 19:28:42 +00003841 // If the allocation is for an even multiple of the cast type size
3842 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003843 Value *Amt = ConstantUInt::get(Type::UIntTy,
Chris Lattnerbc61e662003-11-02 05:57:39 +00003844 AllocElTySize/CastElTySize);
Chris Lattnerfae10102004-07-06 19:28:42 +00003845 std::string Name = AI->getName(); AI->setName("");
3846 AllocationInst *New;
3847 if (isa<MallocInst>(AI))
3848 New = new MallocInst(CastElTy, Amt, Name);
3849 else
3850 New = new AllocaInst(CastElTy, Amt, Name);
3851 InsertNewInstBefore(New, *AI);
3852 return ReplaceInstUsesWith(CI, New);
3853 }
Chris Lattnerbc61e662003-11-02 05:57:39 +00003854 }
3855 }
3856
Chris Lattner6e7ba452005-01-01 16:22:27 +00003857 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
3858 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
3859 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00003860 if (isa<PHINode>(Src))
3861 if (Instruction *NV = FoldOpIntoPhi(CI))
3862 return NV;
3863
Chris Lattner24c8e382003-07-24 17:35:25 +00003864 // If the source value is an instruction with only this use, we can attempt to
3865 // propagate the cast into the instruction. Also, only handle integral types
3866 // for now.
3867 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00003868 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00003869 CI.getType()->isInteger()) { // Don't mess with casts to bool here
3870 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00003871 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
3872 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00003873
3874 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
3875 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
3876
3877 switch (SrcI->getOpcode()) {
3878 case Instruction::Add:
3879 case Instruction::Mul:
3880 case Instruction::And:
3881 case Instruction::Or:
3882 case Instruction::Xor:
3883 // If we are discarding information, or just changing the sign, rewrite.
3884 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
3885 // Don't insert two casts if they cannot be eliminated. We allow two
3886 // casts to be inserted if the sizes are the same. This could only be
3887 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00003888 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
3889 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00003890 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3891 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
3892 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
3893 ->getOpcode(), Op0c, Op1c);
3894 }
3895 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00003896
3897 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
3898 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
3899 Op1 == ConstantBool::True &&
3900 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
3901 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
3902 return BinaryOperator::createXor(New,
3903 ConstantInt::get(CI.getType(), 1));
3904 }
Chris Lattner24c8e382003-07-24 17:35:25 +00003905 break;
3906 case Instruction::Shl:
3907 // Allow changing the sign of the source operand. Do not allow changing
3908 // the size of the shift, UNLESS the shift amount is a constant. We
3909 // mush not change variable sized shifts to a smaller size, because it
3910 // is undefined to shift more bits out than exist in the value.
3911 if (DestBitSize == SrcBitSize ||
3912 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
3913 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
3914 return new ShiftInst(Instruction::Shl, Op0c, Op1);
3915 }
3916 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00003917 case Instruction::Shr:
3918 // If this is a signed shr, and if all bits shifted in are about to be
3919 // truncated off, turn it into an unsigned shr to allow greater
3920 // simplifications.
3921 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
3922 isa<ConstantInt>(Op1)) {
3923 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
3924 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
3925 // Convert to unsigned.
3926 Value *N1 = InsertOperandCastBefore(Op0,
3927 Op0->getType()->getUnsignedVersion(), &CI);
3928 // Insert the new shift, which is now unsigned.
3929 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
3930 Op1, Src->getName()), CI);
3931 return new CastInst(N1, CI.getType());
3932 }
3933 }
3934 break;
3935
Chris Lattner693787a2005-05-04 19:10:26 +00003936 case Instruction::SetNE:
Chris Lattner693787a2005-05-04 19:10:26 +00003937 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnerd1523802005-05-06 01:53:19 +00003938 if (Op1C->getRawValue() == 0) {
3939 // If the input only has the low bit set, simplify directly.
Jeff Cohen00b168892005-07-27 06:12:32 +00003940 Constant *Not1 =
Chris Lattner693787a2005-05-04 19:10:26 +00003941 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
Chris Lattnerd1523802005-05-06 01:53:19 +00003942 // cast (X != 0) to int --> X if X&~1 == 0
Chris Lattner693787a2005-05-04 19:10:26 +00003943 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3944 if (CI.getType() == Op0->getType())
3945 return ReplaceInstUsesWith(CI, Op0);
3946 else
3947 return new CastInst(Op0, CI.getType());
3948 }
Chris Lattnerd1523802005-05-06 01:53:19 +00003949
3950 // If the input is an and with a single bit, shift then simplify.
3951 ConstantInt *AndRHS;
3952 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
3953 if (AndRHS->getRawValue() &&
3954 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003955 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
Chris Lattnerd1523802005-05-06 01:53:19 +00003956 // Perform an unsigned shr by shiftamt. Convert input to
3957 // unsigned if it is signed.
3958 Value *In = Op0;
3959 if (In->getType()->isSigned())
3960 In = InsertNewInstBefore(new CastInst(In,
3961 In->getType()->getUnsignedVersion(), In->getName()),CI);
3962 // Insert the shift to put the result in the low bit.
3963 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
3964 ConstantInt::get(Type::UByteTy, ShiftAmt),
3965 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00003966 if (CI.getType() == In->getType())
3967 return ReplaceInstUsesWith(CI, In);
3968 else
3969 return new CastInst(In, CI.getType());
3970 }
3971 }
3972 }
3973 break;
3974 case Instruction::SetEQ:
3975 // We if we are just checking for a seteq of a single bit and casting it
3976 // to an integer. If so, shift the bit to the appropriate place then
3977 // cast to integer to avoid the comparison.
3978 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
3979 // Is Op1C a power of two or zero?
3980 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
3981 // cast (X == 1) to int -> X iff X has only the low bit set.
3982 if (Op1C->getRawValue() == 1) {
Jeff Cohen00b168892005-07-27 06:12:32 +00003983 Constant *Not1 =
Chris Lattnerd1523802005-05-06 01:53:19 +00003984 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
3985 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
3986 if (CI.getType() == Op0->getType())
3987 return ReplaceInstUsesWith(CI, Op0);
3988 else
3989 return new CastInst(Op0, CI.getType());
3990 }
3991 }
Chris Lattner693787a2005-05-04 19:10:26 +00003992 }
3993 }
3994 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00003995 }
3996 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003997 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00003998}
3999
Chris Lattnere576b912004-04-09 23:46:01 +00004000/// GetSelectFoldableOperands - We want to turn code that looks like this:
4001/// %C = or %A, %B
4002/// %D = select %cond, %C, %A
4003/// into:
4004/// %C = select %cond, %B, 0
4005/// %D = or %A, %C
4006///
4007/// Assuming that the specified instruction is an operand to the select, return
4008/// a bitmask indicating which operands of this instruction are foldable if they
4009/// equal the other incoming value of the select.
4010///
4011static unsigned GetSelectFoldableOperands(Instruction *I) {
4012 switch (I->getOpcode()) {
4013 case Instruction::Add:
4014 case Instruction::Mul:
4015 case Instruction::And:
4016 case Instruction::Or:
4017 case Instruction::Xor:
4018 return 3; // Can fold through either operand.
4019 case Instruction::Sub: // Can only fold on the amount subtracted.
4020 case Instruction::Shl: // Can only fold on the shift amount.
4021 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00004022 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00004023 default:
4024 return 0; // Cannot fold
4025 }
4026}
4027
4028/// GetSelectFoldableConstant - For the same transformation as the previous
4029/// function, return the identity constant that goes into the select.
4030static Constant *GetSelectFoldableConstant(Instruction *I) {
4031 switch (I->getOpcode()) {
4032 default: assert(0 && "This cannot happen!"); abort();
4033 case Instruction::Add:
4034 case Instruction::Sub:
4035 case Instruction::Or:
4036 case Instruction::Xor:
4037 return Constant::getNullValue(I->getType());
4038 case Instruction::Shl:
4039 case Instruction::Shr:
4040 return Constant::getNullValue(Type::UByteTy);
4041 case Instruction::And:
4042 return ConstantInt::getAllOnesValue(I->getType());
4043 case Instruction::Mul:
4044 return ConstantInt::get(I->getType(), 1);
4045 }
4046}
4047
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004048/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4049/// have the same opcode and only one use each. Try to simplify this.
4050Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4051 Instruction *FI) {
4052 if (TI->getNumOperands() == 1) {
4053 // If this is a non-volatile load or a cast from the same type,
4054 // merge.
4055 if (TI->getOpcode() == Instruction::Cast) {
4056 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4057 return 0;
4058 } else {
4059 return 0; // unknown unary op.
4060 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004061
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004062 // Fold this by inserting a select from the input values.
4063 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4064 FI->getOperand(0), SI.getName()+".v");
4065 InsertNewInstBefore(NewSI, SI);
4066 return new CastInst(NewSI, TI->getType());
4067 }
4068
4069 // Only handle binary operators here.
4070 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4071 return 0;
4072
4073 // Figure out if the operations have any operands in common.
4074 Value *MatchOp, *OtherOpT, *OtherOpF;
4075 bool MatchIsOpZero;
4076 if (TI->getOperand(0) == FI->getOperand(0)) {
4077 MatchOp = TI->getOperand(0);
4078 OtherOpT = TI->getOperand(1);
4079 OtherOpF = FI->getOperand(1);
4080 MatchIsOpZero = true;
4081 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4082 MatchOp = TI->getOperand(1);
4083 OtherOpT = TI->getOperand(0);
4084 OtherOpF = FI->getOperand(0);
4085 MatchIsOpZero = false;
4086 } else if (!TI->isCommutative()) {
4087 return 0;
4088 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4089 MatchOp = TI->getOperand(0);
4090 OtherOpT = TI->getOperand(1);
4091 OtherOpF = FI->getOperand(0);
4092 MatchIsOpZero = true;
4093 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4094 MatchOp = TI->getOperand(1);
4095 OtherOpT = TI->getOperand(0);
4096 OtherOpF = FI->getOperand(1);
4097 MatchIsOpZero = true;
4098 } else {
4099 return 0;
4100 }
4101
4102 // If we reach here, they do have operations in common.
4103 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4104 OtherOpF, SI.getName()+".v");
4105 InsertNewInstBefore(NewSI, SI);
4106
4107 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4108 if (MatchIsOpZero)
4109 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4110 else
4111 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4112 } else {
4113 if (MatchIsOpZero)
4114 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4115 else
4116 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4117 }
4118}
4119
Chris Lattner3d69f462004-03-12 05:52:32 +00004120Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004121 Value *CondVal = SI.getCondition();
4122 Value *TrueVal = SI.getTrueValue();
4123 Value *FalseVal = SI.getFalseValue();
4124
4125 // select true, X, Y -> X
4126 // select false, X, Y -> Y
4127 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00004128 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004129 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00004130 else {
4131 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004132 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00004133 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004134
4135 // select C, X, X -> X
4136 if (TrueVal == FalseVal)
4137 return ReplaceInstUsesWith(SI, TrueVal);
4138
Chris Lattnere87597f2004-10-16 18:11:37 +00004139 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4140 return ReplaceInstUsesWith(SI, FalseVal);
4141 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4142 return ReplaceInstUsesWith(SI, TrueVal);
4143 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4144 if (isa<Constant>(TrueVal))
4145 return ReplaceInstUsesWith(SI, TrueVal);
4146 else
4147 return ReplaceInstUsesWith(SI, FalseVal);
4148 }
4149
Chris Lattner0c199a72004-04-08 04:43:23 +00004150 if (SI.getType() == Type::BoolTy)
4151 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4152 if (C == ConstantBool::True) {
4153 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00004154 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004155 } else {
4156 // Change: A = select B, false, C --> A = and !B, C
4157 Value *NotCond =
4158 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4159 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00004160 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004161 }
4162 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4163 if (C == ConstantBool::False) {
4164 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00004165 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004166 } else {
4167 // Change: A = select B, C, true --> A = or !B, C
4168 Value *NotCond =
4169 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4170 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00004171 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00004172 }
4173 }
4174
Chris Lattner2eefe512004-04-09 19:05:30 +00004175 // Selecting between two integer constants?
4176 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4177 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4178 // select C, 1, 0 -> cast C to int
4179 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4180 return new CastInst(CondVal, SI.getType());
4181 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4182 // select C, 0, 1 -> cast !C to int
4183 Value *NotCond =
4184 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00004185 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00004186 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00004187 }
Chris Lattner457dd822004-06-09 07:59:58 +00004188
4189 // If one of the constants is zero (we know they can't both be) and we
4190 // have a setcc instruction with zero, and we have an 'and' with the
4191 // non-constant value, eliminate this whole mess. This corresponds to
4192 // cases like this: ((X & 27) ? 27 : 0)
4193 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4194 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4195 if ((IC->getOpcode() == Instruction::SetEQ ||
4196 IC->getOpcode() == Instruction::SetNE) &&
4197 isa<ConstantInt>(IC->getOperand(1)) &&
4198 cast<Constant>(IC->getOperand(1))->isNullValue())
4199 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4200 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004201 isa<ConstantInt>(ICA->getOperand(1)) &&
4202 (ICA->getOperand(1) == TrueValC ||
4203 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00004204 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4205 // Okay, now we know that everything is set up, we just don't
4206 // know whether we have a setne or seteq and whether the true or
4207 // false val is the zero.
4208 bool ShouldNotVal = !TrueValC->isNullValue();
4209 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4210 Value *V = ICA;
4211 if (ShouldNotVal)
4212 V = InsertNewInstBefore(BinaryOperator::create(
4213 Instruction::Xor, V, ICA->getOperand(1)), SI);
4214 return ReplaceInstUsesWith(SI, V);
4215 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00004216 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00004217
4218 // See if we are selecting two values based on a comparison of the two values.
4219 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4220 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4221 // Transform (X == Y) ? X : Y -> Y
4222 if (SCI->getOpcode() == Instruction::SetEQ)
4223 return ReplaceInstUsesWith(SI, FalseVal);
4224 // Transform (X != Y) ? X : Y -> X
4225 if (SCI->getOpcode() == Instruction::SetNE)
4226 return ReplaceInstUsesWith(SI, TrueVal);
4227 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4228
4229 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4230 // Transform (X == Y) ? Y : X -> X
4231 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00004232 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00004233 // Transform (X != Y) ? Y : X -> Y
4234 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00004235 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00004236 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4237 }
4238 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004239
Chris Lattner87875da2005-01-13 22:52:24 +00004240 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4241 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4242 if (TI->hasOneUse() && FI->hasOneUse()) {
4243 bool isInverse = false;
4244 Instruction *AddOp = 0, *SubOp = 0;
4245
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00004246 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4247 if (TI->getOpcode() == FI->getOpcode())
4248 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4249 return IV;
4250
4251 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4252 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00004253 if (TI->getOpcode() == Instruction::Sub &&
4254 FI->getOpcode() == Instruction::Add) {
4255 AddOp = FI; SubOp = TI;
4256 } else if (FI->getOpcode() == Instruction::Sub &&
4257 TI->getOpcode() == Instruction::Add) {
4258 AddOp = TI; SubOp = FI;
4259 }
4260
4261 if (AddOp) {
4262 Value *OtherAddOp = 0;
4263 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4264 OtherAddOp = AddOp->getOperand(1);
4265 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4266 OtherAddOp = AddOp->getOperand(0);
4267 }
4268
4269 if (OtherAddOp) {
4270 // So at this point we know we have:
4271 // select C, (add X, Y), (sub X, ?)
4272 // We can do the transform profitably if either 'Y' = '?' or '?' is
4273 // a constant.
4274 if (SubOp->getOperand(1) == AddOp ||
4275 isa<Constant>(SubOp->getOperand(1))) {
4276 Value *NegVal;
4277 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4278 NegVal = ConstantExpr::getNeg(C);
4279 } else {
4280 NegVal = InsertNewInstBefore(
4281 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4282 }
4283
Chris Lattner906ab502005-01-14 17:35:12 +00004284 Value *NewTrueOp = OtherAddOp;
Chris Lattner87875da2005-01-13 22:52:24 +00004285 Value *NewFalseOp = NegVal;
4286 if (AddOp != TI)
4287 std::swap(NewTrueOp, NewFalseOp);
4288 Instruction *NewSel =
4289 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
Misha Brukmanfd939082005-04-21 23:48:37 +00004290
Chris Lattner87875da2005-01-13 22:52:24 +00004291 NewSel = InsertNewInstBefore(NewSel, SI);
Chris Lattner906ab502005-01-14 17:35:12 +00004292 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00004293 }
4294 }
4295 }
4296 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004297
Chris Lattnere576b912004-04-09 23:46:01 +00004298 // See if we can fold the select into one of our operands.
4299 if (SI.getType()->isInteger()) {
4300 // See the comment above GetSelectFoldableOperands for a description of the
4301 // transformation we are doing here.
4302 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4303 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4304 !isa<Constant>(FalseVal))
4305 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4306 unsigned OpToFold = 0;
4307 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4308 OpToFold = 1;
4309 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4310 OpToFold = 2;
4311 }
4312
4313 if (OpToFold) {
4314 Constant *C = GetSelectFoldableConstant(TVI);
4315 std::string Name = TVI->getName(); TVI->setName("");
4316 Instruction *NewSel =
4317 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4318 Name);
4319 InsertNewInstBefore(NewSel, SI);
4320 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4321 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4322 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4323 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4324 else {
4325 assert(0 && "Unknown instruction!!");
4326 }
4327 }
4328 }
Chris Lattnera96879a2004-09-29 17:40:11 +00004329
Chris Lattnere576b912004-04-09 23:46:01 +00004330 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4331 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4332 !isa<Constant>(TrueVal))
4333 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4334 unsigned OpToFold = 0;
4335 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4336 OpToFold = 1;
4337 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4338 OpToFold = 2;
4339 }
4340
4341 if (OpToFold) {
4342 Constant *C = GetSelectFoldableConstant(FVI);
4343 std::string Name = FVI->getName(); FVI->setName("");
4344 Instruction *NewSel =
4345 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4346 Name);
4347 InsertNewInstBefore(NewSel, SI);
4348 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4349 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4350 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4351 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4352 else {
4353 assert(0 && "Unknown instruction!!");
4354 }
4355 }
4356 }
4357 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00004358
4359 if (BinaryOperator::isNot(CondVal)) {
4360 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4361 SI.setOperand(1, FalseVal);
4362 SI.setOperand(2, TrueVal);
4363 return &SI;
4364 }
4365
Chris Lattner3d69f462004-03-12 05:52:32 +00004366 return 0;
4367}
4368
4369
Chris Lattner9fe38862003-06-19 17:00:31 +00004370// CallInst simplification
4371//
4372Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004373 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4374 // visitCallSite.
Chris Lattner35b9e482004-10-12 04:52:52 +00004375 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4376 bool Changed = false;
4377
4378 // memmove/cpy/set of zero bytes is a noop.
4379 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4380 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4381
4382 // FIXME: Increase alignment here.
Misha Brukmanfd939082005-04-21 23:48:37 +00004383
Chris Lattner35b9e482004-10-12 04:52:52 +00004384 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4385 if (CI->getRawValue() == 1) {
4386 // Replace the instruction with just byte operations. We would
4387 // transform other cases to loads/stores, but we don't know if
4388 // alignment is sufficient.
4389 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004390 }
4391
Chris Lattner35b9e482004-10-12 04:52:52 +00004392 // If we have a memmove and the source operation is a constant global,
4393 // then the source and dest pointers can't alias, so we can change this
4394 // into a call to memcpy.
4395 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4396 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4397 if (GVSrc->isConstant()) {
4398 Module *M = CI.getParent()->getParent()->getParent();
4399 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4400 CI.getCalledFunction()->getFunctionType());
4401 CI.setOperand(0, MemCpy);
4402 Changed = true;
4403 }
4404
4405 if (Changed) return &CI;
Chris Lattner954f66a2004-11-18 21:41:39 +00004406 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4407 // If this stoppoint is at the same source location as the previous
4408 // stoppoint in the chain, it is not needed.
4409 if (DbgStopPointInst *PrevSPI =
4410 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4411 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4412 SPI->getColNo() == PrevSPI->getColNo()) {
4413 SPI->replaceAllUsesWith(PrevSPI);
4414 return EraseInstFromFunction(CI);
4415 }
Chris Lattner35b9e482004-10-12 04:52:52 +00004416 }
4417
Chris Lattnera44d8a22003-10-07 22:32:43 +00004418 return visitCallSite(&CI);
Chris Lattner9fe38862003-06-19 17:00:31 +00004419}
4420
4421// InvokeInst simplification
4422//
4423Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00004424 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00004425}
4426
Chris Lattnera44d8a22003-10-07 22:32:43 +00004427// visitCallSite - Improvements for call and invoke instructions.
4428//
4429Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00004430 bool Changed = false;
4431
4432 // If the callee is a constexpr cast of a function, attempt to move the cast
4433 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00004434 if (transformConstExprCastCall(CS)) return 0;
4435
Chris Lattner6c266db2003-10-07 22:54:13 +00004436 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00004437
Chris Lattner08b22ec2005-05-13 07:09:09 +00004438 if (Function *CalleeF = dyn_cast<Function>(Callee))
4439 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4440 Instruction *OldCall = CS.getInstruction();
4441 // If the call and callee calling conventions don't match, this call must
4442 // be unreachable, as the call is undefined.
4443 new StoreInst(ConstantBool::True,
4444 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4445 if (!OldCall->use_empty())
4446 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4447 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4448 return EraseInstFromFunction(*OldCall);
4449 return 0;
4450 }
4451
Chris Lattner17be6352004-10-18 02:59:09 +00004452 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4453 // This instruction is not reachable, just remove it. We insert a store to
4454 // undef so that we know that this code is not reachable, despite the fact
4455 // that we can't modify the CFG here.
4456 new StoreInst(ConstantBool::True,
4457 UndefValue::get(PointerType::get(Type::BoolTy)),
4458 CS.getInstruction());
4459
4460 if (!CS.getInstruction()->use_empty())
4461 CS.getInstruction()->
4462 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4463
4464 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4465 // Don't break the CFG, insert a dummy cond branch.
4466 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4467 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00004468 }
Chris Lattner17be6352004-10-18 02:59:09 +00004469 return EraseInstFromFunction(*CS.getInstruction());
4470 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004471
Chris Lattner6c266db2003-10-07 22:54:13 +00004472 const PointerType *PTy = cast<PointerType>(Callee->getType());
4473 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4474 if (FTy->isVarArg()) {
4475 // See if we can optimize any arguments passed through the varargs area of
4476 // the call.
4477 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4478 E = CS.arg_end(); I != E; ++I)
4479 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4480 // If this cast does not effect the value passed through the varargs
4481 // area, we can eliminate the use of the cast.
4482 Value *Op = CI->getOperand(0);
4483 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4484 *I = Op;
4485 Changed = true;
4486 }
4487 }
4488 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004489
Chris Lattner6c266db2003-10-07 22:54:13 +00004490 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00004491}
4492
Chris Lattner9fe38862003-06-19 17:00:31 +00004493// transformConstExprCastCall - If the callee is a constexpr cast of a function,
4494// attempt to move the cast to the arguments of the call/invoke.
4495//
4496bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4497 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4498 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00004499 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00004500 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00004501 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00004502 Instruction *Caller = CS.getInstruction();
4503
4504 // Okay, this is a cast from a function to a different type. Unless doing so
4505 // would cause a type conversion of one of our arguments, change this call to
4506 // be a direct call with arguments casted to the appropriate types.
4507 //
4508 const FunctionType *FT = Callee->getFunctionType();
4509 const Type *OldRetTy = Caller->getType();
4510
Chris Lattnerf78616b2004-01-14 06:06:08 +00004511 // Check to see if we are changing the return type...
4512 if (OldRetTy != FT->getReturnType()) {
4513 if (Callee->isExternal() &&
4514 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4515 !Caller->use_empty())
4516 return false; // Cannot transform this return value...
4517
4518 // If the callsite is an invoke instruction, and the return value is used by
4519 // a PHI node in a successor, we cannot change the return type of the call
4520 // because there is no place to put the cast instruction (without breaking
4521 // the critical edge). Bail out in this case.
4522 if (!Caller->use_empty())
4523 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4524 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4525 UI != E; ++UI)
4526 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4527 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004528 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00004529 return false;
4530 }
Chris Lattner9fe38862003-06-19 17:00:31 +00004531
4532 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4533 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004534
Chris Lattner9fe38862003-06-19 17:00:31 +00004535 CallSite::arg_iterator AI = CS.arg_begin();
4536 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4537 const Type *ParamTy = FT->getParamType(i);
4538 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanfd939082005-04-21 23:48:37 +00004539 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00004540 }
4541
4542 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4543 Callee->isExternal())
4544 return false; // Do not delete arguments unless we have a function body...
4545
4546 // Okay, we decided that this is a safe thing to do: go ahead and start
4547 // inserting cast instructions as necessary...
4548 std::vector<Value*> Args;
4549 Args.reserve(NumActualArgs);
4550
4551 AI = CS.arg_begin();
4552 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4553 const Type *ParamTy = FT->getParamType(i);
4554 if ((*AI)->getType() == ParamTy) {
4555 Args.push_back(*AI);
4556 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00004557 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4558 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00004559 }
4560 }
4561
4562 // If the function takes more arguments than the call was taking, add them
4563 // now...
4564 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4565 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4566
4567 // If we are removing arguments to the function, emit an obnoxious warning...
4568 if (FT->getNumParams() < NumActualArgs)
4569 if (!FT->isVarArg()) {
4570 std::cerr << "WARNING: While resolving call to function '"
4571 << Callee->getName() << "' arguments were dropped!\n";
4572 } else {
4573 // Add all of the arguments in their promoted form to the arg list...
4574 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4575 const Type *PTy = getPromotedType((*AI)->getType());
4576 if (PTy != (*AI)->getType()) {
4577 // Must promote to pass through va_arg area!
4578 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4579 InsertNewInstBefore(Cast, *Caller);
4580 Args.push_back(Cast);
4581 } else {
4582 Args.push_back(*AI);
4583 }
4584 }
4585 }
4586
4587 if (FT->getReturnType() == Type::VoidTy)
4588 Caller->setName(""); // Void type should not have a name...
4589
4590 Instruction *NC;
4591 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00004592 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00004593 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00004594 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00004595 } else {
4596 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00004597 if (cast<CallInst>(Caller)->isTailCall())
4598 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00004599 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00004600 }
4601
4602 // Insert a cast of the return type as necessary...
4603 Value *NV = NC;
4604 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4605 if (NV->getType() != Type::VoidTy) {
4606 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00004607
4608 // If this is an invoke instruction, we should insert it after the first
4609 // non-phi, instruction in the normal successor block.
4610 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4611 BasicBlock::iterator I = II->getNormalDest()->begin();
4612 while (isa<PHINode>(I)) ++I;
4613 InsertNewInstBefore(NC, *I);
4614 } else {
4615 // Otherwise, it's a call, just insert cast right after the call instr
4616 InsertNewInstBefore(NC, *Caller);
4617 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00004618 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00004619 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00004620 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00004621 }
4622 }
4623
4624 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4625 Caller->replaceAllUsesWith(NV);
4626 Caller->getParent()->getInstList().erase(Caller);
4627 removeFromWorkList(Caller);
4628 return true;
4629}
4630
4631
Chris Lattnerbac32862004-11-14 19:13:23 +00004632// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4633// operator and they all are only used by the PHI, PHI together their
4634// inputs, and do the operation once, to the result of the PHI.
4635Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4636 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4637
4638 // Scan the instruction, looking for input operations that can be folded away.
4639 // If all input operands to the phi are the same instruction (e.g. a cast from
4640 // the same type or "+42") we can pull the operation through the PHI, reducing
4641 // code size and simplifying code.
4642 Constant *ConstantOp = 0;
4643 const Type *CastSrcTy = 0;
4644 if (isa<CastInst>(FirstInst)) {
4645 CastSrcTy = FirstInst->getOperand(0)->getType();
4646 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4647 // Can fold binop or shift if the RHS is a constant.
4648 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4649 if (ConstantOp == 0) return 0;
4650 } else {
4651 return 0; // Cannot fold this operation.
4652 }
4653
4654 // Check to see if all arguments are the same operation.
4655 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4656 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4657 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4658 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4659 return 0;
4660 if (CastSrcTy) {
4661 if (I->getOperand(0)->getType() != CastSrcTy)
4662 return 0; // Cast operation must match.
4663 } else if (I->getOperand(1) != ConstantOp) {
4664 return 0;
4665 }
4666 }
4667
4668 // Okay, they are all the same operation. Create a new PHI node of the
4669 // correct type, and PHI together all of the LHS's of the instructions.
4670 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4671 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00004672 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00004673
4674 Value *InVal = FirstInst->getOperand(0);
4675 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00004676
4677 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00004678 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4679 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4680 if (NewInVal != InVal)
4681 InVal = 0;
4682 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4683 }
4684
4685 Value *PhiVal;
4686 if (InVal) {
4687 // The new PHI unions all of the same values together. This is really
4688 // common, so we handle it intelligently here for compile-time speed.
4689 PhiVal = InVal;
4690 delete NewPN;
4691 } else {
4692 InsertNewInstBefore(NewPN, PN);
4693 PhiVal = NewPN;
4694 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004695
Chris Lattnerbac32862004-11-14 19:13:23 +00004696 // Insert and return the new operation.
4697 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00004698 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00004699 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00004700 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00004701 else
4702 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00004703 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00004704}
Chris Lattnera1be5662002-05-02 17:06:02 +00004705
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004706/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4707/// that is dead.
4708static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4709 if (PN->use_empty()) return true;
4710 if (!PN->hasOneUse()) return false;
4711
4712 // Remember this node, and if we find the cycle, return.
4713 if (!PotentiallyDeadPHIs.insert(PN).second)
4714 return true;
4715
4716 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4717 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00004718
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004719 return false;
4720}
4721
Chris Lattner473945d2002-05-06 18:06:38 +00004722// PHINode simplification
4723//
Chris Lattner7e708292002-06-25 16:13:24 +00004724Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner68ee7362005-08-05 01:04:30 +00004725 if (Value *V = PN.hasConstantValue())
4726 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00004727
4728 // If the only user of this instruction is a cast instruction, and all of the
4729 // incoming values are constants, change this PHI to merge together the casted
4730 // constants.
4731 if (PN.hasOneUse())
4732 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4733 if (CI->getType() != PN.getType()) { // noop casts will be folded
4734 bool AllConstant = true;
4735 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4736 if (!isa<Constant>(PN.getIncomingValue(i))) {
4737 AllConstant = false;
4738 break;
4739 }
4740 if (AllConstant) {
4741 // Make a new PHI with all casted values.
4742 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4743 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4744 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4745 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4746 PN.getIncomingBlock(i));
4747 }
4748
4749 // Update the cast instruction.
4750 CI->setOperand(0, New);
4751 WorkList.push_back(CI); // revisit the cast instruction to fold.
4752 WorkList.push_back(New); // Make sure to revisit the new Phi
4753 return &PN; // PN is now dead!
4754 }
4755 }
Chris Lattnerbac32862004-11-14 19:13:23 +00004756
4757 // If all PHI operands are the same operation, pull them through the PHI,
4758 // reducing code size.
4759 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4760 PN.getIncomingValue(0)->hasOneUse())
4761 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4762 return Result;
4763
Chris Lattnera3fd1c52005-01-17 05:10:15 +00004764 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4765 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4766 // PHI)... break the cycle.
4767 if (PN.hasOneUse())
4768 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4769 std::set<PHINode*> PotentiallyDeadPHIs;
4770 PotentiallyDeadPHIs.insert(&PN);
4771 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4772 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4773 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004774
Chris Lattner60921c92003-12-19 05:58:40 +00004775 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00004776}
4777
Chris Lattner28977af2004-04-05 01:30:19 +00004778static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4779 Instruction *InsertPoint,
4780 InstCombiner *IC) {
4781 unsigned PS = IC->getTargetData().getPointerSize();
4782 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00004783 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4784 // We must insert a cast to ensure we sign-extend.
4785 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4786 V->getName()), *InsertPoint);
4787 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4788 *InsertPoint);
4789}
4790
Chris Lattnera1be5662002-05-02 17:06:02 +00004791
Chris Lattner7e708292002-06-25 16:13:24 +00004792Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00004793 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00004794 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00004795 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004796 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00004797 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004798
Chris Lattnere87597f2004-10-16 18:11:37 +00004799 if (isa<UndefValue>(GEP.getOperand(0)))
4800 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4801
Chris Lattnerc6bd1952004-02-22 05:25:17 +00004802 bool HasZeroPointerIndex = false;
4803 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4804 HasZeroPointerIndex = C->isNullValue();
4805
4806 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00004807 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00004808
Chris Lattner28977af2004-04-05 01:30:19 +00004809 // Eliminate unneeded casts for indices.
4810 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004811 gep_type_iterator GTI = gep_type_begin(GEP);
4812 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4813 if (isa<SequentialType>(*GTI)) {
4814 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4815 Value *Src = CI->getOperand(0);
4816 const Type *SrcTy = Src->getType();
4817 const Type *DestTy = CI->getType();
4818 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004819 if (SrcTy->getPrimitiveSizeInBits() ==
4820 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004821 // We can always eliminate a cast from ulong or long to the other.
4822 // We can always eliminate a cast from uint to int or the other on
4823 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00004824 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004825 MadeChange = true;
4826 GEP.setOperand(i, Src);
4827 }
4828 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4829 SrcTy->getPrimitiveSize() == 4) {
4830 // We can always eliminate a cast from int to [u]long. We can
4831 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4832 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00004833 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00004834 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004835 MadeChange = true;
4836 GEP.setOperand(i, Src);
4837 }
Chris Lattner28977af2004-04-05 01:30:19 +00004838 }
4839 }
4840 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004841 // If we are using a wider index than needed for this platform, shrink it
4842 // to what we need. If the incoming value needs a cast instruction,
4843 // insert it. This explicit cast can make subsequent optimizations more
4844 // obvious.
4845 Value *Op = GEP.getOperand(i);
4846 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00004847 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00004848 GEP.setOperand(i, ConstantExpr::getCast(C,
4849 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00004850 MadeChange = true;
4851 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00004852 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4853 Op->getName()), GEP);
4854 GEP.setOperand(i, Op);
4855 MadeChange = true;
4856 }
Chris Lattner67769e52004-07-20 01:48:15 +00004857
4858 // If this is a constant idx, make sure to canonicalize it to be a signed
4859 // operand, otherwise CSE and other optimizations are pessimized.
4860 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
4861 GEP.setOperand(i, ConstantExpr::getCast(CUI,
4862 CUI->getType()->getSignedVersion()));
4863 MadeChange = true;
4864 }
Chris Lattner28977af2004-04-05 01:30:19 +00004865 }
4866 if (MadeChange) return &GEP;
4867
Chris Lattner90ac28c2002-08-02 19:29:35 +00004868 // Combine Indices - If the source pointer to this getelementptr instruction
4869 // is a getelementptr instruction, combine the indices of the two
4870 // getelementptr instructions into a single instruction.
4871 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00004872 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00004873 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00004874 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00004875
4876 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00004877 // Note that if our source is a gep chain itself that we wait for that
4878 // chain to be resolved before we perform this transformation. This
4879 // avoids us creating a TON of code in some cases.
4880 //
4881 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
4882 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
4883 return 0; // Wait until our source is folded to completion.
4884
Chris Lattner90ac28c2002-08-02 19:29:35 +00004885 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00004886
4887 // Find out whether the last index in the source GEP is a sequential idx.
4888 bool EndsWithSequential = false;
4889 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
4890 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00004891 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00004892
Chris Lattner90ac28c2002-08-02 19:29:35 +00004893 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00004894 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00004895 // Replace: gep (gep %P, long B), long A, ...
4896 // With: T = long A+B; gep %P, T, ...
4897 //
Chris Lattner620ce142004-05-07 22:09:22 +00004898 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00004899 if (SO1 == Constant::getNullValue(SO1->getType())) {
4900 Sum = GO1;
4901 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
4902 Sum = SO1;
4903 } else {
4904 // If they aren't the same type, convert both to an integer of the
4905 // target's pointer size.
4906 if (SO1->getType() != GO1->getType()) {
4907 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
4908 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
4909 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
4910 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
4911 } else {
4912 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00004913 if (SO1->getType()->getPrimitiveSize() == PS) {
4914 // Convert GO1 to SO1's type.
4915 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
4916
4917 } else if (GO1->getType()->getPrimitiveSize() == PS) {
4918 // Convert SO1 to GO1's type.
4919 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
4920 } else {
4921 const Type *PT = TD->getIntPtrType();
4922 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
4923 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
4924 }
4925 }
4926 }
Chris Lattner620ce142004-05-07 22:09:22 +00004927 if (isa<Constant>(SO1) && isa<Constant>(GO1))
4928 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
4929 else {
Chris Lattner48595f12004-06-10 02:07:29 +00004930 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
4931 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00004932 }
Chris Lattner28977af2004-04-05 01:30:19 +00004933 }
Chris Lattner620ce142004-05-07 22:09:22 +00004934
4935 // Recycle the GEP we already have if possible.
4936 if (SrcGEPOperands.size() == 2) {
4937 GEP.setOperand(0, SrcGEPOperands[0]);
4938 GEP.setOperand(1, Sum);
4939 return &GEP;
4940 } else {
4941 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4942 SrcGEPOperands.end()-1);
4943 Indices.push_back(Sum);
4944 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
4945 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004946 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00004947 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00004948 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00004949 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00004950 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
4951 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00004952 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
4953 }
4954
4955 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00004956 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00004957
Chris Lattner620ce142004-05-07 22:09:22 +00004958 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00004959 // GEP of global variable. If all of the indices for this GEP are
4960 // constants, we can promote this to a constexpr instead of an instruction.
4961
4962 // Scan for nonconstants...
4963 std::vector<Constant*> Indices;
4964 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
4965 for (; I != E && isa<Constant>(*I); ++I)
4966 Indices.push_back(cast<Constant>(*I));
4967
4968 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00004969 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00004970
4971 // Replace all uses of the GEP with the new constexpr...
4972 return ReplaceInstUsesWith(GEP, CE);
4973 }
Chris Lattnereed48272005-09-13 00:40:14 +00004974 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
4975 if (!isa<PointerType>(X->getType())) {
4976 // Not interesting. Source pointer must be a cast from pointer.
4977 } else if (HasZeroPointerIndex) {
4978 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
4979 // into : GEP [10 x ubyte]* X, long 0, ...
4980 //
4981 // This occurs when the program declares an array extern like "int X[];"
4982 //
4983 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
4984 const PointerType *XTy = cast<PointerType>(X->getType());
4985 if (const ArrayType *XATy =
4986 dyn_cast<ArrayType>(XTy->getElementType()))
4987 if (const ArrayType *CATy =
4988 dyn_cast<ArrayType>(CPTy->getElementType()))
4989 if (CATy->getElementType() == XATy->getElementType()) {
4990 // At this point, we know that the cast source type is a pointer
4991 // to an array of the same type as the destination pointer
4992 // array. Because the array type is never stepped over (there
4993 // is a leading zero) we can fold the cast into this GEP.
4994 GEP.setOperand(0, X);
4995 return &GEP;
4996 }
4997 } else if (GEP.getNumOperands() == 2) {
4998 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00004999 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5000 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00005001 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5002 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5003 if (isa<ArrayType>(SrcElTy) &&
5004 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5005 TD->getTypeSize(ResElTy)) {
5006 Value *V = InsertNewInstBefore(
5007 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5008 GEP.getOperand(1), GEP.getName()), GEP);
5009 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005010 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00005011
5012 // Transform things like:
5013 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5014 // (where tmp = 8*tmp2) into:
5015 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5016
5017 if (isa<ArrayType>(SrcElTy) &&
5018 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5019 uint64_t ArrayEltSize =
5020 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5021
5022 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5023 // allow either a mul, shift, or constant here.
5024 Value *NewIdx = 0;
5025 ConstantInt *Scale = 0;
5026 if (ArrayEltSize == 1) {
5027 NewIdx = GEP.getOperand(1);
5028 Scale = ConstantInt::get(NewIdx->getType(), 1);
5029 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00005030 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00005031 Scale = CI;
5032 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5033 if (Inst->getOpcode() == Instruction::Shl &&
5034 isa<ConstantInt>(Inst->getOperand(1))) {
5035 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5036 if (Inst->getType()->isSigned())
5037 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5038 else
5039 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5040 NewIdx = Inst->getOperand(0);
5041 } else if (Inst->getOpcode() == Instruction::Mul &&
5042 isa<ConstantInt>(Inst->getOperand(1))) {
5043 Scale = cast<ConstantInt>(Inst->getOperand(1));
5044 NewIdx = Inst->getOperand(0);
5045 }
5046 }
5047
5048 // If the index will be to exactly the right offset with the scale taken
5049 // out, perform the transformation.
5050 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5051 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5052 Scale = ConstantSInt::get(C->getType(),
Chris Lattner6e2f8432005-09-14 17:32:56 +00005053 (int64_t)C->getRawValue() /
5054 (int64_t)ArrayEltSize);
Chris Lattner7835cdd2005-09-13 18:36:04 +00005055 else
5056 Scale = ConstantUInt::get(Scale->getType(),
5057 Scale->getRawValue() / ArrayEltSize);
5058 if (Scale->getRawValue() != 1) {
5059 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5060 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5061 NewIdx = InsertNewInstBefore(Sc, GEP);
5062 }
5063
5064 // Insert the new GEP instruction.
5065 Instruction *Idx =
5066 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5067 NewIdx, GEP.getName());
5068 Idx = InsertNewInstBefore(Idx, GEP);
5069 return new CastInst(Idx, GEP.getType());
5070 }
5071 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005072 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005073 }
5074
Chris Lattner8a2a3112001-12-14 16:52:21 +00005075 return 0;
5076}
5077
Chris Lattner0864acf2002-11-04 16:18:53 +00005078Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5079 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5080 if (AI.isArrayAllocation()) // Check C != 1
5081 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5082 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00005083 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00005084
5085 // Create and insert the replacement instruction...
5086 if (isa<MallocInst>(AI))
Chris Lattner7c881df2004-03-19 06:08:10 +00005087 New = new MallocInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00005088 else {
5089 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattner7c881df2004-03-19 06:08:10 +00005090 New = new AllocaInst(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00005091 }
Chris Lattner7c881df2004-03-19 06:08:10 +00005092
5093 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00005094
Chris Lattner0864acf2002-11-04 16:18:53 +00005095 // Scan to the end of the allocation instructions, to skip over a block of
5096 // allocas if possible...
5097 //
5098 BasicBlock::iterator It = New;
5099 while (isa<AllocationInst>(*It)) ++It;
5100
5101 // Now that I is pointing to the first non-allocation-inst in the block,
5102 // insert our getelementptr instruction...
5103 //
Chris Lattner693787a2005-05-04 19:10:26 +00005104 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5105 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5106 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00005107
5108 // Now make everything use the getelementptr instead of the original
5109 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00005110 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00005111 } else if (isa<UndefValue>(AI.getArraySize())) {
5112 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00005113 }
Chris Lattner7c881df2004-03-19 06:08:10 +00005114
5115 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5116 // Note that we only do this for alloca's, because malloc should allocate and
5117 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00005118 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00005119 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00005120 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5121
Chris Lattner0864acf2002-11-04 16:18:53 +00005122 return 0;
5123}
5124
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005125Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5126 Value *Op = FI.getOperand(0);
5127
5128 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5129 if (CastInst *CI = dyn_cast<CastInst>(Op))
5130 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5131 FI.setOperand(0, CI->getOperand(0));
5132 return &FI;
5133 }
5134
Chris Lattner17be6352004-10-18 02:59:09 +00005135 // free undef -> unreachable.
5136 if (isa<UndefValue>(Op)) {
5137 // Insert a new store to null because we cannot modify the CFG here.
5138 new StoreInst(ConstantBool::True,
5139 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5140 return EraseInstFromFunction(FI);
5141 }
5142
Chris Lattner6160e852004-02-28 04:57:37 +00005143 // If we have 'free null' delete the instruction. This can happen in stl code
5144 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00005145 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005146 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00005147
Chris Lattner67b1e1b2003-12-07 01:24:23 +00005148 return 0;
5149}
5150
5151
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005152/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00005153static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5154 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00005155 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00005156
5157 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00005158 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00005159 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00005160
5161 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5162 // If the source is an array, the code below will not succeed. Check to
5163 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5164 // constants.
5165 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5166 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5167 if (ASrcTy->getNumElements() != 0) {
5168 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5169 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5170 SrcTy = cast<PointerType>(CastOp->getType());
5171 SrcPTy = SrcTy->getElementType();
5172 }
5173
5174 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00005175 // Do not allow turning this into a load of an integer, which is then
5176 // casted to a pointer, this pessimizes pointer analysis a lot.
5177 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005178 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00005179 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00005180
Chris Lattnerf9527852005-01-31 04:50:46 +00005181 // Okay, we are casting from one integer or pointer type to another of
5182 // the same size. Instead of casting the pointer before the load, cast
5183 // the result of the loaded value.
5184 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5185 CI->getName(),
5186 LI.isVolatile()),LI);
5187 // Now cast the result of the load.
5188 return new CastInst(NewLoad, LI.getType());
5189 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00005190 }
5191 }
5192 return 0;
5193}
5194
Chris Lattnerc10aced2004-09-19 18:43:46 +00005195/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00005196/// from this value cannot trap. If it is not obviously safe to load from the
5197/// specified pointer, we do a quick local scan of the basic block containing
5198/// ScanFrom, to determine if the address is already accessed.
5199static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5200 // If it is an alloca or global variable, it is always safe to load from.
5201 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5202
5203 // Otherwise, be a little bit agressive by scanning the local block where we
5204 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005205 // from/to. If so, the previous load or store would have already trapped,
5206 // so there is no harm doing an extra load (also, CSE will later eliminate
5207 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00005208 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5209
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005210 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00005211 --BBI;
5212
5213 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5214 if (LI->getOperand(0) == V) return true;
5215 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5216 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00005217
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00005218 }
Chris Lattner8a375202004-09-19 19:18:10 +00005219 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00005220}
5221
Chris Lattner833b8a42003-06-26 05:06:25 +00005222Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5223 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00005224
Chris Lattner37366c12005-05-01 04:24:53 +00005225 // load (cast X) --> cast (load X) iff safe
5226 if (CastInst *CI = dyn_cast<CastInst>(Op))
5227 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5228 return Res;
5229
5230 // None of the following transforms are legal for volatile loads.
5231 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00005232
Chris Lattner62f254d2005-09-12 22:00:15 +00005233 if (&LI.getParent()->front() != &LI) {
5234 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00005235 // If the instruction immediately before this is a store to the same
5236 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00005237 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5238 if (SI->getOperand(1) == LI.getOperand(0))
5239 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00005240 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5241 if (LIB->getOperand(0) == LI.getOperand(0))
5242 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00005243 }
Chris Lattner37366c12005-05-01 04:24:53 +00005244
5245 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5246 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5247 isa<UndefValue>(GEPI->getOperand(0))) {
5248 // Insert a new store to null instruction before the load to indicate
5249 // that this code is not reachable. We do this instead of inserting
5250 // an unreachable instruction directly because we cannot modify the
5251 // CFG.
5252 new StoreInst(UndefValue::get(LI.getType()),
5253 Constant::getNullValue(Op->getType()), &LI);
5254 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5255 }
5256
Chris Lattnere87597f2004-10-16 18:11:37 +00005257 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00005258 // load null/undef -> undef
5259 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00005260 // Insert a new store to null instruction before the load to indicate that
5261 // this code is not reachable. We do this instead of inserting an
5262 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00005263 new StoreInst(UndefValue::get(LI.getType()),
5264 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00005265 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00005266 }
Chris Lattner833b8a42003-06-26 05:06:25 +00005267
Chris Lattnere87597f2004-10-16 18:11:37 +00005268 // Instcombine load (constant global) into the value loaded.
5269 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5270 if (GV->isConstant() && !GV->isExternal())
5271 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00005272
Chris Lattnere87597f2004-10-16 18:11:37 +00005273 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5274 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5275 if (CE->getOpcode() == Instruction::GetElementPtr) {
5276 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5277 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00005278 if (Constant *V =
5279 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00005280 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00005281 if (CE->getOperand(0)->isNullValue()) {
5282 // Insert a new store to null instruction before the load to indicate
5283 // that this code is not reachable. We do this instead of inserting
5284 // an unreachable instruction directly because we cannot modify the
5285 // CFG.
5286 new StoreInst(UndefValue::get(LI.getType()),
5287 Constant::getNullValue(Op->getType()), &LI);
5288 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5289 }
5290
Chris Lattnere87597f2004-10-16 18:11:37 +00005291 } else if (CE->getOpcode() == Instruction::Cast) {
5292 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5293 return Res;
5294 }
5295 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00005296
Chris Lattner37366c12005-05-01 04:24:53 +00005297 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00005298 // Change select and PHI nodes to select values instead of addresses: this
5299 // helps alias analysis out a lot, allows many others simplifications, and
5300 // exposes redundancy in the code.
5301 //
5302 // Note that we cannot do the transformation unless we know that the
5303 // introduced loads cannot trap! Something like this is valid as long as
5304 // the condition is always false: load (select bool %C, int* null, int* %G),
5305 // but it would not be valid if we transformed it to load from null
5306 // unconditionally.
5307 //
5308 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5309 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00005310 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5311 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00005312 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005313 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00005314 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005315 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00005316 return new SelectInst(SI->getCondition(), V1, V2);
5317 }
5318
Chris Lattner684fe212004-09-23 15:46:00 +00005319 // load (select (cond, null, P)) -> load P
5320 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5321 if (C->isNullValue()) {
5322 LI.setOperand(0, SI->getOperand(2));
5323 return &LI;
5324 }
5325
5326 // load (select (cond, P, null)) -> load P
5327 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5328 if (C->isNullValue()) {
5329 LI.setOperand(0, SI->getOperand(1));
5330 return &LI;
5331 }
5332
Chris Lattnerc10aced2004-09-19 18:43:46 +00005333 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5334 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005335 bool Safe = PN->getParent() == LI.getParent();
5336
5337 // Scan all of the instructions between the PHI and the load to make
5338 // sure there are no instructions that might possibly alter the value
5339 // loaded from the PHI.
5340 if (Safe) {
5341 BasicBlock::iterator I = &LI;
5342 for (--I; !isa<PHINode>(I); --I)
5343 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5344 Safe = false;
5345 break;
5346 }
5347 }
5348
5349 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00005350 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005351 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00005352 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00005353
Chris Lattnerc10aced2004-09-19 18:43:46 +00005354 if (Safe) {
5355 // Create the PHI.
5356 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5357 InsertNewInstBefore(NewPN, *PN);
5358 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5359
5360 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5361 BasicBlock *BB = PN->getIncomingBlock(i);
5362 Value *&TheLoad = LoadMap[BB];
5363 if (TheLoad == 0) {
5364 Value *InVal = PN->getIncomingValue(i);
5365 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5366 InVal->getName()+".val"),
5367 *BB->getTerminator());
5368 }
5369 NewPN->addIncoming(TheLoad, BB);
5370 }
5371 return ReplaceInstUsesWith(LI, NewPN);
5372 }
5373 }
5374 }
Chris Lattner833b8a42003-06-26 05:06:25 +00005375 return 0;
5376}
5377
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005378/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5379/// when possible.
5380static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5381 User *CI = cast<User>(SI.getOperand(1));
5382 Value *CastOp = CI->getOperand(0);
5383
5384 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5385 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5386 const Type *SrcPTy = SrcTy->getElementType();
5387
5388 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5389 // If the source is an array, the code below will not succeed. Check to
5390 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5391 // constants.
5392 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5393 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5394 if (ASrcTy->getNumElements() != 0) {
5395 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5396 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5397 SrcTy = cast<PointerType>(CastOp->getType());
5398 SrcPTy = SrcTy->getElementType();
5399 }
5400
5401 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005402 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005403 IC.getTargetData().getTypeSize(DestPTy)) {
5404
5405 // Okay, we are casting from one integer or pointer type to another of
5406 // the same size. Instead of casting the pointer before the store, cast
5407 // the value to be stored.
5408 Value *NewCast;
5409 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5410 NewCast = ConstantExpr::getCast(C, SrcPTy);
5411 else
5412 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5413 SrcPTy,
5414 SI.getOperand(0)->getName()+".c"), SI);
5415
5416 return new StoreInst(NewCast, CastOp);
5417 }
5418 }
5419 }
5420 return 0;
5421}
5422
Chris Lattner2f503e62005-01-31 05:36:43 +00005423Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5424 Value *Val = SI.getOperand(0);
5425 Value *Ptr = SI.getOperand(1);
5426
5427 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5428 removeFromWorkList(&SI);
5429 SI.eraseFromParent();
5430 ++NumCombined;
5431 return 0;
5432 }
5433
5434 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5435
5436 // store X, null -> turns into 'unreachable' in SimplifyCFG
5437 if (isa<ConstantPointerNull>(Ptr)) {
5438 if (!isa<UndefValue>(Val)) {
5439 SI.setOperand(0, UndefValue::get(Val->getType()));
5440 if (Instruction *U = dyn_cast<Instruction>(Val))
5441 WorkList.push_back(U); // Dropped a use.
5442 ++NumCombined;
5443 }
5444 return 0; // Do not modify these!
5445 }
5446
5447 // store undef, Ptr -> noop
5448 if (isa<UndefValue>(Val)) {
5449 removeFromWorkList(&SI);
5450 SI.eraseFromParent();
5451 ++NumCombined;
5452 return 0;
5453 }
5454
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00005455 // If the pointer destination is a cast, see if we can fold the cast into the
5456 // source instead.
5457 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5458 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5459 return Res;
5460 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5461 if (CE->getOpcode() == Instruction::Cast)
5462 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5463 return Res;
5464
Chris Lattner408902b2005-09-12 23:23:25 +00005465
5466 // If this store is the last instruction in the basic block, and if the block
5467 // ends with an unconditional branch, try to move it to the successor block.
5468 BasicBlock::iterator BBI = &SI; ++BBI;
5469 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5470 if (BI->isUnconditional()) {
5471 // Check to see if the successor block has exactly two incoming edges. If
5472 // so, see if the other predecessor contains a store to the same location.
5473 // if so, insert a PHI node (if needed) and move the stores down.
5474 BasicBlock *Dest = BI->getSuccessor(0);
5475
5476 pred_iterator PI = pred_begin(Dest);
5477 BasicBlock *Other = 0;
5478 if (*PI != BI->getParent())
5479 Other = *PI;
5480 ++PI;
5481 if (PI != pred_end(Dest)) {
5482 if (*PI != BI->getParent())
5483 if (Other)
5484 Other = 0;
5485 else
5486 Other = *PI;
5487 if (++PI != pred_end(Dest))
5488 Other = 0;
5489 }
5490 if (Other) { // If only one other pred...
5491 BBI = Other->getTerminator();
5492 // Make sure this other block ends in an unconditional branch and that
5493 // there is an instruction before the branch.
5494 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5495 BBI != Other->begin()) {
5496 --BBI;
5497 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5498
5499 // If this instruction is a store to the same location.
5500 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5501 // Okay, we know we can perform this transformation. Insert a PHI
5502 // node now if we need it.
5503 Value *MergedVal = OtherStore->getOperand(0);
5504 if (MergedVal != SI.getOperand(0)) {
5505 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5506 PN->reserveOperandSpace(2);
5507 PN->addIncoming(SI.getOperand(0), SI.getParent());
5508 PN->addIncoming(OtherStore->getOperand(0), Other);
5509 MergedVal = InsertNewInstBefore(PN, Dest->front());
5510 }
5511
5512 // Advance to a place where it is safe to insert the new store and
5513 // insert it.
5514 BBI = Dest->begin();
5515 while (isa<PHINode>(BBI)) ++BBI;
5516 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5517 OtherStore->isVolatile()), *BBI);
5518
5519 // Nuke the old stores.
5520 removeFromWorkList(&SI);
5521 removeFromWorkList(OtherStore);
5522 SI.eraseFromParent();
5523 OtherStore->eraseFromParent();
5524 ++NumCombined;
5525 return 0;
5526 }
5527 }
5528 }
5529 }
5530
Chris Lattner2f503e62005-01-31 05:36:43 +00005531 return 0;
5532}
5533
5534
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005535Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5536 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00005537 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005538 BasicBlock *TrueDest;
5539 BasicBlock *FalseDest;
5540 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5541 !isa<Constant>(X)) {
5542 // Swap Destinations and condition...
5543 BI.setCondition(X);
5544 BI.setSuccessor(0, FalseDest);
5545 BI.setSuccessor(1, TrueDest);
5546 return &BI;
5547 }
5548
5549 // Cannonicalize setne -> seteq
5550 Instruction::BinaryOps Op; Value *Y;
5551 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5552 TrueDest, FalseDest)))
5553 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5554 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5555 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5556 std::string Name = I->getName(); I->setName("");
5557 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5558 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00005559 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005560 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00005561 BI.setSuccessor(0, FalseDest);
5562 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005563 removeFromWorkList(I);
5564 I->getParent()->getInstList().erase(I);
5565 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00005566 return &BI;
5567 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005568
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00005569 return 0;
5570}
Chris Lattner0864acf2002-11-04 16:18:53 +00005571
Chris Lattner46238a62004-07-03 00:26:11 +00005572Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5573 Value *Cond = SI.getCondition();
5574 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5575 if (I->getOpcode() == Instruction::Add)
5576 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5577 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5578 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00005579 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00005580 AddRHS));
5581 SI.setOperand(0, I->getOperand(0));
5582 WorkList.push_back(I);
5583 return &SI;
5584 }
5585 }
5586 return 0;
5587}
5588
Chris Lattner8a2a3112001-12-14 16:52:21 +00005589
Chris Lattner62b14df2002-09-02 04:59:56 +00005590void InstCombiner::removeFromWorkList(Instruction *I) {
5591 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5592 WorkList.end());
5593}
5594
Chris Lattnerea1c4542004-12-08 23:43:58 +00005595
5596/// TryToSinkInstruction - Try to move the specified instruction from its
5597/// current block into the beginning of DestBlock, which can only happen if it's
5598/// safe to move the instruction past all of the instructions between it and the
5599/// end of its block.
5600static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5601 assert(I->hasOneUse() && "Invariants didn't hold!");
5602
5603 // Cannot move control-flow-involving instructions.
5604 if (isa<PHINode>(I) || isa<InvokeInst>(I) || isa<CallInst>(I)) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00005605
Chris Lattnerea1c4542004-12-08 23:43:58 +00005606 // Do not sink alloca instructions out of the entry block.
5607 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5608 return false;
5609
Chris Lattner96a52a62004-12-09 07:14:34 +00005610 // We can only sink load instructions if there is nothing between the load and
5611 // the end of block that could change the value.
5612 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5613 if (LI->isVolatile()) return false; // Don't sink volatile loads.
5614
5615 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5616 Scan != E; ++Scan)
5617 if (Scan->mayWriteToMemory())
5618 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00005619 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00005620
5621 BasicBlock::iterator InsertPos = DestBlock->begin();
5622 while (isa<PHINode>(InsertPos)) ++InsertPos;
5623
Chris Lattner4bc5f802005-08-08 19:11:57 +00005624 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00005625 ++NumSunkInst;
5626 return true;
5627}
5628
Chris Lattner7e708292002-06-25 16:13:24 +00005629bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005630 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00005631 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00005632
Chris Lattnerb3d59702005-07-07 20:40:38 +00005633 {
5634 // Populate the worklist with the reachable instructions.
5635 std::set<BasicBlock*> Visited;
5636 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5637 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5638 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5639 WorkList.push_back(I);
Jeff Cohen00b168892005-07-27 06:12:32 +00005640
Chris Lattnerb3d59702005-07-07 20:40:38 +00005641 // Do a quick scan over the function. If we find any blocks that are
5642 // unreachable, remove any instructions inside of them. This prevents
5643 // the instcombine code from having to deal with some bad special cases.
5644 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5645 if (!Visited.count(BB)) {
5646 Instruction *Term = BB->getTerminator();
5647 while (Term != BB->begin()) { // Remove instrs bottom-up
5648 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00005649
Chris Lattnerb3d59702005-07-07 20:40:38 +00005650 DEBUG(std::cerr << "IC: DCE: " << *I);
5651 ++NumDeadInst;
5652
5653 if (!I->use_empty())
5654 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5655 I->eraseFromParent();
5656 }
5657 }
5658 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00005659
5660 while (!WorkList.empty()) {
5661 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5662 WorkList.pop_back();
5663
Misha Brukmana3bbcb52002-10-29 23:06:16 +00005664 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00005665 // Check to see if we can DIE the instruction...
5666 if (isInstructionTriviallyDead(I)) {
5667 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00005668 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005669 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00005670 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005671
Chris Lattnerad5fec12005-01-28 19:32:01 +00005672 DEBUG(std::cerr << "IC: DCE: " << *I);
5673
5674 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00005675 removeFromWorkList(I);
5676 continue;
5677 }
Chris Lattner62b14df2002-09-02 04:59:56 +00005678
Misha Brukmana3bbcb52002-10-29 23:06:16 +00005679 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00005680 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005681 Value* Ptr = I->getOperand(0);
Chris Lattner061718c2004-10-16 19:44:59 +00005682 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005683 cast<Constant>(Ptr)->isNullValue() &&
5684 !isa<ConstantPointerNull>(C) &&
5685 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner061718c2004-10-16 19:44:59 +00005686 // If this is a constant expr gep that is effectively computing an
5687 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5688 bool isFoldableGEP = true;
5689 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5690 if (!isa<ConstantInt>(I->getOperand(i)))
5691 isFoldableGEP = false;
5692 if (isFoldableGEP) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00005693 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner061718c2004-10-16 19:44:59 +00005694 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5695 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00005696 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00005697 C = ConstantExpr::getCast(C, I->getType());
5698 }
5699 }
5700
Chris Lattnerad5fec12005-01-28 19:32:01 +00005701 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5702
Chris Lattner62b14df2002-09-02 04:59:56 +00005703 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005704 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00005705 ReplaceInstUsesWith(*I, C);
5706
Chris Lattner62b14df2002-09-02 04:59:56 +00005707 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00005708 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00005709 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005710 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00005711 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00005712
Chris Lattnerea1c4542004-12-08 23:43:58 +00005713 // See if we can trivially sink this instruction to a successor basic block.
5714 if (I->hasOneUse()) {
5715 BasicBlock *BB = I->getParent();
5716 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5717 if (UserParent != BB) {
5718 bool UserIsSuccessor = false;
5719 // See if the user is one of our successors.
5720 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5721 if (*SI == UserParent) {
5722 UserIsSuccessor = true;
5723 break;
5724 }
5725
5726 // If the user is one of our immediate successors, and if that successor
5727 // only has us as a predecessors (we'd have to split the critical edge
5728 // otherwise), we can keep going.
5729 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5730 next(pred_begin(UserParent)) == pred_end(UserParent))
5731 // Okay, the CFG is simple enough, try to sink this instruction.
5732 Changed |= TryToSinkInstruction(I, UserParent);
5733 }
5734 }
5735
Chris Lattner8a2a3112001-12-14 16:52:21 +00005736 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00005737 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00005738 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005739 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005740 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00005741 DEBUG(std::cerr << "IC: Old = " << *I
5742 << " New = " << *Result);
5743
Chris Lattnerf523d062004-06-09 05:08:07 +00005744 // Everything uses the new instruction now.
5745 I->replaceAllUsesWith(Result);
5746
5747 // Push the new instruction and any users onto the worklist.
5748 WorkList.push_back(Result);
5749 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005750
5751 // Move the name to the new instruction first...
5752 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00005753 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005754
5755 // Insert the new instruction into the basic block...
5756 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00005757 BasicBlock::iterator InsertPos = I;
5758
5759 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5760 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5761 ++InsertPos;
5762
5763 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005764
Chris Lattner00d51312004-05-01 23:27:23 +00005765 // Make sure that we reprocess all operands now that we reduced their
5766 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00005767 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5768 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5769 WorkList.push_back(OpI);
5770
Chris Lattnerf523d062004-06-09 05:08:07 +00005771 // Instructions can end up on the worklist more than once. Make sure
5772 // we do not process an instruction that has been deleted.
5773 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00005774
5775 // Erase the old instruction.
5776 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005777 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00005778 DEBUG(std::cerr << "IC: MOD = " << *I);
5779
Chris Lattner90ac28c2002-08-02 19:29:35 +00005780 // If the instruction was modified, it's possible that it is now dead.
5781 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00005782 if (isInstructionTriviallyDead(I)) {
5783 // Make sure we process all operands now that we are reducing their
5784 // use counts.
5785 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5786 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5787 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00005788
Chris Lattner00d51312004-05-01 23:27:23 +00005789 // Instructions may end up in the worklist more than once. Erase all
5790 // occurrances of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00005791 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00005792 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00005793 } else {
5794 WorkList.push_back(Result);
5795 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00005796 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00005797 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005798 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005799 }
5800 }
5801
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005802 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005803}
5804
Brian Gaeke96d4bf72004-07-27 17:43:21 +00005805FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005806 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00005807}
Brian Gaeked0fde302003-11-11 22:41:34 +00005808