blob: 1c4bceaef40dfbf87c503854786e68763bb25d3a [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 Lattnerdac58ad2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000058
Chris Lattnerdd841ae2002-04-18 17:39:14 +000059namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner9ca96412006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattnerea1c4542004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000065
Chris Lattnerf57b8452002-04-27 06:56:12 +000066 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000067 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000070 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000071
Chris Lattner7bcc0e72004-02-28 05:22:00 +000072 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
74 /// now.
75 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +000076 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000077 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000078 UI != UE; ++UI)
79 WorkList.push_back(cast<Instruction>(*UI));
80 }
81
Chris Lattner7bcc0e72004-02-28 05:22:00 +000082 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
84 ///
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
89 }
90
Chris Lattner62b14df2002-09-02 04:59:56 +000091 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000093 public:
Chris Lattner7e708292002-06-25 16:13:24 +000094 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000095
Chris Lattner97e52e42002-04-28 21:27:06 +000096 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000097 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000098 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000099 }
100
Chris Lattner28977af2004-04-05 01:30:19 +0000101 TargetData &getTargetData() const { return *TD; }
102
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
105 // Return Value:
106 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000107 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000108 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000109 //
Chris Lattner7e708292002-06-25 16:13:24 +0000110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120
Chris Lattner574da9b2005-01-13 20:14:25 +0000121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000123 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner4d5542c2006-01-06 07:12:35 +0000124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125 ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000126 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000129 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000134 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000135 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000136 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000137 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000138 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000139 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000140 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000141 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000142 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000143
144 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000145 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000146
Chris Lattner9fe38862003-06-19 17:00:31 +0000147 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000148 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000149 bool transformConstExprCastCall(CallSite CS);
150
Chris Lattner28977af2004-04-05 01:30:19 +0000151 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000152 // InsertNewInstBefore - insert an instruction New before instruction Old
153 // in the program. Add the new instruction to the worklist.
154 //
Chris Lattner955f3312004-09-28 21:48:02 +0000155 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000156 assert(New && New->getParent() == 0 &&
157 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000158 BasicBlock *BB = Old.getParent();
159 BB->getInstList().insert(&Old, New); // Insert inst
160 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000161 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000162 }
163
Chris Lattner0c967662004-09-24 15:21:34 +0000164 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
165 /// This also adds the cast to the worklist. Finally, this returns the
166 /// cast.
167 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
168 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000169
Chris Lattnere2ed0572006-04-06 19:19:17 +0000170 if (Constant *CV = dyn_cast<Constant>(V))
171 return ConstantExpr::getCast(CV, Ty);
172
Chris Lattner0c967662004-09-24 15:21:34 +0000173 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
174 WorkList.push_back(C);
175 return C;
176 }
177
Chris Lattner8b170942002-08-09 23:47:40 +0000178 // ReplaceInstUsesWith - This method is to be used when an instruction is
179 // found to be dead, replacable with another preexisting expression. Here
180 // we add all uses of I to the worklist, replace all uses of I with the new
181 // value, then return I, so that the inst combiner will know that I was
182 // modified.
183 //
184 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000185 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000186 if (&I != V) {
187 I.replaceAllUsesWith(V);
188 return &I;
189 } else {
190 // If we are replacing the instruction with itself, this must be in a
191 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000192 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000193 return &I;
194 }
Chris Lattner8b170942002-08-09 23:47:40 +0000195 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000196
Chris Lattner6dce1a72006-02-07 06:56:34 +0000197 // UpdateValueUsesWith - This method is to be used when an value is
198 // found to be replacable with another preexisting expression or was
199 // updated. Here we add all uses of I to the worklist, replace all uses of
200 // I with the new value (unless the instruction was just updated), then
201 // return true, so that the inst combiner will know that I was modified.
202 //
203 bool UpdateValueUsesWith(Value *Old, Value *New) {
204 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
205 if (Old != New)
206 Old->replaceAllUsesWith(New);
207 if (Instruction *I = dyn_cast<Instruction>(Old))
208 WorkList.push_back(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000209 if (Instruction *I = dyn_cast<Instruction>(New))
210 WorkList.push_back(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000211 return true;
212 }
213
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000214 // EraseInstFromFunction - When dealing with an instruction that has side
215 // effects or produces a void value, we can't rely on DCE to delete the
216 // instruction. Instead, visit methods should return the value returned by
217 // this function.
218 Instruction *EraseInstFromFunction(Instruction &I) {
219 assert(I.use_empty() && "Cannot erase instruction that is used!");
220 AddUsesToWorkList(I);
221 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000222 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000223 return 0; // Don't do anything with FI
224 }
225
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000226 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000227 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
228 /// InsertBefore instruction. This is specialized a bit to avoid inserting
229 /// casts that are known to not do anything...
230 ///
231 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
232 Instruction *InsertBefore);
233
Chris Lattnerc8802d22003-03-11 00:12:48 +0000234 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000235 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000236 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000237
Chris Lattner255d8912006-02-11 09:31:47 +0000238 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
239 uint64_t &KnownZero, uint64_t &KnownOne,
240 unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000241
242 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
243 // PHI node as operand #0, see if we can fold the instruction into the PHI
244 // (which is only possible if all operands to the PHI are constants).
245 Instruction *FoldOpIntoPhi(Instruction &I);
246
Chris Lattnerbac32862004-11-14 19:13:23 +0000247 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
248 // operator and they all are only used by the PHI, PHI together their
249 // inputs, and do the operation once, to the result of the PHI.
250 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
251
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000252 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
253 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000254
255 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
256 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000257 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
258 bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000259 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000260 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000261
Chris Lattnera6275cc2002-07-26 21:12:46 +0000262 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000263}
264
Chris Lattner4f98c562003-03-10 21:43:22 +0000265// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000266// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000267static unsigned getComplexity(Value *V) {
268 if (isa<Instruction>(V)) {
269 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000270 return 3;
271 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000272 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000273 if (isa<Argument>(V)) return 3;
274 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000275}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000276
Chris Lattnerc8802d22003-03-11 00:12:48 +0000277// isOnlyUse - Return true if this instruction will be deleted if we stop using
278// it.
279static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000280 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000281}
282
Chris Lattner4cb170c2004-02-23 06:38:22 +0000283// getPromotedType - Return the specified type promoted as it would be to pass
284// though a va_arg area...
285static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000286 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000287 case Type::SByteTyID:
288 case Type::ShortTyID: return Type::IntTy;
289 case Type::UByteTyID:
290 case Type::UShortTyID: return Type::UIntTy;
291 case Type::FloatTyID: return Type::DoubleTy;
292 default: return Ty;
293 }
294}
295
Chris Lattnereed48272005-09-13 00:40:14 +0000296/// isCast - If the specified operand is a CastInst or a constant expr cast,
297/// return the operand value, otherwise return null.
298static Value *isCast(Value *V) {
299 if (CastInst *I = dyn_cast<CastInst>(V))
300 return I->getOperand(0);
301 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
302 if (CE->getOpcode() == Instruction::Cast)
303 return CE->getOperand(0);
304 return 0;
305}
306
Chris Lattner4f98c562003-03-10 21:43:22 +0000307// SimplifyCommutative - This performs a few simplifications for commutative
308// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000309//
Chris Lattner4f98c562003-03-10 21:43:22 +0000310// 1. Order operands such that they are listed from right (least complex) to
311// left (most complex). This puts constants before unary operators before
312// binary operators.
313//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000314// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
315// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000316//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000317bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000318 bool Changed = false;
319 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
320 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000321
Chris Lattner4f98c562003-03-10 21:43:22 +0000322 if (!I.isAssociative()) return Changed;
323 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000324 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
325 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
326 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000327 Constant *Folded = ConstantExpr::get(I.getOpcode(),
328 cast<Constant>(I.getOperand(1)),
329 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000330 I.setOperand(0, Op->getOperand(0));
331 I.setOperand(1, Folded);
332 return true;
333 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
334 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
335 isOnlyUse(Op) && isOnlyUse(Op1)) {
336 Constant *C1 = cast<Constant>(Op->getOperand(1));
337 Constant *C2 = cast<Constant>(Op1->getOperand(1));
338
339 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000340 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000341 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
342 Op1->getOperand(0),
343 Op1->getName(), &I);
344 WorkList.push_back(New);
345 I.setOperand(0, New);
346 I.setOperand(1, Folded);
347 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000348 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000349 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000350 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000351}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000352
Chris Lattner8d969642003-03-10 23:06:50 +0000353// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
354// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000355//
Chris Lattner8d969642003-03-10 23:06:50 +0000356static inline Value *dyn_castNegVal(Value *V) {
357 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000358 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000359
Chris Lattner0ce85802004-12-14 20:08:06 +0000360 // Constants can be considered to be negated values if they can be folded.
361 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
362 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000363 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000364}
365
Chris Lattner8d969642003-03-10 23:06:50 +0000366static inline Value *dyn_castNotVal(Value *V) {
367 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000368 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000369
370 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000371 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000372 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000373 return 0;
374}
375
Chris Lattnerc8802d22003-03-11 00:12:48 +0000376// dyn_castFoldableMul - If this value is a multiply that can be folded into
377// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000378// non-constant operand of the multiply, and set CST to point to the multiplier.
379// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000380//
Chris Lattner50af16a2004-11-13 19:50:12 +0000381static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000382 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000383 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000384 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000385 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000386 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000387 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000388 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000389 // The multiplier is really 1 << CST.
390 Constant *One = ConstantInt::get(V->getType(), 1);
391 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
392 return I->getOperand(0);
393 }
394 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000395 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000396}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000397
Chris Lattner574da9b2005-01-13 20:14:25 +0000398/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
399/// expression, return it.
400static User *dyn_castGetElementPtr(Value *V) {
401 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
403 if (CE->getOpcode() == Instruction::GetElementPtr)
404 return cast<User>(V);
405 return false;
406}
407
Chris Lattner955f3312004-09-28 21:48:02 +0000408// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000409static ConstantInt *AddOne(ConstantInt *C) {
410 return cast<ConstantInt>(ConstantExpr::getAdd(C,
411 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000412}
Chris Lattnera96879a2004-09-29 17:40:11 +0000413static ConstantInt *SubOne(ConstantInt *C) {
414 return cast<ConstantInt>(ConstantExpr::getSub(C,
415 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000416}
417
Chris Lattner255d8912006-02-11 09:31:47 +0000418/// GetConstantInType - Return a ConstantInt with the specified type and value.
419///
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000420static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner255d8912006-02-11 09:31:47 +0000421 if (Ty->isUnsigned())
422 return ConstantUInt::get(Ty, Val);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000423 else if (Ty->getTypeID() == Type::BoolTyID)
424 return ConstantBool::get(Val);
Chris Lattner255d8912006-02-11 09:31:47 +0000425 int64_t SVal = Val;
426 SVal <<= 64-Ty->getPrimitiveSizeInBits();
427 SVal >>= 64-Ty->getPrimitiveSizeInBits();
428 return ConstantSInt::get(Ty, SVal);
429}
430
431
Chris Lattner68d5ff22006-02-09 07:38:58 +0000432/// ComputeMaskedBits - Determine which of the bits specified in Mask are
433/// known to be either zero or one and return them in the KnownZero/KnownOne
434/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
435/// processing.
436static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
437 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000438 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
439 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000440 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000441 // optimized based on the contradictory assumption that it is non-zero.
442 // Because instcombine aggressively folds operations with undef args anyway,
443 // this won't lose us code quality.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000444 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
445 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000446 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000447 KnownZero = ~KnownOne & Mask;
448 return;
449 }
450
451 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000452 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000453 return; // Limit search depth.
454
455 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000456 Instruction *I = dyn_cast<Instruction>(V);
457 if (!I) return;
458
459 switch (I->getOpcode()) {
460 case Instruction::And:
461 // If either the LHS or the RHS are Zero, the result is zero.
462 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
463 Mask &= ~KnownZero;
464 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
465 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
466 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
467
468 // Output known-1 bits are only known if set in both the LHS & RHS.
469 KnownOne &= KnownOne2;
470 // Output known-0 are known to be clear if zero in either the LHS | RHS.
471 KnownZero |= KnownZero2;
472 return;
473 case Instruction::Or:
474 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
475 Mask &= ~KnownOne;
476 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
477 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
478 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
479
480 // Output known-0 bits are only known if clear in both the LHS & RHS.
481 KnownZero &= KnownZero2;
482 // Output known-1 are known to be set if set in either the LHS | RHS.
483 KnownOne |= KnownOne2;
484 return;
485 case Instruction::Xor: {
486 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
487 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
488 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
489 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
490
491 // Output known-0 bits are known if clear or set in both the LHS & RHS.
492 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
493 // Output known-1 are known to be set if set in only one of the LHS, RHS.
494 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
495 KnownZero = KnownZeroOut;
496 return;
497 }
498 case Instruction::Select:
499 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
500 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
501 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
502 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
503
504 // Only known if known in both the LHS and RHS.
505 KnownOne &= KnownOne2;
506 KnownZero &= KnownZero2;
507 return;
508 case Instruction::Cast: {
509 const Type *SrcTy = I->getOperand(0)->getType();
510 if (!SrcTy->isIntegral()) return;
511
512 // If this is an integer truncate or noop, just look in the input.
513 if (SrcTy->getPrimitiveSizeInBits() >=
514 I->getType()->getPrimitiveSizeInBits()) {
515 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000516 return;
517 }
Chris Lattner68d5ff22006-02-09 07:38:58 +0000518
Chris Lattner255d8912006-02-11 09:31:47 +0000519 // Sign or Zero extension. Compute the bits in the result that are not
520 // present in the input.
521 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
522 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000523
Chris Lattner255d8912006-02-11 09:31:47 +0000524 // Handle zero extension.
525 if (!SrcTy->isSigned()) {
526 Mask &= SrcTy->getIntegralTypeMask();
527 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
528 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
529 // The top bits are known to be zero.
530 KnownZero |= NewBits;
531 } else {
532 // Sign extension.
533 Mask &= SrcTy->getIntegralTypeMask();
534 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
535 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000536
Chris Lattner255d8912006-02-11 09:31:47 +0000537 // If the sign bit of the input is known set or clear, then we know the
538 // top bits of the result.
539 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
540 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner68d5ff22006-02-09 07:38:58 +0000541 KnownZero |= NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000542 KnownOne &= ~NewBits;
543 } else if (KnownOne & InSignBit) { // Input sign bit known set
544 KnownOne |= NewBits;
545 KnownZero &= ~NewBits;
546 } else { // Input sign bit unknown
547 KnownZero &= ~NewBits;
548 KnownOne &= ~NewBits;
549 }
550 }
551 return;
552 }
553 case Instruction::Shl:
554 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
555 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
556 Mask >>= SA->getValue();
557 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
558 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
559 KnownZero <<= SA->getValue();
560 KnownOne <<= SA->getValue();
561 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
562 return;
563 }
564 break;
565 case Instruction::Shr:
566 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
567 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
568 // Compute the new bits that are at the top now.
569 uint64_t HighBits = (1ULL << SA->getValue())-1;
570 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
571
572 if (I->getType()->isUnsigned()) { // Unsigned shift right.
573 Mask <<= SA->getValue();
574 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
575 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
576 KnownZero >>= SA->getValue();
577 KnownOne >>= SA->getValue();
578 KnownZero |= HighBits; // high bits known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000579 } else {
Chris Lattner255d8912006-02-11 09:31:47 +0000580 Mask <<= SA->getValue();
581 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
582 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
583 KnownZero >>= SA->getValue();
584 KnownOne >>= SA->getValue();
585
586 // Handle the sign bits.
587 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
588 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
589
590 if (KnownZero & SignBit) { // New bits are known zero.
591 KnownZero |= HighBits;
592 } else if (KnownOne & SignBit) { // New bits are known one.
593 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000594 }
595 }
596 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000597 }
Chris Lattner255d8912006-02-11 09:31:47 +0000598 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000599 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000600}
601
602/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
603/// this predicate to simplify operations downstream. Mask is known to be zero
604/// for bits that V cannot have.
605static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000606 uint64_t KnownZero, KnownOne;
607 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
608 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
609 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000610}
611
Chris Lattner255d8912006-02-11 09:31:47 +0000612/// ShrinkDemandedConstant - Check to see if the specified operand of the
613/// specified instruction is a constant integer. If so, check to see if there
614/// are any bits set in the constant that are not demanded. If so, shrink the
615/// constant and return true.
616static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
617 uint64_t Demanded) {
618 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
619 if (!OpC) return false;
620
621 // If there are no bits set that aren't demanded, nothing to do.
622 if ((~Demanded & OpC->getZExtValue()) == 0)
623 return false;
624
625 // This is producing any bits that are not needed, shrink the RHS.
626 uint64_t Val = Demanded & OpC->getZExtValue();
627 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
628 return true;
629}
630
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000631// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
632// set of known zero and one bits, compute the maximum and minimum values that
633// could have the specified known zero and known one bits, returning them in
634// min/max.
635static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
636 uint64_t KnownZero,
637 uint64_t KnownOne,
638 int64_t &Min, int64_t &Max) {
639 uint64_t TypeBits = Ty->getIntegralTypeMask();
640 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
641
642 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
643
644 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
645 // bit if it is unknown.
646 Min = KnownOne;
647 Max = KnownOne|UnknownBits;
648
649 if (SignBit & UnknownBits) { // Sign bit is unknown
650 Min |= SignBit;
651 Max &= ~SignBit;
652 }
653
654 // Sign extend the min/max values.
655 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
656 Min = (Min << ShAmt) >> ShAmt;
657 Max = (Max << ShAmt) >> ShAmt;
658}
659
660// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
661// a set of known zero and one bits, compute the maximum and minimum values that
662// could have the specified known zero and known one bits, returning them in
663// min/max.
664static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
665 uint64_t KnownZero,
666 uint64_t KnownOne,
667 uint64_t &Min,
668 uint64_t &Max) {
669 uint64_t TypeBits = Ty->getIntegralTypeMask();
670 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
671
672 // The minimum value is when the unknown bits are all zeros.
673 Min = KnownOne;
674 // The maximum value is when the unknown bits are all ones.
675 Max = KnownOne|UnknownBits;
676}
Chris Lattner255d8912006-02-11 09:31:47 +0000677
678
679/// SimplifyDemandedBits - Look at V. At this point, we know that only the
680/// DemandedMask bits of the result of V are ever used downstream. If we can
681/// use this information to simplify V, do so and return true. Otherwise,
682/// analyze the expression and return a mask of KnownOne and KnownZero bits for
683/// the expression (used to simplify the caller). The KnownZero/One bits may
684/// only be accurate for those bits in the DemandedMask.
685bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
686 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +0000687 unsigned Depth) {
Chris Lattner255d8912006-02-11 09:31:47 +0000688 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
689 // We know all of the bits for a constant!
690 KnownOne = CI->getZExtValue() & DemandedMask;
691 KnownZero = ~KnownOne & DemandedMask;
692 return false;
693 }
694
695 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000696 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +0000697 if (Depth != 0) { // Not at the root.
698 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
699 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000700 return false;
Chris Lattner255d8912006-02-11 09:31:47 +0000701 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000702 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +0000703 // just set the DemandedMask to all bits.
704 DemandedMask = V->getType()->getIntegralTypeMask();
705 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner74c51a02006-02-07 08:05:22 +0000706 if (V != UndefValue::get(V->getType()))
707 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
708 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000709 } else if (Depth == 6) { // Limit search depth.
710 return false;
711 }
712
713 Instruction *I = dyn_cast<Instruction>(V);
714 if (!I) return false; // Only analyze instructions.
715
Chris Lattner255d8912006-02-11 09:31:47 +0000716 uint64_t KnownZero2, KnownOne2;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000717 switch (I->getOpcode()) {
718 default: break;
719 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +0000720 // If either the LHS or the RHS are Zero, the result is zero.
721 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
722 KnownZero, KnownOne, Depth+1))
723 return true;
724 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
725
726 // If something is known zero on the RHS, the bits aren't demanded on the
727 // LHS.
728 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
729 KnownZero2, KnownOne2, Depth+1))
730 return true;
731 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
732
733 // If all of the demanded bits are known one on one side, return the other.
734 // These bits cannot contribute to the result of the 'and'.
735 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
736 return UpdateValueUsesWith(I, I->getOperand(0));
737 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
738 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000739
740 // If all of the demanded bits in the inputs are known zeros, return zero.
741 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
742 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
743
Chris Lattner255d8912006-02-11 09:31:47 +0000744 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000745 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +0000746 return UpdateValueUsesWith(I, I);
747
748 // Output known-1 bits are only known if set in both the LHS & RHS.
749 KnownOne &= KnownOne2;
750 // Output known-0 are known to be clear if zero in either the LHS | RHS.
751 KnownZero |= KnownZero2;
752 break;
753 case Instruction::Or:
754 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
755 KnownZero, KnownOne, Depth+1))
756 return true;
757 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
758 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
759 KnownZero2, KnownOne2, Depth+1))
760 return true;
761 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
762
763 // If all of the demanded bits are known zero on one side, return the other.
764 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +0000765 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +0000766 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +0000767 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +0000768 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000769
770 // If all of the potentially set bits on one side are known to be set on
771 // the other side, just use the 'other' side.
772 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
773 (DemandedMask & (~KnownZero)))
774 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +0000775 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
776 (DemandedMask & (~KnownZero2)))
777 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +0000778
779 // If the RHS is a constant, see if we can simplify it.
780 if (ShrinkDemandedConstant(I, 1, DemandedMask))
781 return UpdateValueUsesWith(I, I);
782
783 // Output known-0 bits are only known if clear in both the LHS & RHS.
784 KnownZero &= KnownZero2;
785 // Output known-1 are known to be set if set in either the LHS | RHS.
786 KnownOne |= KnownOne2;
787 break;
788 case Instruction::Xor: {
789 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
790 KnownZero, KnownOne, Depth+1))
791 return true;
792 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
793 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
794 KnownZero2, KnownOne2, Depth+1))
795 return true;
796 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
797
798 // If all of the demanded bits are known zero on one side, return the other.
799 // These bits cannot contribute to the result of the 'xor'.
800 if ((DemandedMask & KnownZero) == DemandedMask)
801 return UpdateValueUsesWith(I, I->getOperand(0));
802 if ((DemandedMask & KnownZero2) == DemandedMask)
803 return UpdateValueUsesWith(I, I->getOperand(1));
804
805 // Output known-0 bits are known if clear or set in both the LHS & RHS.
806 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
807 // Output known-1 are known to be set if set in only one of the LHS, RHS.
808 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
809
810 // If all of the unknown bits are known to be zero on one side or the other
811 // (but not both) turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000812 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner255d8912006-02-11 09:31:47 +0000813 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
814 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
815 Instruction *Or =
816 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
817 I->getName());
818 InsertNewInstBefore(Or, *I);
819 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000820 }
821 }
Chris Lattner255d8912006-02-11 09:31:47 +0000822
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000823 // If all of the demanded bits on one side are known, and all of the set
824 // bits on that side are also known to be set on the other side, turn this
825 // into an AND, as we know the bits will be cleared.
826 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
827 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
828 if ((KnownOne & KnownOne2) == KnownOne) {
829 Constant *AndC = GetConstantInType(I->getType(),
830 ~KnownOne & DemandedMask);
831 Instruction *And =
832 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
833 InsertNewInstBefore(And, *I);
834 return UpdateValueUsesWith(I, And);
835 }
836 }
837
Chris Lattner255d8912006-02-11 09:31:47 +0000838 // If the RHS is a constant, see if we can simplify it.
839 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
840 if (ShrinkDemandedConstant(I, 1, DemandedMask))
841 return UpdateValueUsesWith(I, I);
842
843 KnownZero = KnownZeroOut;
844 KnownOne = KnownOneOut;
845 break;
846 }
847 case Instruction::Select:
848 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
849 KnownZero, KnownOne, Depth+1))
850 return true;
851 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
852 KnownZero2, KnownOne2, Depth+1))
853 return true;
854 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
855 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
856
857 // If the operands are constants, see if we can simplify them.
858 if (ShrinkDemandedConstant(I, 1, DemandedMask))
859 return UpdateValueUsesWith(I, I);
860 if (ShrinkDemandedConstant(I, 2, DemandedMask))
861 return UpdateValueUsesWith(I, I);
862
863 // Only known if known in both the LHS and RHS.
864 KnownOne &= KnownOne2;
865 KnownZero &= KnownZero2;
866 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000867 case Instruction::Cast: {
868 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +0000869 if (!SrcTy->isIntegral()) return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000870
Chris Lattner255d8912006-02-11 09:31:47 +0000871 // If this is an integer truncate or noop, just look in the input.
872 if (SrcTy->getPrimitiveSizeInBits() >=
873 I->getType()->getPrimitiveSizeInBits()) {
874 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
875 KnownZero, KnownOne, Depth+1))
876 return true;
877 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
878 break;
879 }
880
881 // Sign or Zero extension. Compute the bits in the result that are not
882 // present in the input.
883 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
884 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
885
886 // Handle zero extension.
887 if (!SrcTy->isSigned()) {
888 DemandedMask &= SrcTy->getIntegralTypeMask();
889 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
890 KnownZero, KnownOne, Depth+1))
891 return true;
892 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
893 // The top bits are known to be zero.
894 KnownZero |= NewBits;
895 } else {
896 // Sign extension.
Chris Lattnerf345fe42006-02-13 22:41:07 +0000897 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
898 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
899
900 // If any of the sign extended bits are demanded, we know that the sign
901 // bit is demanded.
902 if (NewBits & DemandedMask)
903 InputDemandedBits |= InSignBit;
904
905 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner255d8912006-02-11 09:31:47 +0000906 KnownZero, KnownOne, Depth+1))
907 return true;
908 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
909
910 // If the sign bit of the input is known set or clear, then we know the
911 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +0000912
Chris Lattner255d8912006-02-11 09:31:47 +0000913 // If the input sign bit is known zero, or if the NewBits are not demanded
914 // convert this into a zero extension.
915 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner6dce1a72006-02-07 06:56:34 +0000916 // Convert to unsigned first.
Chris Lattnerd89d8882006-02-07 19:07:40 +0000917 Instruction *NewVal;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000918 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattnerd89d8882006-02-07 19:07:40 +0000919 I->getOperand(0)->getName());
920 InsertNewInstBefore(NewVal, *I);
Chris Lattner255d8912006-02-11 09:31:47 +0000921 // Then cast that to the destination type.
Chris Lattnerd89d8882006-02-07 19:07:40 +0000922 NewVal = new CastInst(NewVal, I->getType(), I->getName());
923 InsertNewInstBefore(NewVal, *I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000924 return UpdateValueUsesWith(I, NewVal);
Chris Lattner255d8912006-02-11 09:31:47 +0000925 } else if (KnownOne & InSignBit) { // Input sign bit known set
926 KnownOne |= NewBits;
927 KnownZero &= ~NewBits;
928 } else { // Input sign bit unknown
929 KnownZero &= ~NewBits;
930 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000931 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000932 }
Chris Lattner255d8912006-02-11 09:31:47 +0000933 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000934 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000935 case Instruction::Shl:
Chris Lattner255d8912006-02-11 09:31:47 +0000936 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
937 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
938 KnownZero, KnownOne, Depth+1))
939 return true;
940 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
941 KnownZero <<= SA->getValue();
942 KnownOne <<= SA->getValue();
943 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
944 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000945 break;
946 case Instruction::Shr:
Chris Lattner255d8912006-02-11 09:31:47 +0000947 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
948 unsigned ShAmt = SA->getValue();
949
950 // Compute the new bits that are at the top now.
951 uint64_t HighBits = (1ULL << ShAmt)-1;
952 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattnerc15637b2006-02-13 06:09:08 +0000953 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner255d8912006-02-11 09:31:47 +0000954 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +0000955 if (SimplifyDemandedBits(I->getOperand(0),
956 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +0000957 KnownZero, KnownOne, Depth+1))
958 return true;
959 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +0000960 KnownZero &= TypeMask;
961 KnownOne &= TypeMask;
Chris Lattner255d8912006-02-11 09:31:47 +0000962 KnownZero >>= ShAmt;
963 KnownOne >>= ShAmt;
964 KnownZero |= HighBits; // high bits known zero.
965 } else { // Signed shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +0000966 if (SimplifyDemandedBits(I->getOperand(0),
967 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +0000968 KnownZero, KnownOne, Depth+1))
969 return true;
970 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +0000971 KnownZero &= TypeMask;
972 KnownOne &= TypeMask;
Chris Lattner255d8912006-02-11 09:31:47 +0000973 KnownZero >>= SA->getValue();
974 KnownOne >>= SA->getValue();
975
976 // Handle the sign bits.
977 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
978 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
979
980 // If the input sign bit is known to be zero, or if none of the top bits
981 // are demanded, turn this into an unsigned shift right.
982 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
983 // Convert the input to unsigned.
984 Instruction *NewVal;
985 NewVal = new CastInst(I->getOperand(0),
986 I->getType()->getUnsignedVersion(),
987 I->getOperand(0)->getName());
988 InsertNewInstBefore(NewVal, *I);
989 // Perform the unsigned shift right.
990 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
991 InsertNewInstBefore(NewVal, *I);
992 // Then cast that to the destination type.
993 NewVal = new CastInst(NewVal, I->getType(), I->getName());
994 InsertNewInstBefore(NewVal, *I);
995 return UpdateValueUsesWith(I, NewVal);
996 } else if (KnownOne & SignBit) { // New bits are known one.
997 KnownOne |= HighBits;
998 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000999 }
Chris Lattner255d8912006-02-11 09:31:47 +00001000 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001001 break;
1002 }
Chris Lattner255d8912006-02-11 09:31:47 +00001003
1004 // If the client is only demanding bits that we know, return the known
1005 // constant.
1006 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1007 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001008 return false;
1009}
1010
Chris Lattner955f3312004-09-28 21:48:02 +00001011// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1012// true when both operands are equal...
1013//
1014static bool isTrueWhenEqual(Instruction &I) {
1015 return I.getOpcode() == Instruction::SetEQ ||
1016 I.getOpcode() == Instruction::SetGE ||
1017 I.getOpcode() == Instruction::SetLE;
1018}
Chris Lattner564a7272003-08-13 19:01:45 +00001019
1020/// AssociativeOpt - Perform an optimization on an associative operator. This
1021/// function is designed to check a chain of associative operators for a
1022/// potential to apply a certain optimization. Since the optimization may be
1023/// applicable if the expression was reassociated, this checks the chain, then
1024/// reassociates the expression as necessary to expose the optimization
1025/// opportunity. This makes use of a special Functor, which must define
1026/// 'shouldApply' and 'apply' methods.
1027///
1028template<typename Functor>
1029Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1030 unsigned Opcode = Root.getOpcode();
1031 Value *LHS = Root.getOperand(0);
1032
1033 // Quick check, see if the immediate LHS matches...
1034 if (F.shouldApply(LHS))
1035 return F.apply(Root);
1036
1037 // Otherwise, if the LHS is not of the same opcode as the root, return.
1038 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001039 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001040 // Should we apply this transform to the RHS?
1041 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1042
1043 // If not to the RHS, check to see if we should apply to the LHS...
1044 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1045 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1046 ShouldApply = true;
1047 }
1048
1049 // If the functor wants to apply the optimization to the RHS of LHSI,
1050 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1051 if (ShouldApply) {
1052 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001053
Chris Lattner564a7272003-08-13 19:01:45 +00001054 // Now all of the instructions are in the current basic block, go ahead
1055 // and perform the reassociation.
1056 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1057
1058 // First move the selected RHS to the LHS of the root...
1059 Root.setOperand(0, LHSI->getOperand(1));
1060
1061 // Make what used to be the LHS of the root be the user of the root...
1062 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001063 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001064 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1065 return 0;
1066 }
Chris Lattner65725312004-04-16 18:08:07 +00001067 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001068 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001069 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1070 BasicBlock::iterator ARI = &Root; ++ARI;
1071 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1072 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001073
1074 // Now propagate the ExtraOperand down the chain of instructions until we
1075 // get to LHSI.
1076 while (TmpLHSI != LHSI) {
1077 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001078 // Move the instruction to immediately before the chain we are
1079 // constructing to avoid breaking dominance properties.
1080 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1081 BB->getInstList().insert(ARI, NextLHSI);
1082 ARI = NextLHSI;
1083
Chris Lattner564a7272003-08-13 19:01:45 +00001084 Value *NextOp = NextLHSI->getOperand(1);
1085 NextLHSI->setOperand(1, ExtraOperand);
1086 TmpLHSI = NextLHSI;
1087 ExtraOperand = NextOp;
1088 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001089
Chris Lattner564a7272003-08-13 19:01:45 +00001090 // Now that the instructions are reassociated, have the functor perform
1091 // the transformation...
1092 return F.apply(Root);
1093 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001094
Chris Lattner564a7272003-08-13 19:01:45 +00001095 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1096 }
1097 return 0;
1098}
1099
1100
1101// AddRHS - Implements: X + X --> X << 1
1102struct AddRHS {
1103 Value *RHS;
1104 AddRHS(Value *rhs) : RHS(rhs) {}
1105 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1106 Instruction *apply(BinaryOperator &Add) const {
1107 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1108 ConstantInt::get(Type::UByteTy, 1));
1109 }
1110};
1111
1112// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1113// iff C1&C2 == 0
1114struct AddMaskingAnd {
1115 Constant *C2;
1116 AddMaskingAnd(Constant *c) : C2(c) {}
1117 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001118 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001119 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001120 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001121 }
1122 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001123 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001124 }
1125};
1126
Chris Lattner6e7ba452005-01-01 16:22:27 +00001127static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001128 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001129 if (isa<CastInst>(I)) {
1130 if (Constant *SOC = dyn_cast<Constant>(SO))
1131 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001132
Chris Lattner6e7ba452005-01-01 16:22:27 +00001133 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1134 SO->getName() + ".cast"), I);
1135 }
1136
Chris Lattner2eefe512004-04-09 19:05:30 +00001137 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001138 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1139 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001140
Chris Lattner2eefe512004-04-09 19:05:30 +00001141 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1142 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001143 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1144 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001145 }
1146
1147 Value *Op0 = SO, *Op1 = ConstOperand;
1148 if (!ConstIsRHS)
1149 std::swap(Op0, Op1);
1150 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001151 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1152 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1153 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1154 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +00001155 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001156 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001157 abort();
1158 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001159 return IC->InsertNewInstBefore(New, I);
1160}
1161
1162// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1163// constant as the other operand, try to fold the binary operator into the
1164// select arguments. This also works for Cast instructions, which obviously do
1165// not have a second operand.
1166static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1167 InstCombiner *IC) {
1168 // Don't modify shared select instructions
1169 if (!SI->hasOneUse()) return 0;
1170 Value *TV = SI->getOperand(1);
1171 Value *FV = SI->getOperand(2);
1172
1173 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001174 // Bool selects with constant operands can be folded to logical ops.
1175 if (SI->getType() == Type::BoolTy) return 0;
1176
Chris Lattner6e7ba452005-01-01 16:22:27 +00001177 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1178 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1179
1180 return new SelectInst(SI->getCondition(), SelectTrueVal,
1181 SelectFalseVal);
1182 }
1183 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001184}
1185
Chris Lattner4e998b22004-09-29 05:07:12 +00001186
1187/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1188/// node as operand #0, see if we can fold the instruction into the PHI (which
1189/// is only possible if all operands to the PHI are constants).
1190Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1191 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001192 unsigned NumPHIValues = PN->getNumIncomingValues();
1193 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1194 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001195
1196 // Check to see if all of the operands of the PHI are constants. If not, we
1197 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +00001198 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +00001199 if (!isa<Constant>(PN->getIncomingValue(i)))
1200 return 0;
1201
1202 // Okay, we can do the transformation: create the new PHI node.
1203 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1204 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +00001205 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001206 InsertNewInstBefore(NewPN, *PN);
1207
1208 // Next, add all of the operands to the PHI.
1209 if (I.getNumOperands() == 2) {
1210 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001211 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001212 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1213 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1214 PN->getIncomingBlock(i));
1215 }
1216 } else {
1217 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1218 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001219 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001220 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1221 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1222 PN->getIncomingBlock(i));
1223 }
1224 }
1225 return ReplaceInstUsesWith(I, NewPN);
1226}
1227
Chris Lattner7e708292002-06-25 16:13:24 +00001228Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001229 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001230 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001231
Chris Lattner66331a42004-04-10 22:01:55 +00001232 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001233 // X + undef -> undef
1234 if (isa<UndefValue>(RHS))
1235 return ReplaceInstUsesWith(I, RHS);
1236
Chris Lattner66331a42004-04-10 22:01:55 +00001237 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +00001238 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1239 if (RHSC->isNullValue())
1240 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001241 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1242 if (CFP->isExactlyValue(-0.0))
1243 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001244 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001245
Chris Lattner66331a42004-04-10 22:01:55 +00001246 // X + (signbit) --> X ^ signbit
1247 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner74c51a02006-02-07 08:05:22 +00001248 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00001249 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001250 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +00001251 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001252
1253 if (isa<PHINode>(LHS))
1254 if (Instruction *NV = FoldOpIntoPhi(I))
1255 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001256
Chris Lattner4f637d42006-01-06 17:59:59 +00001257 ConstantInt *XorRHS = 0;
1258 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +00001259 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1260 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1261 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1262 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1263
1264 uint64_t C0080Val = 1ULL << 31;
1265 int64_t CFF80Val = -C0080Val;
1266 unsigned Size = 32;
1267 do {
1268 if (TySizeBits > Size) {
1269 bool Found = false;
1270 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1271 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1272 if (RHSSExt == CFF80Val) {
1273 if (XorRHS->getZExtValue() == C0080Val)
1274 Found = true;
1275 } else if (RHSZExt == C0080Val) {
1276 if (XorRHS->getSExtValue() == CFF80Val)
1277 Found = true;
1278 }
1279 if (Found) {
1280 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00001281 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00001282 Mask <<= 64-(TySizeBits-Size);
Chris Lattner68d5ff22006-02-09 07:38:58 +00001283 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00001284 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00001285 Size = 0; // Not a sign ext, but can't be any others either.
1286 goto FoundSExt;
1287 }
1288 }
1289 Size >>= 1;
1290 C0080Val >>= Size;
1291 CFF80Val >>= Size;
1292 } while (Size >= 8);
1293
1294FoundSExt:
1295 const Type *MiddleType = 0;
1296 switch (Size) {
1297 default: break;
1298 case 32: MiddleType = Type::IntTy; break;
1299 case 16: MiddleType = Type::ShortTy; break;
1300 case 8: MiddleType = Type::SByteTy; break;
1301 }
1302 if (MiddleType) {
1303 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1304 InsertNewInstBefore(NewTrunc, I);
1305 return new CastInst(NewTrunc, I.getType());
1306 }
1307 }
Chris Lattner66331a42004-04-10 22:01:55 +00001308 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001309
Chris Lattner564a7272003-08-13 19:01:45 +00001310 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +00001311 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001312 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001313
1314 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1315 if (RHSI->getOpcode() == Instruction::Sub)
1316 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1317 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1318 }
1319 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1320 if (LHSI->getOpcode() == Instruction::Sub)
1321 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1322 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1323 }
Robert Bocchino71698282004-07-27 21:02:21 +00001324 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001325
Chris Lattner5c4afb92002-05-08 22:46:53 +00001326 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00001327 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001328 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001329
1330 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001331 if (!isa<Constant>(RHS))
1332 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001333 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001334
Misha Brukmanfd939082005-04-21 23:48:37 +00001335
Chris Lattner50af16a2004-11-13 19:50:12 +00001336 ConstantInt *C2;
1337 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1338 if (X == RHS) // X*C + X --> X * (C+1)
1339 return BinaryOperator::createMul(RHS, AddOne(C2));
1340
1341 // X*C1 + X*C2 --> X * (C1+C2)
1342 ConstantInt *C1;
1343 if (X == dyn_castFoldableMul(RHS, C1))
1344 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001345 }
1346
1347 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00001348 if (dyn_castFoldableMul(RHS, C2) == LHS)
1349 return BinaryOperator::createMul(LHS, AddOne(C2));
1350
Chris Lattnerad3448c2003-02-18 19:57:07 +00001351
Chris Lattner564a7272003-08-13 19:01:45 +00001352 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001353 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +00001354 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00001355
Chris Lattner6b032052003-10-02 15:11:26 +00001356 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001357 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001358 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1359 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1360 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00001361 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001362
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001363 // (X & FF00) + xx00 -> (X+xx00) & FF00
1364 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1365 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1366 if (Anded == CRHS) {
1367 // See if all bits from the first bit set in the Add RHS up are included
1368 // in the mask. First, get the rightmost bit.
1369 uint64_t AddRHSV = CRHS->getRawValue();
1370
1371 // Form a mask of all bits from the lowest bit added through the top.
1372 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +00001373 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001374
1375 // See if the and mask includes all of these bits.
1376 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001377
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001378 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1379 // Okay, the xform is safe. Insert the new add pronto.
1380 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1381 LHS->getName()), I);
1382 return BinaryOperator::createAnd(NewAdd, C2);
1383 }
1384 }
1385 }
1386
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001387 // Try to fold constant add into select arguments.
1388 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001389 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001390 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00001391 }
1392
Chris Lattner7e708292002-06-25 16:13:24 +00001393 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001394}
1395
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001396// isSignBit - Return true if the value represented by the constant only has the
1397// highest order bit set.
1398static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001399 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +00001400 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001401}
1402
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001403/// RemoveNoopCast - Strip off nonconverting casts from the value.
1404///
1405static Value *RemoveNoopCast(Value *V) {
1406 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1407 const Type *CTy = CI->getType();
1408 const Type *OpTy = CI->getOperand(0)->getType();
1409 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001410 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001411 return RemoveNoopCast(CI->getOperand(0));
1412 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1413 return RemoveNoopCast(CI->getOperand(0));
1414 }
1415 return V;
1416}
1417
Chris Lattner7e708292002-06-25 16:13:24 +00001418Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001419 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001420
Chris Lattner233f7dc2002-08-12 21:17:25 +00001421 if (Op0 == Op1) // sub X, X -> 0
1422 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001423
Chris Lattner233f7dc2002-08-12 21:17:25 +00001424 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001425 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001426 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001427
Chris Lattnere87597f2004-10-16 18:11:37 +00001428 if (isa<UndefValue>(Op0))
1429 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1430 if (isa<UndefValue>(Op1))
1431 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1432
Chris Lattnerd65460f2003-11-05 01:06:05 +00001433 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1434 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001435 if (C->isAllOnesValue())
1436 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001437
Chris Lattnerd65460f2003-11-05 01:06:05 +00001438 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001439 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001440 if (match(Op1, m_Not(m_Value(X))))
1441 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001442 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001443 // -((uint)X >> 31) -> ((int)X >> 31)
1444 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001445 if (C->isNullValue()) {
1446 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1447 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +00001448 if (SI->getOpcode() == Instruction::Shr)
1449 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1450 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001451 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +00001452 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001453 else
Chris Lattner5dd04022004-06-17 18:16:02 +00001454 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001455 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +00001456 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +00001457 // Ok, the transformation is safe. Insert a cast of the incoming
1458 // value, then the new shift, then the new cast.
1459 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1460 SI->getOperand(0)->getName());
1461 Value *InV = InsertNewInstBefore(FirstCast, I);
1462 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1463 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001464 if (NewShift->getType() == I.getType())
1465 return NewShift;
1466 else {
1467 InV = InsertNewInstBefore(NewShift, I);
1468 return new CastInst(NewShift, I.getType());
1469 }
Chris Lattner9c290672004-03-12 23:53:13 +00001470 }
1471 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001472 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001473
1474 // Try to fold constant sub into select arguments.
1475 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001476 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001477 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001478
1479 if (isa<PHINode>(Op0))
1480 if (Instruction *NV = FoldOpIntoPhi(I))
1481 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00001482 }
1483
Chris Lattner43d84d62005-04-07 16:15:25 +00001484 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1485 if (Op1I->getOpcode() == Instruction::Add &&
1486 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +00001487 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001488 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001489 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001490 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001491 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1492 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1493 // C1-(X+C2) --> (C1-C2)-X
1494 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1495 Op1I->getOperand(0));
1496 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001497 }
1498
Chris Lattnerfd059242003-10-15 16:48:29 +00001499 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001500 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1501 // is not used by anyone else...
1502 //
Chris Lattner0517e722004-02-02 20:09:56 +00001503 if (Op1I->getOpcode() == Instruction::Sub &&
1504 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001505 // Swap the two operands of the subexpr...
1506 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1507 Op1I->setOperand(0, IIOp1);
1508 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001509
Chris Lattnera2881962003-02-18 19:28:33 +00001510 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00001511 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001512 }
1513
1514 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1515 //
1516 if (Op1I->getOpcode() == Instruction::And &&
1517 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1518 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1519
Chris Lattnerf523d062004-06-09 05:08:07 +00001520 Value *NewNot =
1521 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001522 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001523 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001524
Chris Lattner91ccc152004-10-06 15:08:25 +00001525 // -(X sdiv C) -> (X sdiv -C)
1526 if (Op1I->getOpcode() == Instruction::Div)
1527 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +00001528 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00001529 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +00001530 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00001531 ConstantExpr::getNeg(DivRHS));
1532
Chris Lattnerad3448c2003-02-18 19:57:07 +00001533 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001534 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00001535 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001536 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00001537 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00001538 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001539 }
Chris Lattner40371712002-05-09 01:29:19 +00001540 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001541 }
Chris Lattnera2881962003-02-18 19:28:33 +00001542
Chris Lattner7edc8c22005-04-07 17:14:51 +00001543 if (!Op0->getType()->isFloatingPoint())
1544 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1545 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001546 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1547 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1548 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1549 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00001550 } else if (Op0I->getOpcode() == Instruction::Sub) {
1551 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1552 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001553 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001554
Chris Lattner50af16a2004-11-13 19:50:12 +00001555 ConstantInt *C1;
1556 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1557 if (X == Op1) { // X*C - X --> X * (C-1)
1558 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1559 return BinaryOperator::createMul(Op1, CP1);
1560 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001561
Chris Lattner50af16a2004-11-13 19:50:12 +00001562 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1563 if (X == dyn_castFoldableMul(Op1, C2))
1564 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1565 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001566 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001567}
1568
Chris Lattner4cb170c2004-02-23 06:38:22 +00001569/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1570/// really just returns true if the most significant (sign) bit is set.
1571static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1572 if (RHS->getType()->isSigned()) {
1573 // True if source is LHS < 0 or LHS <= -1
1574 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1575 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1576 } else {
1577 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1578 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1579 // the size of the integer type.
1580 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +00001581 return RHSC->getValue() ==
1582 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001583 if (Opcode == Instruction::SetGT)
1584 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00001585 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001586 }
1587 return false;
1588}
1589
Chris Lattner7e708292002-06-25 16:13:24 +00001590Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001591 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00001592 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001593
Chris Lattnere87597f2004-10-16 18:11:37 +00001594 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1595 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1596
Chris Lattner233f7dc2002-08-12 21:17:25 +00001597 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00001598 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1599 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001600
1601 // ((X << C1)*C2) == (X * (C2 << C1))
1602 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1603 if (SI->getOpcode() == Instruction::Shl)
1604 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001605 return BinaryOperator::createMul(SI->getOperand(0),
1606 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001607
Chris Lattner515c97c2003-09-11 22:24:54 +00001608 if (CI->isNullValue())
1609 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1610 if (CI->equalsInt(1)) // X * 1 == X
1611 return ReplaceInstUsesWith(I, Op0);
1612 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00001613 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001614
Chris Lattner515c97c2003-09-11 22:24:54 +00001615 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001616 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1617 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00001618 return new ShiftInst(Instruction::Shl, Op0,
1619 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001620 }
Robert Bocchino71698282004-07-27 21:02:21 +00001621 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001622 if (Op1F->isNullValue())
1623 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00001624
Chris Lattnera2881962003-02-18 19:28:33 +00001625 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1626 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1627 if (Op1F->getValue() == 1.0)
1628 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1629 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001630
1631 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1632 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1633 isa<ConstantInt>(Op0I->getOperand(1))) {
1634 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1635 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1636 Op1, "tmp");
1637 InsertNewInstBefore(Add, I);
1638 Value *C1C2 = ConstantExpr::getMul(Op1,
1639 cast<Constant>(Op0I->getOperand(1)));
1640 return BinaryOperator::createAdd(Add, C1C2);
1641
1642 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001643
1644 // Try to fold constant mul into select arguments.
1645 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001646 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001647 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001648
1649 if (isa<PHINode>(Op0))
1650 if (Instruction *NV = FoldOpIntoPhi(I))
1651 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001652 }
1653
Chris Lattnera4f445b2003-03-10 23:23:04 +00001654 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1655 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001656 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001657
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001658 // If one of the operands of the multiply is a cast from a boolean value, then
1659 // we know the bool is either zero or one, so this is a 'masking' multiply.
1660 // See if we can simplify things based on how the boolean was originally
1661 // formed.
1662 CastInst *BoolCast = 0;
1663 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1664 if (CI->getOperand(0)->getType() == Type::BoolTy)
1665 BoolCast = CI;
1666 if (!BoolCast)
1667 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1668 if (CI->getOperand(0)->getType() == Type::BoolTy)
1669 BoolCast = CI;
1670 if (BoolCast) {
1671 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1672 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1673 const Type *SCOpTy = SCIOp0->getType();
1674
Chris Lattner4cb170c2004-02-23 06:38:22 +00001675 // If the setcc is true iff the sign bit of X is set, then convert this
1676 // multiply into a shift/and combination.
1677 if (isa<ConstantInt>(SCIOp1) &&
1678 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001679 // Shift the X value right to turn it into "all signbits".
1680 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00001681 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001682 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001683 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00001684 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1685 SCIOp0->getName()), I);
1686 }
1687
1688 Value *V =
1689 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1690 BoolCast->getOperand(0)->getName()+
1691 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001692
1693 // If the multiply type is not the same as the source type, sign extend
1694 // or truncate to the multiply type.
1695 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001696 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001697
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001698 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001699 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001700 }
1701 }
1702 }
1703
Chris Lattner7e708292002-06-25 16:13:24 +00001704 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001705}
1706
Chris Lattner7e708292002-06-25 16:13:24 +00001707Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001708 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001709
Chris Lattner857e8cd2004-12-12 21:48:58 +00001710 if (isa<UndefValue>(Op0)) // undef / X -> 0
1711 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1712 if (isa<UndefValue>(Op1))
1713 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1714
1715 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001716 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001717 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001718 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001719
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001720 // div X, -1 == -X
1721 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001722 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001723
Chris Lattner857e8cd2004-12-12 21:48:58 +00001724 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001725 if (LHS->getOpcode() == Instruction::Div)
1726 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001727 // (X / C1) / C2 -> X / (C1*C2)
1728 return BinaryOperator::createDiv(LHS->getOperand(0),
1729 ConstantExpr::getMul(RHS, LHSRHS));
1730 }
1731
Chris Lattnera2881962003-02-18 19:28:33 +00001732 // Check to see if this is an unsigned division with an exact power of 2,
1733 // if so, convert to a right shift.
1734 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1735 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001736 if (isPowerOf2_64(Val)) {
1737 uint64_t C = Log2_64(Val);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001738 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001739 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001740 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001741
Chris Lattnera052f822004-10-09 02:50:40 +00001742 // -X/C -> X/-C
1743 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001744 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001745 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1746
Chris Lattner857e8cd2004-12-12 21:48:58 +00001747 if (!RHS->isNullValue()) {
1748 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001749 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001750 return R;
1751 if (isa<PHINode>(Op0))
1752 if (Instruction *NV = FoldOpIntoPhi(I))
1753 return NV;
1754 }
Chris Lattnera2881962003-02-18 19:28:33 +00001755 }
1756
Chris Lattner857e8cd2004-12-12 21:48:58 +00001757 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1758 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1759 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1760 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1761 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1762 if (STO->getValue() == 0) { // Couldn't be this argument.
1763 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001764 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001765 } else if (SFO->getValue() == 0) {
Chris Lattnerf9c775c2005-06-16 04:55:52 +00001766 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001767 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001768 }
1769
Chris Lattnerbf70b832005-04-08 04:03:26 +00001770 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001771 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1772 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattnerbf70b832005-04-08 04:03:26 +00001773 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1774 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1775 TC, SI->getName()+".t");
1776 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001777
Chris Lattnerbf70b832005-04-08 04:03:26 +00001778 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1779 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1780 FC, SI->getName()+".f");
1781 FSI = InsertNewInstBefore(FSI, I);
1782 return new SelectInst(SI->getOperand(0), TSI, FSI);
1783 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001784 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001785
Chris Lattnera2881962003-02-18 19:28:33 +00001786 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001787 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001788 if (LHS->equalsInt(0))
1789 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1790
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001791 if (I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00001792 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001793 // unsigned inputs), turn this into a udiv.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001794 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1795 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001796 const Type *NTy = Op0->getType()->getUnsignedVersion();
1797 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1798 InsertNewInstBefore(LHS, I);
1799 Value *RHS;
1800 if (Constant *R = dyn_cast<Constant>(Op1))
1801 RHS = ConstantExpr::getCast(R, NTy);
1802 else
1803 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1804 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1805 InsertNewInstBefore(Div, I);
1806 return new CastInst(Div, I.getType());
1807 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001808 } else {
1809 // Known to be an unsigned division.
1810 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1811 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1812 if (RHSI->getOpcode() == Instruction::Shl &&
1813 isa<ConstantUInt>(RHSI->getOperand(0))) {
1814 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1815 if (isPowerOf2_64(C1)) {
1816 unsigned C2 = Log2_64(C1);
1817 Value *Add = RHSI->getOperand(1);
1818 if (C2) {
1819 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1820 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1821 "tmp"), I);
1822 }
1823 return new ShiftInst(Instruction::Shr, Op0, Add);
1824 }
1825 }
1826 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001827 }
1828
Chris Lattner3f5b8772002-05-06 16:14:14 +00001829 return 0;
1830}
1831
1832
Chris Lattnerdb3f8732006-03-02 06:50:58 +00001833/// GetFactor - If we can prove that the specified value is at least a multiple
1834/// of some factor, return that factor.
1835static Constant *GetFactor(Value *V) {
1836 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1837 return CI;
1838
1839 // Unless we can be tricky, we know this is a multiple of 1.
1840 Constant *Result = ConstantInt::get(V->getType(), 1);
1841
1842 Instruction *I = dyn_cast<Instruction>(V);
1843 if (!I) return Result;
1844
1845 if (I->getOpcode() == Instruction::Mul) {
1846 // Handle multiplies by a constant, etc.
1847 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1848 GetFactor(I->getOperand(1)));
1849 } else if (I->getOpcode() == Instruction::Shl) {
1850 // (X<<C) -> X * (1 << C)
1851 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1852 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1853 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1854 }
1855 } else if (I->getOpcode() == Instruction::And) {
1856 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1857 // X & 0xFFF0 is known to be a multiple of 16.
1858 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1859 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1860 return ConstantExpr::getShl(Result,
1861 ConstantUInt::get(Type::UByteTy, Zeros));
1862 }
1863 } else if (I->getOpcode() == Instruction::Cast) {
1864 Value *Op = I->getOperand(0);
1865 // Only handle int->int casts.
1866 if (!Op->getType()->isInteger()) return Result;
1867 return ConstantExpr::getCast(GetFactor(Op), V->getType());
1868 }
1869 return Result;
1870}
1871
Chris Lattner7e708292002-06-25 16:13:24 +00001872Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001874
1875 // 0 % X == 0, we don't need to preserve faults!
1876 if (Constant *LHS = dyn_cast<Constant>(Op0))
1877 if (LHS->isNullValue())
1878 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1879
1880 if (isa<UndefValue>(Op0)) // undef % X -> 0
1881 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1882 if (isa<UndefValue>(Op1))
1883 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1884
Chris Lattner11a49f22005-11-05 07:28:37 +00001885 if (I.getType()->isSigned()) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001886 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00001887 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00001888 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00001889 // X % -Y -> X % Y
1890 AddUsesToWorkList(I);
1891 I.setOperand(1, RHSNeg);
1892 return &I;
1893 }
Chris Lattner11a49f22005-11-05 07:28:37 +00001894
1895 // If the top bits of both operands are zero (i.e. we can prove they are
1896 // unsigned inputs), turn this into a urem.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001897 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1898 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattner11a49f22005-11-05 07:28:37 +00001899 const Type *NTy = Op0->getType()->getUnsignedVersion();
1900 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1901 InsertNewInstBefore(LHS, I);
1902 Value *RHS;
1903 if (Constant *R = dyn_cast<Constant>(Op1))
1904 RHS = ConstantExpr::getCast(R, NTy);
1905 else
1906 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1907 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1908 InsertNewInstBefore(Rem, I);
1909 return new CastInst(Rem, I.getType());
1910 }
1911 }
Chris Lattner5b73c082004-07-06 07:01:22 +00001912
Chris Lattner857e8cd2004-12-12 21:48:58 +00001913 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001914 // X % 0 == undef, we don't need to preserve faults!
1915 if (RHS->equalsInt(0))
1916 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
1917
Chris Lattnera2881962003-02-18 19:28:33 +00001918 if (RHS->equalsInt(1)) // X % 1 == 0
1919 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1920
1921 // Check to see if this is an unsigned remainder with an exact power of 2,
1922 // if so, convert to a bitwise and.
1923 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001924 if (isPowerOf2_64(C->getValue()))
1925 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattner857e8cd2004-12-12 21:48:58 +00001926
Chris Lattner97943922006-02-28 05:49:21 +00001927 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1928 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1929 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1930 return R;
1931 } else if (isa<PHINode>(Op0I)) {
1932 if (Instruction *NV = FoldOpIntoPhi(I))
1933 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00001934 }
Chris Lattnerdb3f8732006-03-02 06:50:58 +00001935
1936 // X*C1%C2 --> 0 iff C1%C2 == 0
1937 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
1938 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00001939 }
Chris Lattnera2881962003-02-18 19:28:33 +00001940 }
1941
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001942 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1943 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1944 if (I.getType()->isUnsigned() &&
1945 RHSI->getOpcode() == Instruction::Shl &&
1946 isa<ConstantUInt>(RHSI->getOperand(0))) {
1947 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1948 if (isPowerOf2_64(C1)) {
1949 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1950 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1951 "tmp"), I);
1952 return BinaryOperator::createAnd(Op0, Add);
1953 }
1954 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00001955
1956 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1957 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1958 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1959 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1960 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1961 if (STO->getValue() == 0) { // Couldn't be this argument.
1962 I.setOperand(1, SFO);
1963 return &I;
1964 } else if (SFO->getValue() == 0) {
1965 I.setOperand(1, STO);
1966 return &I;
1967 }
1968
1969 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
1970 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1971 SubOne(STO), SI->getName()+".t"), I);
1972 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1973 SubOne(SFO), SI->getName()+".f"), I);
1974 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1975 }
1976 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001977 }
1978
Chris Lattner3f5b8772002-05-06 16:14:14 +00001979 return 0;
1980}
1981
Chris Lattner8b170942002-08-09 23:47:40 +00001982// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001983static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner1a074fc2006-02-07 07:00:41 +00001984 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1985 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner8b170942002-08-09 23:47:40 +00001986
1987 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00001988
Chris Lattner8b170942002-08-09 23:47:40 +00001989 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00001990 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00001991 int64_t Val = INT64_MAX; // All ones
1992 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1993 return CS->getValue() == Val-1;
1994}
1995
1996// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00001997static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00001998 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1999 return CU->getValue() == 1;
2000
2001 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00002002
2003 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00002004 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002005 int64_t Val = -1; // All ones
2006 Val <<= TypeBits-1; // Shift over to the right spot
2007 return CS->getValue() == Val+1;
2008}
2009
Chris Lattner457dd822004-06-09 07:59:58 +00002010// isOneBitSet - Return true if there is exactly one bit set in the specified
2011// constant.
2012static bool isOneBitSet(const ConstantInt *CI) {
2013 uint64_t V = CI->getRawValue();
2014 return V && (V & (V-1)) == 0;
2015}
2016
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002017#if 0 // Currently unused
2018// isLowOnes - Return true if the constant is of the form 0+1+.
2019static bool isLowOnes(const ConstantInt *CI) {
2020 uint64_t V = CI->getRawValue();
2021
2022 // There won't be bits set in parts that the type doesn't contain.
2023 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2024
2025 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2026 return U && V && (U & V) == 0;
2027}
2028#endif
2029
2030// isHighOnes - Return true if the constant is of the form 1+0+.
2031// This is the same as lowones(~X).
2032static bool isHighOnes(const ConstantInt *CI) {
2033 uint64_t V = ~CI->getRawValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002034 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002035
2036 // There won't be bits set in parts that the type doesn't contain.
2037 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2038
2039 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2040 return U && V && (U & V) == 0;
2041}
2042
2043
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002044/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2045/// are carefully arranged to allow folding of expressions such as:
2046///
2047/// (A < B) | (A > B) --> (A != B)
2048///
2049/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2050/// represents that the comparison is true if A == B, and bit value '1' is true
2051/// if A < B.
2052///
2053static unsigned getSetCondCode(const SetCondInst *SCI) {
2054 switch (SCI->getOpcode()) {
2055 // False -> 0
2056 case Instruction::SetGT: return 1;
2057 case Instruction::SetEQ: return 2;
2058 case Instruction::SetGE: return 3;
2059 case Instruction::SetLT: return 4;
2060 case Instruction::SetNE: return 5;
2061 case Instruction::SetLE: return 6;
2062 // True -> 7
2063 default:
2064 assert(0 && "Invalid SetCC opcode!");
2065 return 0;
2066 }
2067}
2068
2069/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2070/// opcode and two operands into either a constant true or false, or a brand new
2071/// SetCC instruction.
2072static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2073 switch (Opcode) {
2074 case 0: return ConstantBool::False;
2075 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2076 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2077 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2078 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2079 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2080 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2081 case 7: return ConstantBool::True;
2082 default: assert(0 && "Illegal SetCCCode!"); return 0;
2083 }
2084}
2085
2086// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2087struct FoldSetCCLogical {
2088 InstCombiner &IC;
2089 Value *LHS, *RHS;
2090 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2091 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2092 bool shouldApply(Value *V) const {
2093 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2094 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2095 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2096 return false;
2097 }
2098 Instruction *apply(BinaryOperator &Log) const {
2099 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2100 if (SCI->getOperand(0) != LHS) {
2101 assert(SCI->getOperand(1) == LHS);
2102 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2103 }
2104
2105 unsigned LHSCode = getSetCondCode(SCI);
2106 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2107 unsigned Code;
2108 switch (Log.getOpcode()) {
2109 case Instruction::And: Code = LHSCode & RHSCode; break;
2110 case Instruction::Or: Code = LHSCode | RHSCode; break;
2111 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002112 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002113 }
2114
2115 Value *RV = getSetCCValue(Code, LHS, RHS);
2116 if (Instruction *I = dyn_cast<Instruction>(RV))
2117 return I;
2118 // Otherwise, it's a constant boolean value...
2119 return IC.ReplaceInstUsesWith(Log, RV);
2120 }
2121};
2122
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002123// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2124// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2125// guaranteed to be either a shift instruction or a binary operator.
2126Instruction *InstCombiner::OptAndOp(Instruction *Op,
2127 ConstantIntegral *OpRHS,
2128 ConstantIntegral *AndRHS,
2129 BinaryOperator &TheAnd) {
2130 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002131 Constant *Together = 0;
2132 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00002133 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002134
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002135 switch (Op->getOpcode()) {
2136 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002137 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002138 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2139 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00002140 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002141 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002142 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002143 }
2144 break;
2145 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002146 if (Together == AndRHS) // (X | C) & C --> C
2147 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002148
Chris Lattner6e7ba452005-01-01 16:22:27 +00002149 if (Op->hasOneUse() && Together != OpRHS) {
2150 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2151 std::string Op0Name = Op->getName(); Op->setName("");
2152 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2153 InsertNewInstBefore(Or, TheAnd);
2154 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002155 }
2156 break;
2157 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002158 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002159 // Adding a one to a single bit bit-field should be turned into an XOR
2160 // of the bit. First thing to check is to see if this AND is with a
2161 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00002162 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002163
2164 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002165 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002166
2167 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002168 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002169 // Ok, at this point, we know that we are masking the result of the
2170 // ADD down to exactly one bit. If the constant we are adding has
2171 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00002172 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002173
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002174 // Check to see if any bits below the one bit set in AndRHSV are set.
2175 if ((AddRHS & (AndRHSV-1)) == 0) {
2176 // If not, the only thing that can effect the output of the AND is
2177 // the bit specified by AndRHSV. If that bit is set, the effect of
2178 // the XOR is to toggle the bit. If it is clear, then the ADD has
2179 // no effect.
2180 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2181 TheAnd.setOperand(0, X);
2182 return &TheAnd;
2183 } else {
2184 std::string Name = Op->getName(); Op->setName("");
2185 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00002186 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002187 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002188 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002189 }
2190 }
2191 }
2192 }
2193 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002194
2195 case Instruction::Shl: {
2196 // We know that the AND will not produce any of the bits shifted in, so if
2197 // the anded constant includes them, clear them now!
2198 //
2199 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002200 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2201 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002202
Chris Lattner0c967662004-09-24 15:21:34 +00002203 if (CI == ShlMask) { // Masking out bits that the shift already masks
2204 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2205 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002206 TheAnd.setOperand(1, CI);
2207 return &TheAnd;
2208 }
2209 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002210 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002211 case Instruction::Shr:
2212 // We know that the AND will not produce any of the bits shifted in, so if
2213 // the anded constant includes them, clear them now! This only applies to
2214 // unsigned shifts, because a signed shr may bring in set bits!
2215 //
2216 if (AndRHS->getType()->isUnsigned()) {
2217 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002218 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2219 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2220
2221 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2222 return ReplaceInstUsesWith(TheAnd, Op);
2223 } else if (CI != AndRHS) {
2224 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00002225 return &TheAnd;
2226 }
Chris Lattner0c967662004-09-24 15:21:34 +00002227 } else { // Signed shr.
2228 // See if this is shifting in some sign extension, then masking it out
2229 // with an and.
2230 if (Op->hasOneUse()) {
2231 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2232 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2233 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00002234 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00002235 // Make the argument unsigned.
2236 Value *ShVal = Op->getOperand(0);
2237 ShVal = InsertCastBefore(ShVal,
2238 ShVal->getType()->getUnsignedVersion(),
2239 TheAnd);
2240 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2241 OpRHS, Op->getName()),
2242 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00002243 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2244 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2245 TheAnd.getName()),
2246 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00002247 return new CastInst(ShVal, Op->getType());
2248 }
2249 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002250 }
2251 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002252 }
2253 return 0;
2254}
2255
Chris Lattner8b170942002-08-09 23:47:40 +00002256
Chris Lattnera96879a2004-09-29 17:40:11 +00002257/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2258/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2259/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2260/// insert new instructions.
2261Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2262 bool Inside, Instruction &IB) {
2263 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2264 "Lo is not <= Hi in range emission code!");
2265 if (Inside) {
2266 if (Lo == Hi) // Trivially false.
2267 return new SetCondInst(Instruction::SetNE, V, V);
2268 if (cast<ConstantIntegral>(Lo)->isMinValue())
2269 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00002270
Chris Lattnera96879a2004-09-29 17:40:11 +00002271 Constant *AddCST = ConstantExpr::getNeg(Lo);
2272 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2273 InsertNewInstBefore(Add, IB);
2274 // Convert to unsigned for the comparison.
2275 const Type *UnsType = Add->getType()->getUnsignedVersion();
2276 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2277 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2278 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2279 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2280 }
2281
2282 if (Lo == Hi) // Trivially true.
2283 return new SetCondInst(Instruction::SetEQ, V, V);
2284
2285 Hi = SubOne(cast<ConstantInt>(Hi));
2286 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2287 return new SetCondInst(Instruction::SetGT, V, Hi);
2288
2289 // Emit X-Lo > Hi-Lo-1
2290 Constant *AddCST = ConstantExpr::getNeg(Lo);
2291 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2292 InsertNewInstBefore(Add, IB);
2293 // Convert to unsigned for the comparison.
2294 const Type *UnsType = Add->getType()->getUnsignedVersion();
2295 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2296 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2297 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2298 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2299}
2300
Chris Lattner7203e152005-09-18 07:22:02 +00002301// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2302// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2303// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2304// not, since all 1s are not contiguous.
2305static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2306 uint64_t V = Val->getRawValue();
2307 if (!isShiftedMask_64(V)) return false;
2308
2309 // look for the first zero bit after the run of ones
2310 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2311 // look for the first non-zero bit
2312 ME = 64-CountLeadingZeros_64(V);
2313 return true;
2314}
2315
2316
2317
2318/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2319/// where isSub determines whether the operator is a sub. If we can fold one of
2320/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002321///
2322/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2323/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2324/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2325///
2326/// return (A +/- B).
2327///
2328Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2329 ConstantIntegral *Mask, bool isSub,
2330 Instruction &I) {
2331 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2332 if (!LHSI || LHSI->getNumOperands() != 2 ||
2333 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2334
2335 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2336
2337 switch (LHSI->getOpcode()) {
2338 default: return 0;
2339 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00002340 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2341 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2342 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2343 break;
2344
2345 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2346 // part, we don't need any explicit masks to take them out of A. If that
2347 // is all N is, ignore it.
2348 unsigned MB, ME;
2349 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00002350 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2351 Mask >>= 64-MB+1;
2352 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002353 break;
2354 }
2355 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002356 return 0;
2357 case Instruction::Or:
2358 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002359 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2360 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2361 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002362 break;
2363 return 0;
2364 }
2365
2366 Instruction *New;
2367 if (isSub)
2368 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2369 else
2370 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2371 return InsertNewInstBefore(New, I);
2372}
2373
Chris Lattner7e708292002-06-25 16:13:24 +00002374Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002375 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002376 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002377
Chris Lattnere87597f2004-10-16 18:11:37 +00002378 if (isa<UndefValue>(Op1)) // X & undef -> 0
2379 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2380
Chris Lattner6e7ba452005-01-01 16:22:27 +00002381 // and X, X = X
2382 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002383 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002384
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002385 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002386 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00002387 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002388 if (!isa<PackedType>(I.getType()) &&
2389 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner255d8912006-02-11 09:31:47 +00002390 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00002391 return &I;
2392
Chris Lattner6e7ba452005-01-01 16:22:27 +00002393 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00002394 uint64_t AndRHSMask = AndRHS->getZExtValue();
2395 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00002396 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002397
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002398 // Optimize a variety of ((val OP C1) & C2) combinations...
2399 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2400 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002401 Value *Op0LHS = Op0I->getOperand(0);
2402 Value *Op0RHS = Op0I->getOperand(1);
2403 switch (Op0I->getOpcode()) {
2404 case Instruction::Xor:
2405 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002406 // If the mask is only needed on one incoming arm, push it up.
2407 if (Op0I->hasOneUse()) {
2408 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2409 // Not masking anything out for the LHS, move to RHS.
2410 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2411 Op0RHS->getName()+".masked");
2412 InsertNewInstBefore(NewRHS, I);
2413 return BinaryOperator::create(
2414 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002415 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00002416 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00002417 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2418 // Not masking anything out for the RHS, move to LHS.
2419 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2420 Op0LHS->getName()+".masked");
2421 InsertNewInstBefore(NewLHS, I);
2422 return BinaryOperator::create(
2423 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2424 }
2425 }
2426
Chris Lattner6e7ba452005-01-01 16:22:27 +00002427 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00002428 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00002429 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2430 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2431 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2432 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2433 return BinaryOperator::createAnd(V, AndRHS);
2434 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2435 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002436 break;
2437
2438 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002439 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2440 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2441 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2442 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2443 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00002444 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002445 }
2446
Chris Lattner58403262003-07-23 19:25:52 +00002447 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002448 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002449 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002450 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2451 const Type *SrcTy = CI->getOperand(0)->getType();
2452
Chris Lattner2b83af22005-08-07 07:03:10 +00002453 // If this is an integer truncation or change from signed-to-unsigned, and
2454 // if the source is an and/or with immediate, transform it. This
2455 // frequently occurs for bitfield accesses.
2456 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2457 if (SrcTy->getPrimitiveSizeInBits() >=
2458 I.getType()->getPrimitiveSizeInBits() &&
2459 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00002460 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00002461 if (CastOp->getOpcode() == Instruction::And) {
2462 // Change: and (cast (and X, C1) to T), C2
2463 // into : and (cast X to T), trunc(C1)&C2
2464 // This will folds the two ands together, which may allow other
2465 // simplifications.
2466 Instruction *NewCast =
2467 new CastInst(CastOp->getOperand(0), I.getType(),
2468 CastOp->getName()+".shrunk");
2469 NewCast = InsertNewInstBefore(NewCast, I);
2470
2471 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2472 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2473 return BinaryOperator::createAnd(NewCast, C3);
2474 } else if (CastOp->getOpcode() == Instruction::Or) {
2475 // Change: and (cast (or X, C1) to T), C2
2476 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2477 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2478 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2479 return ReplaceInstUsesWith(I, AndRHS);
2480 }
2481 }
Chris Lattner06782f82003-07-23 19:36:21 +00002482 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002483
2484 // Try to fold constant and into select arguments.
2485 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002486 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002487 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002488 if (isa<PHINode>(Op0))
2489 if (Instruction *NV = FoldOpIntoPhi(I))
2490 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002491 }
2492
Chris Lattner8d969642003-03-10 23:06:50 +00002493 Value *Op0NotVal = dyn_castNotVal(Op0);
2494 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002495
Chris Lattner5b62aa72004-06-18 06:07:51 +00002496 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2497 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2498
Misha Brukmancb6267b2004-07-30 12:50:08 +00002499 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00002500 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00002501 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2502 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002503 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00002504 return BinaryOperator::createNot(Or);
2505 }
Chris Lattner2082ad92006-02-13 23:07:23 +00002506
2507 {
2508 Value *A = 0, *B = 0;
2509 ConstantInt *C1 = 0, *C2 = 0;
2510 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2511 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2512 return ReplaceInstUsesWith(I, Op1);
2513 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2514 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2515 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00002516
2517 if (Op0->hasOneUse() &&
2518 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2519 if (A == Op1) { // (A^B)&A -> A&(A^B)
2520 I.swapOperands(); // Simplify below
2521 std::swap(Op0, Op1);
2522 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2523 cast<BinaryOperator>(Op0)->swapOperands();
2524 I.swapOperands(); // Simplify below
2525 std::swap(Op0, Op1);
2526 }
2527 }
2528 if (Op1->hasOneUse() &&
2529 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2530 if (B == Op0) { // B&(A^B) -> B&(B^A)
2531 cast<BinaryOperator>(Op1)->swapOperands();
2532 std::swap(A, B);
2533 }
2534 if (A == Op0) { // A&(A^B) -> A & ~B
2535 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2536 InsertNewInstBefore(NotB, I);
2537 return BinaryOperator::createAnd(A, NotB);
2538 }
2539 }
Chris Lattner2082ad92006-02-13 23:07:23 +00002540 }
2541
Chris Lattnera2881962003-02-18 19:28:33 +00002542
Chris Lattner955f3312004-09-28 21:48:02 +00002543 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2544 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002545 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2546 return R;
2547
Chris Lattner955f3312004-09-28 21:48:02 +00002548 Value *LHSVal, *RHSVal;
2549 ConstantInt *LHSCst, *RHSCst;
2550 Instruction::BinaryOps LHSCC, RHSCC;
2551 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2552 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2553 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2554 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002555 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00002556 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2557 // Ensure that the larger constant is on the RHS.
2558 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2559 SetCondInst *LHS = cast<SetCondInst>(Op0);
2560 if (cast<ConstantBool>(Cmp)->getValue()) {
2561 std::swap(LHS, RHS);
2562 std::swap(LHSCst, RHSCst);
2563 std::swap(LHSCC, RHSCC);
2564 }
2565
2566 // At this point, we know we have have two setcc instructions
2567 // comparing a value against two constants and and'ing the result
2568 // together. Because of the above check, we know that we only have
2569 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2570 // FoldSetCCLogical check above), that the two constants are not
2571 // equal.
2572 assert(LHSCst != RHSCst && "Compares not folded above?");
2573
2574 switch (LHSCC) {
2575 default: assert(0 && "Unknown integer condition code!");
2576 case Instruction::SetEQ:
2577 switch (RHSCC) {
2578 default: assert(0 && "Unknown integer condition code!");
2579 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2580 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2581 return ReplaceInstUsesWith(I, ConstantBool::False);
2582 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2583 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2584 return ReplaceInstUsesWith(I, LHS);
2585 }
2586 case Instruction::SetNE:
2587 switch (RHSCC) {
2588 default: assert(0 && "Unknown integer condition code!");
2589 case Instruction::SetLT:
2590 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2591 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2592 break; // (X != 13 & X < 15) -> no change
2593 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2594 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2595 return ReplaceInstUsesWith(I, RHS);
2596 case Instruction::SetNE:
2597 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2598 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2599 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2600 LHSVal->getName()+".off");
2601 InsertNewInstBefore(Add, I);
2602 const Type *UnsType = Add->getType()->getUnsignedVersion();
2603 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2604 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2605 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2606 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2607 }
2608 break; // (X != 13 & X != 15) -> no change
2609 }
2610 break;
2611 case Instruction::SetLT:
2612 switch (RHSCC) {
2613 default: assert(0 && "Unknown integer condition code!");
2614 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2615 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2616 return ReplaceInstUsesWith(I, ConstantBool::False);
2617 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2618 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2619 return ReplaceInstUsesWith(I, LHS);
2620 }
2621 case Instruction::SetGT:
2622 switch (RHSCC) {
2623 default: assert(0 && "Unknown integer condition code!");
2624 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2625 return ReplaceInstUsesWith(I, LHS);
2626 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2627 return ReplaceInstUsesWith(I, RHS);
2628 case Instruction::SetNE:
2629 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2630 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2631 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00002632 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2633 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00002634 }
2635 }
2636 }
2637 }
2638
Chris Lattner7e708292002-06-25 16:13:24 +00002639 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002640}
2641
Chris Lattner7e708292002-06-25 16:13:24 +00002642Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002643 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002644 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002645
Chris Lattnere87597f2004-10-16 18:11:37 +00002646 if (isa<UndefValue>(Op1))
2647 return ReplaceInstUsesWith(I, // X | undef -> -1
2648 ConstantIntegral::getAllOnesValue(I.getType()));
2649
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002650 // or X, X = X
2651 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002652 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002653
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002654 // See if we can simplify any instructions used by the instruction whose sole
2655 // purpose is to compute bits we don't care about.
2656 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002657 if (!isa<PackedType>(I.getType()) &&
2658 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002659 KnownZero, KnownOne))
2660 return &I;
2661
Chris Lattner3f5b8772002-05-06 16:14:14 +00002662 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002663 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002664 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002665 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2666 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002667 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2668 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002669 InsertNewInstBefore(Or, I);
2670 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2671 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002672
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002673 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2674 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2675 std::string Op0Name = Op0->getName(); Op0->setName("");
2676 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2677 InsertNewInstBefore(Or, I);
2678 return BinaryOperator::createXor(Or,
2679 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002680 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002681
2682 // Try to fold constant and into select arguments.
2683 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002684 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002685 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002686 if (isa<PHINode>(Op0))
2687 if (Instruction *NV = FoldOpIntoPhi(I))
2688 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002689 }
2690
Chris Lattner4f637d42006-01-06 17:59:59 +00002691 Value *A = 0, *B = 0;
2692 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002693
2694 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2695 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2696 return ReplaceInstUsesWith(I, Op1);
2697 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2698 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2699 return ReplaceInstUsesWith(I, Op0);
2700
Chris Lattner6e4c6492005-05-09 04:58:36 +00002701 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2702 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002703 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002704 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2705 Op0->setName("");
2706 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2707 }
2708
2709 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2710 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002711 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002712 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2713 Op0->setName("");
2714 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2715 }
2716
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002717 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002718 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002719 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2720
2721 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2722 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2723
2724
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002725 // If we have: ((V + N) & C1) | (V & C2)
2726 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2727 // replace with V+N.
2728 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002729 Value *V1 = 0, *V2 = 0;
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002730 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2731 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2732 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002733 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002734 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002735 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002736 return ReplaceInstUsesWith(I, A);
2737 }
2738 // Or commutes, try both ways.
2739 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2740 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2741 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002742 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002743 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002744 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002745 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002746 }
2747 }
2748 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002749
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002750 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2751 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00002752 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002753 ConstantIntegral::getAllOnesValue(I.getType()));
2754 } else {
2755 A = 0;
2756 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002757 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002758 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2759 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00002760 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002761 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00002762
Misha Brukmancb6267b2004-07-30 12:50:08 +00002763 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002764 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2765 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2766 I.getName()+".demorgan"), I);
2767 return BinaryOperator::createNot(And);
2768 }
Chris Lattnera27231a2003-03-10 23:13:59 +00002769 }
Chris Lattnera2881962003-02-18 19:28:33 +00002770
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002771 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002772 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002773 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2774 return R;
2775
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002776 Value *LHSVal, *RHSVal;
2777 ConstantInt *LHSCst, *RHSCst;
2778 Instruction::BinaryOps LHSCC, RHSCC;
2779 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2780 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2781 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2782 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002783 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002784 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2785 // Ensure that the larger constant is on the RHS.
2786 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2787 SetCondInst *LHS = cast<SetCondInst>(Op0);
2788 if (cast<ConstantBool>(Cmp)->getValue()) {
2789 std::swap(LHS, RHS);
2790 std::swap(LHSCst, RHSCst);
2791 std::swap(LHSCC, RHSCC);
2792 }
2793
2794 // At this point, we know we have have two setcc instructions
2795 // comparing a value against two constants and or'ing the result
2796 // together. Because of the above check, we know that we only have
2797 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2798 // FoldSetCCLogical check above), that the two constants are not
2799 // equal.
2800 assert(LHSCst != RHSCst && "Compares not folded above?");
2801
2802 switch (LHSCC) {
2803 default: assert(0 && "Unknown integer condition code!");
2804 case Instruction::SetEQ:
2805 switch (RHSCC) {
2806 default: assert(0 && "Unknown integer condition code!");
2807 case Instruction::SetEQ:
2808 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2809 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2810 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2811 LHSVal->getName()+".off");
2812 InsertNewInstBefore(Add, I);
2813 const Type *UnsType = Add->getType()->getUnsignedVersion();
2814 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2815 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2816 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2817 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2818 }
2819 break; // (X == 13 | X == 15) -> no change
2820
Chris Lattner240d6f42005-04-19 06:04:18 +00002821 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2822 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002823 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2824 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2825 return ReplaceInstUsesWith(I, RHS);
2826 }
2827 break;
2828 case Instruction::SetNE:
2829 switch (RHSCC) {
2830 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002831 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2832 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2833 return ReplaceInstUsesWith(I, LHS);
2834 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00002835 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002836 return ReplaceInstUsesWith(I, ConstantBool::True);
2837 }
2838 break;
2839 case Instruction::SetLT:
2840 switch (RHSCC) {
2841 default: assert(0 && "Unknown integer condition code!");
2842 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2843 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00002844 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2845 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002846 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2847 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2848 return ReplaceInstUsesWith(I, RHS);
2849 }
2850 break;
2851 case Instruction::SetGT:
2852 switch (RHSCC) {
2853 default: assert(0 && "Unknown integer condition code!");
2854 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2855 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2856 return ReplaceInstUsesWith(I, LHS);
2857 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2858 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2859 return ReplaceInstUsesWith(I, ConstantBool::True);
2860 }
2861 }
2862 }
2863 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002864
Chris Lattner7e708292002-06-25 16:13:24 +00002865 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002866}
2867
Chris Lattnerc317d392004-02-16 01:20:27 +00002868// XorSelf - Implements: X ^ X --> 0
2869struct XorSelf {
2870 Value *RHS;
2871 XorSelf(Value *rhs) : RHS(rhs) {}
2872 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2873 Instruction *apply(BinaryOperator &Xor) const {
2874 return &Xor;
2875 }
2876};
Chris Lattner3f5b8772002-05-06 16:14:14 +00002877
2878
Chris Lattner7e708292002-06-25 16:13:24 +00002879Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002880 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002882
Chris Lattnere87597f2004-10-16 18:11:37 +00002883 if (isa<UndefValue>(Op1))
2884 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2885
Chris Lattnerc317d392004-02-16 01:20:27 +00002886 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2887 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2888 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00002889 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00002890 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002891
2892 // See if we can simplify any instructions used by the instruction whose sole
2893 // purpose is to compute bits we don't care about.
2894 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002895 if (!isa<PackedType>(I.getType()) &&
2896 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002897 KnownZero, KnownOne))
2898 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002899
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002900 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002901 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00002902 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002903 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00002904 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00002905 return new SetCondInst(SCI->getInverseCondition(),
2906 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00002907
Chris Lattnerd65460f2003-11-05 01:06:05 +00002908 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00002909 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2910 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00002911 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2912 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002913 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00002914 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002915 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00002916
2917 // ~(~X & Y) --> (X | ~Y)
2918 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2919 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2920 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2921 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00002922 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00002923 Op0I->getOperand(1)->getName()+".not");
2924 InsertNewInstBefore(NotY, I);
2925 return BinaryOperator::createOr(Op0NotVal, NotY);
2926 }
2927 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002928
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002929 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002930 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00002931 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00002932 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00002933 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2934 return BinaryOperator::createSub(
2935 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00002936 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00002937 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00002938 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00002939 } else if (Op0I->getOpcode() == Instruction::Or) {
2940 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2941 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2942 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2943 // Anything in both C1 and C2 is known to be zero, remove it from
2944 // NewRHS.
2945 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2946 NewRHS = ConstantExpr::getAnd(NewRHS,
2947 ConstantExpr::getNot(CommonBits));
2948 WorkList.push_back(Op0I);
2949 I.setOperand(0, Op0I->getOperand(0));
2950 I.setOperand(1, NewRHS);
2951 return &I;
2952 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00002953 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00002954 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002955
2956 // Try to fold constant and into select arguments.
2957 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002958 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002959 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002960 if (isa<PHINode>(Op0))
2961 if (Instruction *NV = FoldOpIntoPhi(I))
2962 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002963 }
2964
Chris Lattner8d969642003-03-10 23:06:50 +00002965 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002966 if (X == Op1)
2967 return ReplaceInstUsesWith(I,
2968 ConstantIntegral::getAllOnesValue(I.getType()));
2969
Chris Lattner8d969642003-03-10 23:06:50 +00002970 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00002971 if (X == Op0)
2972 return ReplaceInstUsesWith(I,
2973 ConstantIntegral::getAllOnesValue(I.getType()));
2974
Chris Lattner64daab52006-04-01 08:03:55 +00002975 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00002976 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00002977 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002978 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00002979 I.swapOperands();
2980 std::swap(Op0, Op1);
2981 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00002982 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00002983 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00002984 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002985 } else if (Op1I->getOpcode() == Instruction::Xor) {
2986 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2987 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2988 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2989 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00002990 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
2991 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
2992 Op1I->swapOperands();
2993 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
2994 I.swapOperands(); // Simplified below.
2995 std::swap(Op0, Op1);
2996 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00002997 }
Chris Lattnercb40a372003-03-10 18:24:17 +00002998
Chris Lattner64daab52006-04-01 08:03:55 +00002999 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00003000 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003001 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003002 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00003003 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00003004 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3005 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00003006 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00003007 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003008 } else if (Op0I->getOpcode() == Instruction::Xor) {
3009 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3010 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3011 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3012 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003013 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3014 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3015 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00003016 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3017 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00003018 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3019 InsertNewInstBefore(N, I);
3020 return BinaryOperator::createAnd(N, Op1);
3021 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003022 }
3023
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003024 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3025 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3026 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3027 return R;
3028
Chris Lattner7e708292002-06-25 16:13:24 +00003029 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003030}
3031
Chris Lattnera96879a2004-09-29 17:40:11 +00003032/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3033/// overflowed for this type.
3034static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3035 ConstantInt *In2) {
3036 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3037 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3038}
3039
3040static bool isPositive(ConstantInt *C) {
3041 return cast<ConstantSInt>(C)->getValue() >= 0;
3042}
3043
3044/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3045/// overflowed for this type.
3046static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3047 ConstantInt *In2) {
3048 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3049
3050 if (In1->getType()->isUnsigned())
3051 return cast<ConstantUInt>(Result)->getValue() <
3052 cast<ConstantUInt>(In1)->getValue();
3053 if (isPositive(In1) != isPositive(In2))
3054 return false;
3055 if (isPositive(In1))
3056 return cast<ConstantSInt>(Result)->getValue() <
3057 cast<ConstantSInt>(In1)->getValue();
3058 return cast<ConstantSInt>(Result)->getValue() >
3059 cast<ConstantSInt>(In1)->getValue();
3060}
3061
Chris Lattner574da9b2005-01-13 20:14:25 +00003062/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3063/// code necessary to compute the offset from the base pointer (without adding
3064/// in the base pointer). Return the result as a signed integer of intptr size.
3065static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3066 TargetData &TD = IC.getTargetData();
3067 gep_type_iterator GTI = gep_type_begin(GEP);
3068 const Type *UIntPtrTy = TD.getIntPtrType();
3069 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3070 Value *Result = Constant::getNullValue(SIntPtrTy);
3071
3072 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00003073 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00003074
Chris Lattner574da9b2005-01-13 20:14:25 +00003075 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3076 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00003077 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00003078 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3079 SIntPtrTy);
3080 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3081 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003082 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00003083 Scale = ConstantExpr::getMul(OpC, Scale);
3084 if (Constant *RC = dyn_cast<Constant>(Result))
3085 Result = ConstantExpr::getAdd(RC, Scale);
3086 else {
3087 // Emit an add instruction.
3088 Result = IC.InsertNewInstBefore(
3089 BinaryOperator::createAdd(Result, Scale,
3090 GEP->getName()+".offs"), I);
3091 }
3092 }
3093 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00003094 // Convert to correct type.
3095 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3096 Op->getName()+".c"), I);
3097 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003098 // We'll let instcombine(mul) convert this to a shl if possible.
3099 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3100 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00003101
3102 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003103 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00003104 GEP->getName()+".offs"), I);
3105 }
3106 }
3107 return Result;
3108}
3109
3110/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3111/// else. At this point we know that the GEP is on the LHS of the comparison.
3112Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3113 Instruction::BinaryOps Cond,
3114 Instruction &I) {
3115 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00003116
3117 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3118 if (isa<PointerType>(CI->getOperand(0)->getType()))
3119 RHS = CI->getOperand(0);
3120
Chris Lattner574da9b2005-01-13 20:14:25 +00003121 Value *PtrBase = GEPLHS->getOperand(0);
3122 if (PtrBase == RHS) {
3123 // As an optimization, we don't actually have to compute the actual value of
3124 // OFFSET if this is a seteq or setne comparison, just return whether each
3125 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003126 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3127 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003128 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3129 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00003130 bool EmitIt = true;
3131 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3132 if (isa<UndefValue>(C)) // undef index -> undef.
3133 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3134 if (C->isNullValue())
3135 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003136 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3137 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00003138 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00003139 return ReplaceInstUsesWith(I, // No comparison is needed here.
3140 ConstantBool::get(Cond == Instruction::SetNE));
3141 }
3142
3143 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003144 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00003145 new SetCondInst(Cond, GEPLHS->getOperand(i),
3146 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3147 if (InVal == 0)
3148 InVal = Comp;
3149 else {
3150 InVal = InsertNewInstBefore(InVal, I);
3151 InsertNewInstBefore(Comp, I);
3152 if (Cond == Instruction::SetNE) // True if any are unequal
3153 InVal = BinaryOperator::createOr(InVal, Comp);
3154 else // True if all are equal
3155 InVal = BinaryOperator::createAnd(InVal, Comp);
3156 }
3157 }
3158 }
3159
3160 if (InVal)
3161 return InVal;
3162 else
3163 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3164 ConstantBool::get(Cond == Instruction::SetEQ));
3165 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003166
3167 // Only lower this if the setcc is the only user of the GEP or if we expect
3168 // the result to fold to a constant!
3169 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3170 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3171 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3172 return new SetCondInst(Cond, Offset,
3173 Constant::getNullValue(Offset->getType()));
3174 }
3175 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00003176 // If the base pointers are different, but the indices are the same, just
3177 // compare the base pointer.
3178 if (PtrBase != GEPRHS->getOperand(0)) {
3179 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00003180 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00003181 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00003182 if (IndicesTheSame)
3183 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3184 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3185 IndicesTheSame = false;
3186 break;
3187 }
3188
3189 // If all indices are the same, just compare the base pointers.
3190 if (IndicesTheSame)
3191 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3192 GEPRHS->getOperand(0));
3193
3194 // Otherwise, the base pointers are different and the indices are
3195 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00003196 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00003197 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003198
Chris Lattnere9d782b2005-01-13 22:25:21 +00003199 // If one of the GEPs has all zero indices, recurse.
3200 bool AllZeros = true;
3201 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3202 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3203 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3204 AllZeros = false;
3205 break;
3206 }
3207 if (AllZeros)
3208 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3209 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003210
3211 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003212 AllZeros = true;
3213 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3214 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3215 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3216 AllZeros = false;
3217 break;
3218 }
3219 if (AllZeros)
3220 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3221
Chris Lattner4401c9c2005-01-14 00:20:05 +00003222 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3223 // If the GEPs only differ by one index, compare it.
3224 unsigned NumDifferences = 0; // Keep track of # differences.
3225 unsigned DiffOperand = 0; // The operand that differs.
3226 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3227 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00003228 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3229 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003230 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00003231 NumDifferences = 2;
3232 break;
3233 } else {
3234 if (NumDifferences++) break;
3235 DiffOperand = i;
3236 }
3237 }
3238
3239 if (NumDifferences == 0) // SAME GEP?
3240 return ReplaceInstUsesWith(I, // No comparison is needed here.
3241 ConstantBool::get(Cond == Instruction::SetEQ));
3242 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003243 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3244 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00003245
3246 // Convert the operands to signed values to make sure to perform a
3247 // signed comparison.
3248 const Type *NewTy = LHSV->getType()->getSignedVersion();
3249 if (LHSV->getType() != NewTy)
3250 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3251 LHSV->getName()), I);
3252 if (RHSV->getType() != NewTy)
3253 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3254 RHSV->getName()), I);
3255 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003256 }
3257 }
3258
Chris Lattner574da9b2005-01-13 20:14:25 +00003259 // Only lower this if the setcc is the only user of the GEP or if we expect
3260 // the result to fold to a constant!
3261 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3262 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3263 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3264 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3265 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3266 return new SetCondInst(Cond, L, R);
3267 }
3268 }
3269 return 0;
3270}
3271
3272
Chris Lattner484d3cf2005-04-24 06:59:08 +00003273Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003274 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00003275 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3276 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00003277
3278 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00003279 if (Op0 == Op1)
3280 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00003281
Chris Lattnere87597f2004-10-16 18:11:37 +00003282 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3283 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3284
Chris Lattner711b3402004-11-14 07:33:16 +00003285 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3286 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00003287 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3288 isa<ConstantPointerNull>(Op0)) &&
3289 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00003290 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00003291 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3292
3293 // setcc's with boolean values can always be turned into bitwise operations
3294 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00003295 switch (I.getOpcode()) {
3296 default: assert(0 && "Invalid setcc instruction!");
3297 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00003298 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00003299 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00003300 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00003301 }
Chris Lattner5dbef222004-08-11 00:50:51 +00003302 case Instruction::SetNE:
3303 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00003304
Chris Lattner5dbef222004-08-11 00:50:51 +00003305 case Instruction::SetGT:
3306 std::swap(Op0, Op1); // Change setgt -> setlt
3307 // FALL THROUGH
3308 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3309 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3310 InsertNewInstBefore(Not, I);
3311 return BinaryOperator::createAnd(Not, Op1);
3312 }
3313 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00003314 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00003315 // FALL THROUGH
3316 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3317 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3318 InsertNewInstBefore(Not, I);
3319 return BinaryOperator::createOr(Not, Op1);
3320 }
3321 }
Chris Lattner8b170942002-08-09 23:47:40 +00003322 }
3323
Chris Lattner2be51ae2004-06-09 04:24:29 +00003324 // See if we are doing a comparison between a constant and an instruction that
3325 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00003326 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003327 // Check to see if we are comparing against the minimum or maximum value...
3328 if (CI->isMinValue()) {
3329 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3330 return ReplaceInstUsesWith(I, ConstantBool::False);
3331 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3332 return ReplaceInstUsesWith(I, ConstantBool::True);
3333 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3334 return BinaryOperator::createSetEQ(Op0, Op1);
3335 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3336 return BinaryOperator::createSetNE(Op0, Op1);
3337
3338 } else if (CI->isMaxValue()) {
3339 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3340 return ReplaceInstUsesWith(I, ConstantBool::False);
3341 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3342 return ReplaceInstUsesWith(I, ConstantBool::True);
3343 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3344 return BinaryOperator::createSetEQ(Op0, Op1);
3345 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3346 return BinaryOperator::createSetNE(Op0, Op1);
3347
3348 // Comparing against a value really close to min or max?
3349 } else if (isMinValuePlusOne(CI)) {
3350 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3351 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3352 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3353 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3354
3355 } else if (isMaxValueMinusOne(CI)) {
3356 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3357 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3358 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3359 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3360 }
3361
3362 // If we still have a setle or setge instruction, turn it into the
3363 // appropriate setlt or setgt instruction. Since the border cases have
3364 // already been handled above, this requires little checking.
3365 //
3366 if (I.getOpcode() == Instruction::SetLE)
3367 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3368 if (I.getOpcode() == Instruction::SetGE)
3369 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3370
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003371
3372 // See if we can fold the comparison based on bits known to be zero or one
3373 // in the input.
3374 uint64_t KnownZero, KnownOne;
3375 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3376 KnownZero, KnownOne, 0))
3377 return &I;
3378
3379 // Given the known and unknown bits, compute a range that the LHS could be
3380 // in.
3381 if (KnownOne | KnownZero) {
3382 if (Ty->isUnsigned()) { // Unsigned comparison.
3383 uint64_t Min, Max;
3384 uint64_t RHSVal = CI->getZExtValue();
3385 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3386 Min, Max);
3387 switch (I.getOpcode()) { // LE/GE have been folded already.
3388 default: assert(0 && "Unknown setcc opcode!");
3389 case Instruction::SetEQ:
3390 if (Max < RHSVal || Min > RHSVal)
3391 return ReplaceInstUsesWith(I, ConstantBool::False);
3392 break;
3393 case Instruction::SetNE:
3394 if (Max < RHSVal || Min > RHSVal)
3395 return ReplaceInstUsesWith(I, ConstantBool::True);
3396 break;
3397 case Instruction::SetLT:
3398 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3399 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3400 break;
3401 case Instruction::SetGT:
3402 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3403 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3404 break;
3405 }
3406 } else { // Signed comparison.
3407 int64_t Min, Max;
3408 int64_t RHSVal = CI->getSExtValue();
3409 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3410 Min, Max);
3411 switch (I.getOpcode()) { // LE/GE have been folded already.
3412 default: assert(0 && "Unknown setcc opcode!");
3413 case Instruction::SetEQ:
3414 if (Max < RHSVal || Min > RHSVal)
3415 return ReplaceInstUsesWith(I, ConstantBool::False);
3416 break;
3417 case Instruction::SetNE:
3418 if (Max < RHSVal || Min > RHSVal)
3419 return ReplaceInstUsesWith(I, ConstantBool::True);
3420 break;
3421 case Instruction::SetLT:
3422 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3423 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3424 break;
3425 case Instruction::SetGT:
3426 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3427 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3428 break;
3429 }
3430 }
3431 }
3432
3433
Chris Lattner3c6a0d42004-05-25 06:32:08 +00003434 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00003435 switch (LHSI->getOpcode()) {
3436 case Instruction::And:
3437 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3438 LHSI->getOperand(0)->hasOneUse()) {
3439 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3440 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3441 // happens a LOT in code produced by the C front-end, for bitfield
3442 // access.
3443 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003444 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3445
3446 // Check to see if there is a noop-cast between the shift and the and.
3447 if (!Shift) {
3448 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3449 if (CI->getOperand(0)->getType()->isIntegral() &&
3450 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3451 CI->getType()->getPrimitiveSizeInBits())
3452 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3453 }
3454
Chris Lattner648e3bc2004-09-23 21:52:49 +00003455 ConstantUInt *ShAmt;
3456 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003457 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3458 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00003459
Chris Lattner648e3bc2004-09-23 21:52:49 +00003460 // We can fold this as long as we can't shift unknown bits
3461 // into the mask. This can only happen with signed shift
3462 // rights, as they sign-extend.
3463 if (ShAmt) {
3464 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003465 Ty->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00003466 if (!CanFold) {
3467 // To test for the bad case of the signed shr, see if any
3468 // of the bits shifted in could be tested after the mask.
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00003469 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3470 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3471
3472 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00003473 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003474 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3475 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00003476 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3477 CanFold = true;
3478 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003479
Chris Lattner648e3bc2004-09-23 21:52:49 +00003480 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00003481 Constant *NewCst;
3482 if (Shift->getOpcode() == Instruction::Shl)
3483 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3484 else
3485 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003486
Chris Lattner648e3bc2004-09-23 21:52:49 +00003487 // Check to see if we are shifting out any of the bits being
3488 // compared.
3489 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3490 // If we shifted bits out, the fold is not going to work out.
3491 // As a special case, check to see if this means that the
3492 // result is always true or false now.
3493 if (I.getOpcode() == Instruction::SetEQ)
3494 return ReplaceInstUsesWith(I, ConstantBool::False);
3495 if (I.getOpcode() == Instruction::SetNE)
3496 return ReplaceInstUsesWith(I, ConstantBool::True);
3497 } else {
3498 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00003499 Constant *NewAndCST;
3500 if (Shift->getOpcode() == Instruction::Shl)
3501 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3502 else
3503 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3504 LHSI->setOperand(1, NewAndCST);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003505 if (AndTy == Ty)
3506 LHSI->setOperand(0, Shift->getOperand(0));
3507 else {
3508 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3509 *Shift);
3510 LHSI->setOperand(0, NewCast);
3511 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003512 WorkList.push_back(Shift); // Shift is dead.
3513 AddUsesToWorkList(I);
3514 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00003515 }
3516 }
Chris Lattner457dd822004-06-09 07:59:58 +00003517 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003518 }
3519 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00003520
Chris Lattner18d19ca2004-09-28 18:22:15 +00003521 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3522 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3523 switch (I.getOpcode()) {
3524 default: break;
3525 case Instruction::SetEQ:
3526 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003527 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3528
3529 // Check that the shift amount is in range. If not, don't perform
3530 // undefined shifts. When the shift is visited it will be
3531 // simplified.
3532 if (ShAmt->getValue() >= TypeBits)
3533 break;
3534
Chris Lattner18d19ca2004-09-28 18:22:15 +00003535 // If we are comparing against bits always shifted out, the
3536 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003537 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00003538 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3539 if (Comp != CI) {// Comparing against a bit that we know is zero.
3540 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3541 Constant *Cst = ConstantBool::get(IsSetNE);
3542 return ReplaceInstUsesWith(I, Cst);
3543 }
3544
3545 if (LHSI->hasOneUse()) {
3546 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00003547 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003548 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3549
3550 Constant *Mask;
3551 if (CI->getType()->isUnsigned()) {
3552 Mask = ConstantUInt::get(CI->getType(), Val);
3553 } else if (ShAmtVal != 0) {
3554 Mask = ConstantSInt::get(CI->getType(), Val);
3555 } else {
3556 Mask = ConstantInt::getAllOnesValue(CI->getType());
3557 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003558
Chris Lattner18d19ca2004-09-28 18:22:15 +00003559 Instruction *AndI =
3560 BinaryOperator::createAnd(LHSI->getOperand(0),
3561 Mask, LHSI->getName()+".mask");
3562 Value *And = InsertNewInstBefore(AndI, I);
3563 return new SetCondInst(I.getOpcode(), And,
3564 ConstantExpr::getUShr(CI, ShAmt));
3565 }
3566 }
3567 }
3568 }
3569 break;
3570
Chris Lattner83c4ec02004-09-27 19:29:18 +00003571 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00003572 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00003573 switch (I.getOpcode()) {
3574 default: break;
3575 case Instruction::SetEQ:
3576 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003577
3578 // Check that the shift amount is in range. If not, don't perform
3579 // undefined shifts. When the shift is visited it will be
3580 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00003581 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnere17a1282005-06-15 20:53:31 +00003582 if (ShAmt->getValue() >= TypeBits)
3583 break;
3584
Chris Lattnerf63f6472004-09-27 16:18:50 +00003585 // If we are comparing against bits always shifted out, the
3586 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003587 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00003588 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00003589
Chris Lattnerf63f6472004-09-27 16:18:50 +00003590 if (Comp != CI) {// Comparing against a bit that we know is zero.
3591 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3592 Constant *Cst = ConstantBool::get(IsSetNE);
3593 return ReplaceInstUsesWith(I, Cst);
3594 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003595
Chris Lattnerf63f6472004-09-27 16:18:50 +00003596 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003597 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003598
Chris Lattnerf63f6472004-09-27 16:18:50 +00003599 // Otherwise strength reduce the shift into an and.
3600 uint64_t Val = ~0ULL; // All ones.
3601 Val <<= ShAmtVal; // Shift over to the right spot.
3602
3603 Constant *Mask;
3604 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00003605 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00003606 Mask = ConstantUInt::get(CI->getType(), Val);
3607 } else {
3608 Mask = ConstantSInt::get(CI->getType(), Val);
3609 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003610
Chris Lattnerf63f6472004-09-27 16:18:50 +00003611 Instruction *AndI =
3612 BinaryOperator::createAnd(LHSI->getOperand(0),
3613 Mask, LHSI->getName()+".mask");
3614 Value *And = InsertNewInstBefore(AndI, I);
3615 return new SetCondInst(I.getOpcode(), And,
3616 ConstantExpr::getShl(CI, ShAmt));
3617 }
3618 break;
3619 }
3620 }
3621 }
3622 break;
Chris Lattner0c967662004-09-24 15:21:34 +00003623
Chris Lattnera96879a2004-09-29 17:40:11 +00003624 case Instruction::Div:
3625 // Fold: (div X, C1) op C2 -> range check
3626 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3627 // Fold this div into the comparison, producing a range check.
3628 // Determine, based on the divide type, what the range is being
3629 // checked. If there is an overflow on the low or high side, remember
3630 // it, otherwise compute the range [low, hi) bounding the new value.
3631 bool LoOverflow = false, HiOverflow = 0;
3632 ConstantInt *LoBound = 0, *HiBound = 0;
3633
3634 ConstantInt *Prod;
3635 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3636
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003637 Instruction::BinaryOps Opcode = I.getOpcode();
3638
Chris Lattnera96879a2004-09-29 17:40:11 +00003639 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3640 } else if (LHSI->getType()->isUnsigned()) { // udiv
3641 LoBound = Prod;
3642 LoOverflow = ProdOV;
3643 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3644 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3645 if (CI->isNullValue()) { // (X / pos) op 0
3646 // Can't overflow.
3647 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3648 HiBound = DivRHS;
3649 } else if (isPositive(CI)) { // (X / pos) op pos
3650 LoBound = Prod;
3651 LoOverflow = ProdOV;
3652 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3653 } else { // (X / pos) op neg
3654 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3655 LoOverflow = AddWithOverflow(LoBound, Prod,
3656 cast<ConstantInt>(DivRHSH));
3657 HiBound = Prod;
3658 HiOverflow = ProdOV;
3659 }
3660 } else { // Divisor is < 0.
3661 if (CI->isNullValue()) { // (X / neg) op 0
3662 LoBound = AddOne(DivRHS);
3663 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00003664 if (HiBound == DivRHS)
3665 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00003666 } else if (isPositive(CI)) { // (X / neg) op pos
3667 HiOverflow = LoOverflow = ProdOV;
3668 if (!LoOverflow)
3669 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3670 HiBound = AddOne(Prod);
3671 } else { // (X / neg) op neg
3672 LoBound = Prod;
3673 LoOverflow = HiOverflow = ProdOV;
3674 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3675 }
Chris Lattner340a05f2004-10-08 19:15:44 +00003676
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003677 // Dividing by a negate swaps the condition.
3678 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00003679 }
3680
3681 if (LoBound) {
3682 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003683 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003684 default: assert(0 && "Unhandled setcc opcode!");
3685 case Instruction::SetEQ:
3686 if (LoOverflow && HiOverflow)
3687 return ReplaceInstUsesWith(I, ConstantBool::False);
3688 else if (HiOverflow)
3689 return new SetCondInst(Instruction::SetGE, X, LoBound);
3690 else if (LoOverflow)
3691 return new SetCondInst(Instruction::SetLT, X, HiBound);
3692 else
3693 return InsertRangeTest(X, LoBound, HiBound, true, I);
3694 case Instruction::SetNE:
3695 if (LoOverflow && HiOverflow)
3696 return ReplaceInstUsesWith(I, ConstantBool::True);
3697 else if (HiOverflow)
3698 return new SetCondInst(Instruction::SetLT, X, LoBound);
3699 else if (LoOverflow)
3700 return new SetCondInst(Instruction::SetGE, X, HiBound);
3701 else
3702 return InsertRangeTest(X, LoBound, HiBound, false, I);
3703 case Instruction::SetLT:
3704 if (LoOverflow)
3705 return ReplaceInstUsesWith(I, ConstantBool::False);
3706 return new SetCondInst(Instruction::SetLT, X, LoBound);
3707 case Instruction::SetGT:
3708 if (HiOverflow)
3709 return ReplaceInstUsesWith(I, ConstantBool::False);
3710 return new SetCondInst(Instruction::SetGE, X, HiBound);
3711 }
3712 }
3713 }
3714 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00003715 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003716
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003717 // Simplify seteq and setne instructions...
3718 if (I.getOpcode() == Instruction::SetEQ ||
3719 I.getOpcode() == Instruction::SetNE) {
3720 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3721
Chris Lattner00b1a7e2003-07-23 17:26:36 +00003722 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003723 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00003724 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3725 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00003726 case Instruction::Rem:
3727 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3728 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3729 BO->hasOneUse() &&
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003730 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3731 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3732 if (isPowerOf2_64(V)) {
3733 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00003734 const Type *UTy = BO->getType()->getUnsignedVersion();
3735 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3736 UTy, "tmp"), I);
3737 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3738 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3739 RHSCst, BO->getName()), I);
3740 return BinaryOperator::create(I.getOpcode(), NewRem,
3741 Constant::getNullValue(UTy));
3742 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003743 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003744 break;
Chris Lattner3571b722004-07-06 07:38:18 +00003745
Chris Lattner934754b2003-08-13 05:33:12 +00003746 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00003747 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3748 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00003749 if (BO->hasOneUse())
3750 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3751 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00003752 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003753 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3754 // efficiently invertible, or if the add has just this one use.
3755 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003756
Chris Lattner934754b2003-08-13 05:33:12 +00003757 if (Value *NegVal = dyn_castNegVal(BOp1))
3758 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3759 else if (Value *NegVal = dyn_castNegVal(BOp0))
3760 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00003761 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003762 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3763 BO->setName("");
3764 InsertNewInstBefore(Neg, I);
3765 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3766 }
3767 }
3768 break;
3769 case Instruction::Xor:
3770 // For the xor case, we can xor two constants together, eliminating
3771 // the explicit xor.
3772 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3773 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003774 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00003775
3776 // FALLTHROUGH
3777 case Instruction::Sub:
3778 // Replace (([sub|xor] A, B) != 0) with (A != B)
3779 if (CI->isNullValue())
3780 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3781 BO->getOperand(1));
3782 break;
3783
3784 case Instruction::Or:
3785 // If bits are being or'd in that are not present in the constant we
3786 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00003787 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00003788 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00003789 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003790 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003791 }
Chris Lattner934754b2003-08-13 05:33:12 +00003792 break;
3793
3794 case Instruction::And:
3795 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003796 // If bits are being compared against that are and'd out, then the
3797 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00003798 if (!ConstantExpr::getAnd(CI,
3799 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003800 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00003801
Chris Lattner457dd822004-06-09 07:59:58 +00003802 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00003803 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00003804 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3805 Instruction::SetNE, Op0,
3806 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00003807
Chris Lattner934754b2003-08-13 05:33:12 +00003808 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3809 // to be a signed value as appropriate.
3810 if (isSignBit(BOC)) {
3811 Value *X = BO->getOperand(0);
3812 // If 'X' is not signed, insert a cast now...
3813 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00003814 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00003815 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00003816 }
3817 return new SetCondInst(isSetNE ? Instruction::SetLT :
3818 Instruction::SetGE, X,
3819 Constant::getNullValue(X->getType()));
3820 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003821
Chris Lattner83c4ec02004-09-27 19:29:18 +00003822 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003823 if (CI->isNullValue() && isHighOnes(BOC)) {
3824 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003825 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003826
3827 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00003828 if (NegX->getType()->isSigned()) {
3829 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3830 X = InsertCastBefore(X, DestTy, I);
3831 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003832 }
3833
3834 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00003835 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003836 }
3837
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003838 }
Chris Lattner934754b2003-08-13 05:33:12 +00003839 default: break;
3840 }
3841 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003842 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00003843 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003844 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3845 Value *CastOp = Cast->getOperand(0);
3846 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00003847 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003848 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003849 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003850 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003851 "Source and destination signednesses should differ!");
3852 if (Cast->getType()->isSigned()) {
3853 // If this is a signed comparison, check for comparisons in the
3854 // vicinity of zero.
3855 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3856 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00003857 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003858 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003859 else if (I.getOpcode() == Instruction::SetGT &&
3860 cast<ConstantSInt>(CI)->getValue() == -1)
3861 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00003862 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00003863 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003864 } else {
3865 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3866 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003867 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003868 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00003869 return BinaryOperator::createSetGT(CastOp,
3870 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003871 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00003872 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003873 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00003874 return BinaryOperator::createSetLT(CastOp,
3875 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00003876 }
3877 }
3878 }
Chris Lattner40f5d702003-06-04 05:10:11 +00003879 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003880 }
3881
Chris Lattner6970b662005-04-23 15:31:55 +00003882 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3883 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3884 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3885 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00003886 case Instruction::GetElementPtr:
3887 if (RHSC->isNullValue()) {
3888 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3889 bool isAllZeros = true;
3890 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3891 if (!isa<Constant>(LHSI->getOperand(i)) ||
3892 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3893 isAllZeros = false;
3894 break;
3895 }
3896 if (isAllZeros)
3897 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3898 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3899 }
3900 break;
3901
Chris Lattner6970b662005-04-23 15:31:55 +00003902 case Instruction::PHI:
3903 if (Instruction *NV = FoldOpIntoPhi(I))
3904 return NV;
3905 break;
3906 case Instruction::Select:
3907 // If either operand of the select is a constant, we can fold the
3908 // comparison into the select arms, which will cause one to be
3909 // constant folded and the select turned into a bitwise or.
3910 Value *Op1 = 0, *Op2 = 0;
3911 if (LHSI->hasOneUse()) {
3912 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3913 // Fold the known value into the constant operand.
3914 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3915 // Insert a new SetCC of the other select operand.
3916 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3917 LHSI->getOperand(2), RHSC,
3918 I.getName()), I);
3919 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3920 // Fold the known value into the constant operand.
3921 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3922 // Insert a new SetCC of the other select operand.
3923 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3924 LHSI->getOperand(1), RHSC,
3925 I.getName()), I);
3926 }
3927 }
Jeff Cohen9d809302005-04-23 21:38:35 +00003928
Chris Lattner6970b662005-04-23 15:31:55 +00003929 if (Op1)
3930 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3931 break;
3932 }
3933 }
3934
Chris Lattner574da9b2005-01-13 20:14:25 +00003935 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3936 if (User *GEP = dyn_castGetElementPtr(Op0))
3937 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3938 return NI;
3939 if (User *GEP = dyn_castGetElementPtr(Op1))
3940 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3941 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3942 return NI;
3943
Chris Lattnerde90b762003-11-03 04:25:02 +00003944 // Test to see if the operands of the setcc are casted versions of other
3945 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00003946 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3947 Value *CastOp0 = CI->getOperand(0);
3948 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00003949 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00003950 (I.getOpcode() == Instruction::SetEQ ||
3951 I.getOpcode() == Instruction::SetNE)) {
3952 // We keep moving the cast from the left operand over to the right
3953 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00003954 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00003955
Chris Lattnerde90b762003-11-03 04:25:02 +00003956 // If operand #1 is a cast instruction, see if we can eliminate it as
3957 // well.
Chris Lattner68708052003-11-03 05:17:03 +00003958 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3959 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00003960 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00003961 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00003962
Chris Lattnerde90b762003-11-03 04:25:02 +00003963 // If Op1 is a constant, we can fold the cast into the constant.
3964 if (Op1->getType() != Op0->getType())
3965 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3966 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3967 } else {
3968 // Otherwise, cast the RHS right before the setcc
3969 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3970 InsertNewInstBefore(cast<Instruction>(Op1), I);
3971 }
3972 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3973 }
3974
Chris Lattner68708052003-11-03 05:17:03 +00003975 // Handle the special case of: setcc (cast bool to X), <cst>
3976 // This comes up when you have code like
3977 // int X = A < B;
3978 // if (X) ...
3979 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00003980 // with a constant or another cast from the same type.
3981 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3982 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3983 return R;
Chris Lattner68708052003-11-03 05:17:03 +00003984 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00003985
3986 if (I.getOpcode() == Instruction::SetNE ||
3987 I.getOpcode() == Instruction::SetEQ) {
3988 Value *A, *B;
3989 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3990 (A == Op1 || B == Op1)) {
3991 // (A^B) == A -> B == 0
3992 Value *OtherVal = A == Op1 ? B : A;
3993 return BinaryOperator::create(I.getOpcode(), OtherVal,
3994 Constant::getNullValue(A->getType()));
3995 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3996 (A == Op0 || B == Op0)) {
3997 // A == (A^B) -> B == 0
3998 Value *OtherVal = A == Op0 ? B : A;
3999 return BinaryOperator::create(I.getOpcode(), OtherVal,
4000 Constant::getNullValue(A->getType()));
4001 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4002 // (A-B) == A -> B == 0
4003 return BinaryOperator::create(I.getOpcode(), B,
4004 Constant::getNullValue(B->getType()));
4005 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4006 // A == (A-B) -> B == 0
4007 return BinaryOperator::create(I.getOpcode(), B,
4008 Constant::getNullValue(B->getType()));
4009 }
4010 }
Chris Lattner7e708292002-06-25 16:13:24 +00004011 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004012}
4013
Chris Lattner484d3cf2005-04-24 06:59:08 +00004014// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4015// We only handle extending casts so far.
4016//
4017Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4018 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4019 const Type *SrcTy = LHSCIOp->getType();
4020 const Type *DestTy = SCI.getOperand(0)->getType();
4021 Value *RHSCIOp;
4022
4023 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00004024 return 0;
4025
Chris Lattner484d3cf2005-04-24 06:59:08 +00004026 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4027 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4028 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4029
4030 // Is this a sign or zero extension?
4031 bool isSignSrc = SrcTy->isSigned();
4032 bool isSignDest = DestTy->isSigned();
4033
4034 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4035 // Not an extension from the same type?
4036 RHSCIOp = CI->getOperand(0);
4037 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4038 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4039 // Compute the constant that would happen if we truncated to SrcTy then
4040 // reextended to DestTy.
4041 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4042
4043 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4044 RHSCIOp = Res;
4045 } else {
4046 // If the value cannot be represented in the shorter type, we cannot emit
4047 // a simple comparison.
4048 if (SCI.getOpcode() == Instruction::SetEQ)
4049 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4050 if (SCI.getOpcode() == Instruction::SetNE)
4051 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4052
Chris Lattner484d3cf2005-04-24 06:59:08 +00004053 // Evaluate the comparison for LT.
4054 Value *Result;
4055 if (DestTy->isSigned()) {
4056 // We're performing a signed comparison.
4057 if (isSignSrc) {
4058 // Signed extend and signed comparison.
4059 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4060 Result = ConstantBool::False;
4061 else
4062 Result = ConstantBool::True; // X < (large) --> true
4063 } else {
4064 // Unsigned extend and signed comparison.
4065 if (cast<ConstantSInt>(CI)->getValue() < 0)
4066 Result = ConstantBool::False;
4067 else
4068 Result = ConstantBool::True;
4069 }
4070 } else {
4071 // We're performing an unsigned comparison.
4072 if (!isSignSrc) {
4073 // Unsigned extend & compare -> always true.
4074 Result = ConstantBool::True;
4075 } else {
4076 // We're performing an unsigned comp with a sign extended value.
4077 // This is true if the input is >= 0. [aka >s -1]
4078 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4079 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4080 NegOne, SCI.getName()), SCI);
4081 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00004082 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004083
Jeff Cohen00b168892005-07-27 06:12:32 +00004084 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00004085 if (SCI.getOpcode() == Instruction::SetLT) {
4086 return ReplaceInstUsesWith(SCI, Result);
4087 } else {
4088 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4089 if (Constant *CI = dyn_cast<Constant>(Result))
4090 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4091 else
4092 return BinaryOperator::createNot(Result);
4093 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004094 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00004095 } else {
4096 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00004097 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004098
Chris Lattner8d7089e2005-06-16 03:00:08 +00004099 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00004100 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4101}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004102
Chris Lattnerea340052003-03-10 19:16:08 +00004103Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00004104 assert(I.getOperand(1)->getType() == Type::UByteTy);
4105 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00004106 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004107
4108 // shl X, 0 == X and shr X, 0 == X
4109 // shl 0, X == 0 and shr 0, X == 0
4110 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00004111 Op0 == Constant::getNullValue(Op0->getType()))
4112 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004113
Chris Lattnere87597f2004-10-16 18:11:37 +00004114 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4115 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00004116 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00004117 else // undef << X -> 0 AND undef >>u X -> 0
4118 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4119 }
4120 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00004121 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00004122 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4123 else
4124 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4125 }
4126
Chris Lattnerdf17af12003-08-12 21:53:41 +00004127 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4128 if (!isLeftShift)
4129 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4130 if (CSI->isAllOnesValue())
4131 return ReplaceInstUsesWith(I, CSI);
4132
Chris Lattner2eefe512004-04-09 19:05:30 +00004133 // Try to fold constant and into select arguments.
4134 if (isa<Constant>(Op0))
4135 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004136 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004137 return R;
4138
Chris Lattner120347e2005-05-08 17:34:56 +00004139 // See if we can turn a signed shr into an unsigned shr.
4140 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00004141 if (MaskedValueIsZero(Op0,
4142 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattner120347e2005-05-08 17:34:56 +00004143 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4144 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4145 I.getName()), I);
4146 return new CastInst(V, I.getType());
4147 }
4148 }
Jeff Cohen00b168892005-07-27 06:12:32 +00004149
Chris Lattner4d5542c2006-01-06 07:12:35 +00004150 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4151 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4152 return Res;
4153 return 0;
4154}
4155
4156Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4157 ShiftInst &I) {
4158 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner830ed032006-01-06 07:22:22 +00004159 bool isSignedShift = Op0->getType()->isSigned();
4160 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004161
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004162 // See if we can simplify any instructions used by the instruction whose sole
4163 // purpose is to compute bits we don't care about.
4164 uint64_t KnownZero, KnownOne;
4165 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4166 KnownZero, KnownOne))
4167 return &I;
4168
Chris Lattner4d5542c2006-01-06 07:12:35 +00004169 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4170 // of a signed value.
4171 //
4172 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4173 if (Op1->getValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00004174 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00004175 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4176 else {
4177 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4178 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00004179 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004180 }
4181
4182 // ((X*C1) << C2) == (X * (C1 << C2))
4183 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4184 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4185 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4186 return BinaryOperator::createMul(BO->getOperand(0),
4187 ConstantExpr::getShl(BOOp, Op1));
4188
4189 // Try to fold constant and into select arguments.
4190 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4191 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4192 return R;
4193 if (isa<PHINode>(Op0))
4194 if (Instruction *NV = FoldOpIntoPhi(I))
4195 return NV;
4196
4197 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004198 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4199 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4200 Value *V1, *V2;
4201 ConstantInt *CC;
4202 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00004203 default: break;
4204 case Instruction::Add:
4205 case Instruction::And:
4206 case Instruction::Or:
4207 case Instruction::Xor:
4208 // These operators commute.
4209 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004210 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4211 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004212 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004213 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004214 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004215 Op0BO->getName());
4216 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004217 Instruction *X =
4218 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4219 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00004220 InsertNewInstBefore(X, I); // (X + (Y << C))
4221 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00004222 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00004223 return BinaryOperator::createAnd(X, C2);
4224 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004225
Chris Lattner150f12a2005-09-18 06:30:59 +00004226 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4227 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4228 match(Op0BO->getOperand(1),
4229 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004230 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004231 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004232 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004233 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004234 Op0BO->getName());
4235 InsertNewInstBefore(YS, I); // (Y << C)
4236 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00004237 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00004238 V1->getName()+".mask");
4239 InsertNewInstBefore(XM, I); // X & (CC << C)
4240
4241 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4242 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004243
Chris Lattner150f12a2005-09-18 06:30:59 +00004244 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00004245 case Instruction::Sub:
4246 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004247 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4248 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004249 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004250 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004251 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004252 Op0BO->getName());
4253 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004254 Instruction *X =
4255 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4256 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00004257 InsertNewInstBefore(X, I); // (X + (Y << C))
4258 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00004259 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00004260 return BinaryOperator::createAnd(X, C2);
4261 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004262
Chris Lattner150f12a2005-09-18 06:30:59 +00004263 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4264 match(Op0BO->getOperand(0),
4265 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004266 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004267 cast<BinaryOperator>(Op0BO->getOperand(0))
4268 ->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004269 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004270 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004271 Op0BO->getName());
4272 InsertNewInstBefore(YS, I); // (Y << C)
4273 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00004274 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00004275 V1->getName()+".mask");
4276 InsertNewInstBefore(XM, I); // X & (CC << C)
4277
4278 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4279 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004280
Chris Lattner11021cb2005-09-18 05:12:10 +00004281 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004282 }
4283
4284
4285 // If the operand is an bitwise operator with a constant RHS, and the
4286 // shift is the only use, we can pull it out of the shift.
4287 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4288 bool isValid = true; // Valid only for And, Or, Xor
4289 bool highBitSet = false; // Transform if high bit of constant set?
4290
4291 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00004292 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00004293 case Instruction::Add:
4294 isValid = isLeftShift;
4295 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00004296 case Instruction::Or:
4297 case Instruction::Xor:
4298 highBitSet = false;
4299 break;
4300 case Instruction::And:
4301 highBitSet = true;
4302 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004303 }
4304
4305 // If this is a signed shift right, and the high bit is modified
4306 // by the logical operation, do not perform the transformation.
4307 // The highBitSet boolean indicates the value of the high bit of
4308 // the constant which would cause it to be modified for this
4309 // operation.
4310 //
Chris Lattner830ed032006-01-06 07:22:22 +00004311 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004312 uint64_t Val = Op0C->getRawValue();
4313 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4314 }
4315
4316 if (isValid) {
4317 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4318
4319 Instruction *NewShift =
4320 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4321 Op0BO->getName());
4322 Op0BO->setName("");
4323 InsertNewInstBefore(NewShift, I);
4324
4325 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4326 NewRHS);
4327 }
4328 }
4329 }
4330 }
4331
Chris Lattnerad0124c2006-01-06 07:52:12 +00004332 // Find out if this is a shift of a shift by a constant.
4333 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004334 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00004335 ShiftOp = Op0SI;
4336 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4337 // If this is a noop-integer case of a shift instruction, use the shift.
4338 if (CI->getOperand(0)->getType()->isInteger() &&
4339 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4340 CI->getType()->getPrimitiveSizeInBits() &&
4341 isa<ShiftInst>(CI->getOperand(0))) {
4342 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4343 }
4344 }
4345
4346 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4347 // Find the operands and properties of the input shift. Note that the
4348 // signedness of the input shift may differ from the current shift if there
4349 // is a noop cast between the two.
4350 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4351 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattnere8d56c52006-01-07 01:32:28 +00004352 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004353
4354 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4355
4356 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4357 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4358
4359 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4360 if (isLeftShift == isShiftOfLeftShift) {
4361 // Do not fold these shifts if the first one is signed and the second one
4362 // is unsigned and this is a right shift. Further, don't do any folding
4363 // on them.
4364 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4365 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004366
Chris Lattnerad0124c2006-01-06 07:52:12 +00004367 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4368 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4369 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00004370
Chris Lattnerad0124c2006-01-06 07:52:12 +00004371 Value *Op = ShiftOp->getOperand(0);
4372 if (isShiftOfSignedShift != isSignedShift)
4373 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4374 return new ShiftInst(I.getOpcode(), Op,
4375 ConstantUInt::get(Type::UByteTy, Amt));
4376 }
4377
4378 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4379 // signed types, we can only support the (A >> c1) << c2 configuration,
4380 // because it can not turn an arbitrary bit of A into a sign bit.
4381 if (isUnsignedShift || isLeftShift) {
4382 // Calculate bitmask for what gets shifted off the edge.
4383 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4384 if (isLeftShift)
4385 C = ConstantExpr::getShl(C, ShiftAmt1C);
4386 else
Chris Lattnere8d56c52006-01-07 01:32:28 +00004387 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00004388
4389 Value *Op = ShiftOp->getOperand(0);
4390 if (isShiftOfSignedShift != isSignedShift)
4391 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4392
4393 Instruction *Mask =
4394 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4395 InsertNewInstBefore(Mask, I);
4396
4397 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00004398 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004399 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00004400 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004401 return new ShiftInst(I.getOpcode(), Mask,
4402 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004403 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4404 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4405 // Make sure to emit an unsigned shift right, not a signed one.
4406 Mask = InsertNewInstBefore(new CastInst(Mask,
4407 Mask->getType()->getUnsignedVersion(),
4408 Op->getName()), I);
4409 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnerad0124c2006-01-06 07:52:12 +00004410 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004411 InsertNewInstBefore(Mask, I);
4412 return new CastInst(Mask, I.getType());
4413 } else {
4414 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4415 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4416 }
4417 } else {
4418 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4419 Op = InsertNewInstBefore(new CastInst(Mask,
4420 I.getType()->getSignedVersion(),
4421 Mask->getName()), I);
4422 Instruction *Shift =
4423 new ShiftInst(ShiftOp->getOpcode(), Op,
4424 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4425 InsertNewInstBefore(Shift, I);
4426
4427 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4428 C = ConstantExpr::getShl(C, Op1);
4429 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4430 InsertNewInstBefore(Mask, I);
4431 return new CastInst(Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00004432 }
4433 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00004434 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00004435 // this case, C1 == C2 and C1 is 8, 16, or 32.
4436 if (ShiftAmt1 == ShiftAmt2) {
4437 const Type *SExtType = 0;
4438 switch (ShiftAmt1) {
4439 case 8 : SExtType = Type::SByteTy; break;
4440 case 16: SExtType = Type::ShortTy; break;
4441 case 32: SExtType = Type::IntTy; break;
4442 }
4443
4444 if (SExtType) {
4445 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4446 SExtType, "sext");
4447 InsertNewInstBefore(NewTrunc, I);
4448 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00004449 }
Chris Lattner11021cb2005-09-18 05:12:10 +00004450 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00004451 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00004452 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004453 return 0;
4454}
4455
Chris Lattnerbee7e762004-07-20 00:59:32 +00004456enum CastType {
4457 Noop = 0,
4458 Truncate = 1,
4459 Signext = 2,
4460 Zeroext = 3
4461};
4462
4463/// getCastType - In the future, we will split the cast instruction into these
4464/// various types. Until then, we have to do the analysis here.
4465static CastType getCastType(const Type *Src, const Type *Dest) {
4466 assert(Src->isIntegral() && Dest->isIntegral() &&
4467 "Only works on integral types!");
Chris Lattner484d3cf2005-04-24 06:59:08 +00004468 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4469 unsigned DestSize = Dest->getPrimitiveSizeInBits();
Chris Lattnerbee7e762004-07-20 00:59:32 +00004470
4471 if (SrcSize == DestSize) return Noop;
4472 if (SrcSize > DestSize) return Truncate;
4473 if (Src->isSigned()) return Signext;
4474 return Zeroext;
4475}
4476
Chris Lattner3f5b8772002-05-06 16:14:14 +00004477
Chris Lattnera1be5662002-05-02 17:06:02 +00004478// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4479// instruction.
4480//
Chris Lattnerbc528ef2006-01-19 07:40:22 +00004481static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4482 const Type *DstTy, TargetData *TD) {
Chris Lattnera1be5662002-05-02 17:06:02 +00004483
Chris Lattner8fd217c2002-08-02 20:00:25 +00004484 // It is legal to eliminate the instruction if casting A->B->A if the sizes
Misha Brukmanfd939082005-04-21 23:48:37 +00004485 // are identical and the bits don't get reinterpreted (for example
Chris Lattner5eb91942004-07-21 19:50:44 +00004486 // int->float->int would not be allowed).
Misha Brukmanf117cc92003-05-20 18:45:36 +00004487 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
Chris Lattner8fd217c2002-08-02 20:00:25 +00004488 return true;
Chris Lattnera1be5662002-05-02 17:06:02 +00004489
Chris Lattnere8a7e592004-07-21 04:27:24 +00004490 // If we are casting between pointer and integer types, treat pointers as
4491 // integers of the appropriate size for the code below.
4492 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4493 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4494 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
Chris Lattner59a20772004-07-20 05:21:00 +00004495
Chris Lattnera1be5662002-05-02 17:06:02 +00004496 // Allow free casting and conversion of sizes as long as the sign doesn't
4497 // change...
Chris Lattner0c4e8862002-09-03 01:08:28 +00004498 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
Chris Lattnerbee7e762004-07-20 00:59:32 +00004499 CastType FirstCast = getCastType(SrcTy, MidTy);
4500 CastType SecondCast = getCastType(MidTy, DstTy);
Chris Lattner8fd217c2002-08-02 20:00:25 +00004501
Chris Lattnerbee7e762004-07-20 00:59:32 +00004502 // Capture the effect of these two casts. If the result is a legal cast,
4503 // the CastType is stored here, otherwise a special code is used.
4504 static const unsigned CastResult[] = {
4505 // First cast is noop
4506 0, 1, 2, 3,
4507 // First cast is a truncate
4508 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4509 // First cast is a sign ext
Chris Lattner5eb91942004-07-21 19:50:44 +00004510 2, 5, 2, 4, // signext->zeroext never ok
Chris Lattnerbee7e762004-07-20 00:59:32 +00004511 // First cast is a zero ext
Chris Lattner5eb91942004-07-21 19:50:44 +00004512 3, 5, 3, 3,
Chris Lattnerbee7e762004-07-20 00:59:32 +00004513 };
4514
4515 unsigned Result = CastResult[FirstCast*4+SecondCast];
4516 switch (Result) {
4517 default: assert(0 && "Illegal table value!");
4518 case 0:
4519 case 1:
4520 case 2:
4521 case 3:
4522 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4523 // truncates, we could eliminate more casts.
4524 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4525 case 4:
4526 return false; // Not possible to eliminate this here.
4527 case 5:
Chris Lattner5eb91942004-07-21 19:50:44 +00004528 // Sign or zero extend followed by truncate is always ok if the result
4529 // is a truncate or noop.
4530 CastType ResultCast = getCastType(SrcTy, DstTy);
4531 if (ResultCast == Noop || ResultCast == Truncate)
4532 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00004533 // Otherwise we are still growing the value, we are only safe if the
Chris Lattner5eb91942004-07-21 19:50:44 +00004534 // result will match the sign/zeroextendness of the result.
4535 return ResultCast == FirstCast;
Chris Lattner3ecce662002-08-15 16:15:25 +00004536 }
Chris Lattner8fd217c2002-08-02 20:00:25 +00004537 }
Chris Lattnerbc528ef2006-01-19 07:40:22 +00004538
4539 // If this is a cast from 'float -> double -> integer', cast from
4540 // 'float -> integer' directly, as the value isn't changed by the
4541 // float->double conversion.
4542 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4543 DstTy->isIntegral() &&
4544 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4545 return true;
4546
Chris Lattner4132afb2006-04-02 05:43:13 +00004547 // Packed type conversions don't modify bits.
4548 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
4549 return true;
4550
Chris Lattnera1be5662002-05-02 17:06:02 +00004551 return false;
4552}
4553
Chris Lattner59a20772004-07-20 05:21:00 +00004554static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
Chris Lattner24c8e382003-07-24 17:35:25 +00004555 if (V->getType() == Ty || isa<Constant>(V)) return false;
4556 if (const CastInst *CI = dyn_cast<CastInst>(V))
Chris Lattner59a20772004-07-20 05:21:00 +00004557 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4558 TD))
Chris Lattner24c8e382003-07-24 17:35:25 +00004559 return false;
4560 return true;
4561}
4562
4563/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4564/// InsertBefore instruction. This is specialized a bit to avoid inserting
4565/// casts that are known to not do anything...
4566///
4567Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4568 Instruction *InsertBefore) {
4569 if (V->getType() == DestTy) return V;
4570 if (Constant *C = dyn_cast<Constant>(V))
4571 return ConstantExpr::getCast(C, DestTy);
4572
4573 CastInst *CI = new CastInst(V, DestTy, V->getName());
4574 InsertNewInstBefore(CI, *InsertBefore);
4575 return CI;
4576}
Chris Lattnera1be5662002-05-02 17:06:02 +00004577
Chris Lattnercfd65102005-10-29 04:36:15 +00004578/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4579/// expression. If so, decompose it, returning some value X, such that Val is
4580/// X*Scale+Offset.
4581///
4582static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4583 unsigned &Offset) {
4584 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4585 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4586 Offset = CI->getValue();
4587 Scale = 1;
4588 return ConstantUInt::get(Type::UIntTy, 0);
4589 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4590 if (I->getNumOperands() == 2) {
4591 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4592 if (I->getOpcode() == Instruction::Shl) {
4593 // This is a value scaled by '1 << the shift amt'.
4594 Scale = 1U << CUI->getValue();
4595 Offset = 0;
4596 return I->getOperand(0);
4597 } else if (I->getOpcode() == Instruction::Mul) {
4598 // This value is scaled by 'CUI'.
4599 Scale = CUI->getValue();
4600 Offset = 0;
4601 return I->getOperand(0);
4602 } else if (I->getOpcode() == Instruction::Add) {
4603 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4604 // divisible by C2.
4605 unsigned SubScale;
4606 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4607 Offset);
4608 Offset += CUI->getValue();
4609 if (SubScale > 1 && (Offset % SubScale == 0)) {
4610 Scale = SubScale;
4611 return SubVal;
4612 }
4613 }
4614 }
4615 }
4616 }
4617
4618 // Otherwise, we can't look past this.
4619 Scale = 1;
4620 Offset = 0;
4621 return Val;
4622}
4623
4624
Chris Lattnerb3f83972005-10-24 06:03:58 +00004625/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4626/// try to eliminate the cast by moving the type information into the alloc.
4627Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4628 AllocationInst &AI) {
4629 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004630 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00004631
Chris Lattnerb53c2382005-10-24 06:22:12 +00004632 // Remove any uses of AI that are dead.
4633 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4634 std::vector<Instruction*> DeadUsers;
4635 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4636 Instruction *User = cast<Instruction>(*UI++);
4637 if (isInstructionTriviallyDead(User)) {
4638 while (UI != E && *UI == User)
4639 ++UI; // If this instruction uses AI more than once, don't break UI.
4640
4641 // Add operands to the worklist.
4642 AddUsesToWorkList(*User);
4643 ++NumDeadInst;
4644 DEBUG(std::cerr << "IC: DCE: " << *User);
4645
4646 User->eraseFromParent();
4647 removeFromWorkList(User);
4648 }
4649 }
4650
Chris Lattnerb3f83972005-10-24 06:03:58 +00004651 // Get the type really allocated and the type casted to.
4652 const Type *AllocElTy = AI.getAllocatedType();
4653 const Type *CastElTy = PTy->getElementType();
4654 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004655
4656 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4657 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4658 if (CastElTyAlign < AllocElTyAlign) return 0;
4659
Chris Lattner39387a52005-10-24 06:35:18 +00004660 // If the allocation has multiple uses, only promote it if we are strictly
4661 // increasing the alignment of the resultant allocation. If we keep it the
4662 // same, we open the door to infinite loops of various kinds.
4663 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4664
Chris Lattnerb3f83972005-10-24 06:03:58 +00004665 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4666 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004667 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004668
Chris Lattner455fcc82005-10-29 03:19:53 +00004669 // See if we can satisfy the modulus by pulling a scale out of the array
4670 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00004671 unsigned ArraySizeScale, ArrayOffset;
4672 Value *NumElements = // See if the array size is a decomposable linear expr.
4673 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4674
Chris Lattner455fcc82005-10-29 03:19:53 +00004675 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4676 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00004677 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4678 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00004679
Chris Lattner455fcc82005-10-29 03:19:53 +00004680 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4681 Value *Amt = 0;
4682 if (Scale == 1) {
4683 Amt = NumElements;
4684 } else {
4685 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4686 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4687 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4688 else if (Scale != 1) {
4689 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4690 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00004691 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004692 }
4693
Chris Lattnercfd65102005-10-29 04:36:15 +00004694 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4695 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4696 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4697 Amt = InsertNewInstBefore(Tmp, AI);
4698 }
4699
Chris Lattnerb3f83972005-10-24 06:03:58 +00004700 std::string Name = AI.getName(); AI.setName("");
4701 AllocationInst *New;
4702 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00004703 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004704 else
Nate Begeman14b05292005-11-05 09:21:28 +00004705 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004706 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00004707
4708 // If the allocation has multiple uses, insert a cast and change all things
4709 // that used it to use the new cast. This will also hack on CI, but it will
4710 // die soon.
4711 if (!AI.hasOneUse()) {
4712 AddUsesToWorkList(AI);
4713 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4714 InsertNewInstBefore(NewCast, AI);
4715 AI.replaceAllUsesWith(NewCast);
4716 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00004717 return ReplaceInstUsesWith(CI, New);
4718}
4719
4720
Chris Lattnera1be5662002-05-02 17:06:02 +00004721// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004722//
Chris Lattner7e708292002-06-25 16:13:24 +00004723Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00004724 Value *Src = CI.getOperand(0);
4725
Chris Lattnera1be5662002-05-02 17:06:02 +00004726 // If the user is casting a value to the same type, eliminate this cast
4727 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00004728 if (CI.getType() == Src->getType())
4729 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00004730
Chris Lattnere87597f2004-10-16 18:11:37 +00004731 if (isa<UndefValue>(Src)) // cast undef -> undef
4732 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4733
Chris Lattnera1be5662002-05-02 17:06:02 +00004734 // If casting the result of another cast instruction, try to eliminate this
4735 // one!
4736 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00004737 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4738 Value *A = CSrc->getOperand(0);
4739 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4740 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00004741 // This instruction now refers directly to the cast's src operand. This
4742 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00004743 CI.setOperand(0, CSrc->getOperand(0));
4744 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00004745 }
4746
Chris Lattner8fd217c2002-08-02 20:00:25 +00004747 // If this is an A->B->A cast, and we are dealing with integral types, try
4748 // to convert this into a logical 'and' instruction.
4749 //
Misha Brukmanfd939082005-04-21 23:48:37 +00004750 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00004751 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00004752 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00004753 CSrc->getType()->getPrimitiveSizeInBits() <
4754 CI.getType()->getPrimitiveSizeInBits()&&
4755 A->getType()->getPrimitiveSizeInBits() ==
4756 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00004757 assert(CSrc->getType() != Type::ULongTy &&
4758 "Cannot have type bigger than ulong!");
Chris Lattner1a074fc2006-02-07 07:00:41 +00004759 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner6e7ba452005-01-01 16:22:27 +00004760 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4761 AndValue);
4762 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4763 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4764 if (And->getType() != CI.getType()) {
4765 And->setName(CSrc->getName()+".mask");
4766 InsertNewInstBefore(And, CI);
4767 And = new CastInst(And, CI.getType());
4768 }
4769 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00004770 }
4771 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00004772
Chris Lattnera710ddc2004-05-25 04:29:21 +00004773 // If this is a cast to bool, turn it into the appropriate setne instruction.
4774 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00004775 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00004776 Constant::getNullValue(CI.getOperand(0)->getType()));
4777
Chris Lattner6dce1a72006-02-07 06:56:34 +00004778 // See if we can simplify any instructions used by the LHS whose sole
4779 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00004780 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4781 uint64_t KnownZero, KnownOne;
4782 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4783 KnownZero, KnownOne))
4784 return &CI;
4785 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00004786
Chris Lattner797249b2003-06-21 23:12:02 +00004787 // If casting the result of a getelementptr instruction with no offset, turn
4788 // this into a cast of the original pointer!
4789 //
Chris Lattner79d35b32003-06-23 21:59:52 +00004790 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00004791 bool AllZeroOperands = true;
4792 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4793 if (!isa<Constant>(GEP->getOperand(i)) ||
4794 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4795 AllZeroOperands = false;
4796 break;
4797 }
4798 if (AllZeroOperands) {
4799 CI.setOperand(0, GEP->getOperand(0));
4800 return &CI;
4801 }
4802 }
4803
Chris Lattnerbc61e662003-11-02 05:57:39 +00004804 // If we are casting a malloc or alloca to a pointer to a type of the same
4805 // size, rewrite the allocation instruction to allocate the "right" type.
4806 //
4807 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00004808 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4809 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00004810
Chris Lattner6e7ba452005-01-01 16:22:27 +00004811 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4812 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4813 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00004814 if (isa<PHINode>(Src))
4815 if (Instruction *NV = FoldOpIntoPhi(CI))
4816 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00004817
4818 // If the source and destination are pointers, and this cast is equivalent to
4819 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
4820 // This can enhance SROA and other transforms that want type-safe pointers.
4821 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
4822 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
4823 const Type *DstTy = DstPTy->getElementType();
4824 const Type *SrcTy = SrcPTy->getElementType();
4825
4826 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
4827 unsigned NumZeros = 0;
4828 while (SrcTy != DstTy &&
4829 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
4830 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
4831 ++NumZeros;
4832 }
Chris Lattner4e998b22004-09-29 05:07:12 +00004833
Chris Lattner9fb92132006-04-12 18:09:35 +00004834 // If we found a path from the src to dest, create the getelementptr now.
4835 if (SrcTy == DstTy) {
4836 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
4837 return new GetElementPtrInst(Src, Idxs);
4838 }
4839 }
4840
Chris Lattner24c8e382003-07-24 17:35:25 +00004841 // If the source value is an instruction with only this use, we can attempt to
4842 // propagate the cast into the instruction. Also, only handle integral types
4843 // for now.
4844 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00004845 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00004846 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4847 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004848 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4849 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00004850
4851 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4852 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4853
4854 switch (SrcI->getOpcode()) {
4855 case Instruction::Add:
4856 case Instruction::Mul:
4857 case Instruction::And:
4858 case Instruction::Or:
4859 case Instruction::Xor:
4860 // If we are discarding information, or just changing the sign, rewrite.
4861 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4862 // Don't insert two casts if they cannot be eliminated. We allow two
4863 // casts to be inserted if the sizes are the same. This could only be
4864 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00004865 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4866 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00004867 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4868 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4869 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4870 ->getOpcode(), Op0c, Op1c);
4871 }
4872 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00004873
4874 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4875 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4876 Op1 == ConstantBool::True &&
4877 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4878 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4879 return BinaryOperator::createXor(New,
4880 ConstantInt::get(CI.getType(), 1));
4881 }
Chris Lattner24c8e382003-07-24 17:35:25 +00004882 break;
4883 case Instruction::Shl:
4884 // Allow changing the sign of the source operand. Do not allow changing
4885 // the size of the shift, UNLESS the shift amount is a constant. We
4886 // mush not change variable sized shifts to a smaller size, because it
4887 // is undefined to shift more bits out than exist in the value.
4888 if (DestBitSize == SrcBitSize ||
4889 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4890 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4891 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4892 }
4893 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00004894 case Instruction::Shr:
4895 // If this is a signed shr, and if all bits shifted in are about to be
4896 // truncated off, turn it into an unsigned shr to allow greater
4897 // simplifications.
4898 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4899 isa<ConstantInt>(Op1)) {
4900 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4901 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4902 // Convert to unsigned.
4903 Value *N1 = InsertOperandCastBefore(Op0,
4904 Op0->getType()->getUnsignedVersion(), &CI);
4905 // Insert the new shift, which is now unsigned.
4906 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4907 Op1, Src->getName()), CI);
4908 return new CastInst(N1, CI.getType());
4909 }
4910 }
4911 break;
4912
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004913 case Instruction::SetEQ:
Chris Lattner693787a2005-05-04 19:10:26 +00004914 case Instruction::SetNE:
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004915 // We if we are just checking for a seteq of a single bit and casting it
4916 // to an integer. If so, shift the bit to the appropriate place then
4917 // cast to integer to avoid the comparison.
Chris Lattner693787a2005-05-04 19:10:26 +00004918 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004919 uint64_t Op1CV = Op1C->getZExtValue();
4920 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
4921 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4922 // cast (X == 1) to int --> X iff X has only the low bit set.
4923 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
4924 // cast (X != 0) to int --> X iff X has only the low bit set.
4925 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
4926 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
4927 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4928 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4929 // If Op1C some other power of two, convert:
4930 uint64_t KnownZero, KnownOne;
4931 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4932 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4933
4934 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4935 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4936 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4937 // (X&4) == 2 --> false
4938 // (X&4) != 2 --> true
Chris Lattner06e1e252006-02-28 19:47:20 +00004939 Constant *Res = ConstantBool::get(isSetNE);
4940 Res = ConstantExpr::getCast(Res, CI.getType());
4941 return ReplaceInstUsesWith(CI, Res);
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004942 }
4943
4944 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4945 Value *In = Op0;
4946 if (ShiftAmt) {
Chris Lattnerd1523802005-05-06 01:53:19 +00004947 // Perform an unsigned shr by shiftamt. Convert input to
4948 // unsigned if it is signed.
Chris Lattnerd1523802005-05-06 01:53:19 +00004949 if (In->getType()->isSigned())
4950 In = InsertNewInstBefore(new CastInst(In,
4951 In->getType()->getUnsignedVersion(), In->getName()),CI);
4952 // Insert the shift to put the result in the low bit.
4953 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004954 ConstantInt::get(Type::UByteTy, ShiftAmt),
4955 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00004956 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004957
4958 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
4959 Constant *One = ConstantInt::get(In->getType(), 1);
4960 In = BinaryOperator::createXor(In, One, "tmp");
4961 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00004962 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004963
4964 if (CI.getType() == In->getType())
4965 return ReplaceInstUsesWith(CI, In);
4966 else
4967 return new CastInst(In, CI.getType());
Chris Lattnerd1523802005-05-06 01:53:19 +00004968 }
Chris Lattner693787a2005-05-04 19:10:26 +00004969 }
4970 }
4971 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00004972 }
4973 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004974
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004975 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00004976}
4977
Chris Lattnere576b912004-04-09 23:46:01 +00004978/// GetSelectFoldableOperands - We want to turn code that looks like this:
4979/// %C = or %A, %B
4980/// %D = select %cond, %C, %A
4981/// into:
4982/// %C = select %cond, %B, 0
4983/// %D = or %A, %C
4984///
4985/// Assuming that the specified instruction is an operand to the select, return
4986/// a bitmask indicating which operands of this instruction are foldable if they
4987/// equal the other incoming value of the select.
4988///
4989static unsigned GetSelectFoldableOperands(Instruction *I) {
4990 switch (I->getOpcode()) {
4991 case Instruction::Add:
4992 case Instruction::Mul:
4993 case Instruction::And:
4994 case Instruction::Or:
4995 case Instruction::Xor:
4996 return 3; // Can fold through either operand.
4997 case Instruction::Sub: // Can only fold on the amount subtracted.
4998 case Instruction::Shl: // Can only fold on the shift amount.
4999 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00005000 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00005001 default:
5002 return 0; // Cannot fold
5003 }
5004}
5005
5006/// GetSelectFoldableConstant - For the same transformation as the previous
5007/// function, return the identity constant that goes into the select.
5008static Constant *GetSelectFoldableConstant(Instruction *I) {
5009 switch (I->getOpcode()) {
5010 default: assert(0 && "This cannot happen!"); abort();
5011 case Instruction::Add:
5012 case Instruction::Sub:
5013 case Instruction::Or:
5014 case Instruction::Xor:
5015 return Constant::getNullValue(I->getType());
5016 case Instruction::Shl:
5017 case Instruction::Shr:
5018 return Constant::getNullValue(Type::UByteTy);
5019 case Instruction::And:
5020 return ConstantInt::getAllOnesValue(I->getType());
5021 case Instruction::Mul:
5022 return ConstantInt::get(I->getType(), 1);
5023 }
5024}
5025
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005026/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5027/// have the same opcode and only one use each. Try to simplify this.
5028Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5029 Instruction *FI) {
5030 if (TI->getNumOperands() == 1) {
5031 // If this is a non-volatile load or a cast from the same type,
5032 // merge.
5033 if (TI->getOpcode() == Instruction::Cast) {
5034 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5035 return 0;
5036 } else {
5037 return 0; // unknown unary op.
5038 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005039
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005040 // Fold this by inserting a select from the input values.
5041 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5042 FI->getOperand(0), SI.getName()+".v");
5043 InsertNewInstBefore(NewSI, SI);
5044 return new CastInst(NewSI, TI->getType());
5045 }
5046
5047 // Only handle binary operators here.
5048 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5049 return 0;
5050
5051 // Figure out if the operations have any operands in common.
5052 Value *MatchOp, *OtherOpT, *OtherOpF;
5053 bool MatchIsOpZero;
5054 if (TI->getOperand(0) == FI->getOperand(0)) {
5055 MatchOp = TI->getOperand(0);
5056 OtherOpT = TI->getOperand(1);
5057 OtherOpF = FI->getOperand(1);
5058 MatchIsOpZero = true;
5059 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5060 MatchOp = TI->getOperand(1);
5061 OtherOpT = TI->getOperand(0);
5062 OtherOpF = FI->getOperand(0);
5063 MatchIsOpZero = false;
5064 } else if (!TI->isCommutative()) {
5065 return 0;
5066 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5067 MatchOp = TI->getOperand(0);
5068 OtherOpT = TI->getOperand(1);
5069 OtherOpF = FI->getOperand(0);
5070 MatchIsOpZero = true;
5071 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5072 MatchOp = TI->getOperand(1);
5073 OtherOpT = TI->getOperand(0);
5074 OtherOpF = FI->getOperand(1);
5075 MatchIsOpZero = true;
5076 } else {
5077 return 0;
5078 }
5079
5080 // If we reach here, they do have operations in common.
5081 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5082 OtherOpF, SI.getName()+".v");
5083 InsertNewInstBefore(NewSI, SI);
5084
5085 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5086 if (MatchIsOpZero)
5087 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5088 else
5089 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5090 } else {
5091 if (MatchIsOpZero)
5092 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5093 else
5094 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5095 }
5096}
5097
Chris Lattner3d69f462004-03-12 05:52:32 +00005098Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005099 Value *CondVal = SI.getCondition();
5100 Value *TrueVal = SI.getTrueValue();
5101 Value *FalseVal = SI.getFalseValue();
5102
5103 // select true, X, Y -> X
5104 // select false, X, Y -> Y
5105 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00005106 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005107 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00005108 else {
5109 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005110 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00005111 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005112
5113 // select C, X, X -> X
5114 if (TrueVal == FalseVal)
5115 return ReplaceInstUsesWith(SI, TrueVal);
5116
Chris Lattnere87597f2004-10-16 18:11:37 +00005117 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5118 return ReplaceInstUsesWith(SI, FalseVal);
5119 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5120 return ReplaceInstUsesWith(SI, TrueVal);
5121 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5122 if (isa<Constant>(TrueVal))
5123 return ReplaceInstUsesWith(SI, TrueVal);
5124 else
5125 return ReplaceInstUsesWith(SI, FalseVal);
5126 }
5127
Chris Lattner0c199a72004-04-08 04:43:23 +00005128 if (SI.getType() == Type::BoolTy)
5129 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5130 if (C == ConstantBool::True) {
5131 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005132 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005133 } else {
5134 // Change: A = select B, false, C --> A = and !B, C
5135 Value *NotCond =
5136 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5137 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005138 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005139 }
5140 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5141 if (C == ConstantBool::False) {
5142 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005143 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005144 } else {
5145 // Change: A = select B, C, true --> A = or !B, C
5146 Value *NotCond =
5147 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5148 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005149 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005150 }
5151 }
5152
Chris Lattner2eefe512004-04-09 19:05:30 +00005153 // Selecting between two integer constants?
5154 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5155 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5156 // select C, 1, 0 -> cast C to int
5157 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5158 return new CastInst(CondVal, SI.getType());
5159 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5160 // select C, 0, 1 -> cast !C to int
5161 Value *NotCond =
5162 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00005163 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00005164 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00005165 }
Chris Lattner457dd822004-06-09 07:59:58 +00005166
5167 // If one of the constants is zero (we know they can't both be) and we
5168 // have a setcc instruction with zero, and we have an 'and' with the
5169 // non-constant value, eliminate this whole mess. This corresponds to
5170 // cases like this: ((X & 27) ? 27 : 0)
5171 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5172 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5173 if ((IC->getOpcode() == Instruction::SetEQ ||
5174 IC->getOpcode() == Instruction::SetNE) &&
5175 isa<ConstantInt>(IC->getOperand(1)) &&
5176 cast<Constant>(IC->getOperand(1))->isNullValue())
5177 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5178 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005179 isa<ConstantInt>(ICA->getOperand(1)) &&
5180 (ICA->getOperand(1) == TrueValC ||
5181 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00005182 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5183 // Okay, now we know that everything is set up, we just don't
5184 // know whether we have a setne or seteq and whether the true or
5185 // false val is the zero.
5186 bool ShouldNotVal = !TrueValC->isNullValue();
5187 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5188 Value *V = ICA;
5189 if (ShouldNotVal)
5190 V = InsertNewInstBefore(BinaryOperator::create(
5191 Instruction::Xor, V, ICA->getOperand(1)), SI);
5192 return ReplaceInstUsesWith(SI, V);
5193 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005194 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00005195
5196 // See if we are selecting two values based on a comparison of the two values.
5197 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5198 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5199 // Transform (X == Y) ? X : Y -> Y
5200 if (SCI->getOpcode() == Instruction::SetEQ)
5201 return ReplaceInstUsesWith(SI, FalseVal);
5202 // Transform (X != Y) ? X : Y -> X
5203 if (SCI->getOpcode() == Instruction::SetNE)
5204 return ReplaceInstUsesWith(SI, TrueVal);
5205 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5206
5207 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5208 // Transform (X == Y) ? Y : X -> X
5209 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00005210 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00005211 // Transform (X != Y) ? Y : X -> Y
5212 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00005213 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00005214 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5215 }
5216 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005217
Chris Lattner87875da2005-01-13 22:52:24 +00005218 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5219 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5220 if (TI->hasOneUse() && FI->hasOneUse()) {
5221 bool isInverse = false;
5222 Instruction *AddOp = 0, *SubOp = 0;
5223
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005224 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5225 if (TI->getOpcode() == FI->getOpcode())
5226 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5227 return IV;
5228
5229 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5230 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00005231 if (TI->getOpcode() == Instruction::Sub &&
5232 FI->getOpcode() == Instruction::Add) {
5233 AddOp = FI; SubOp = TI;
5234 } else if (FI->getOpcode() == Instruction::Sub &&
5235 TI->getOpcode() == Instruction::Add) {
5236 AddOp = TI; SubOp = FI;
5237 }
5238
5239 if (AddOp) {
5240 Value *OtherAddOp = 0;
5241 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5242 OtherAddOp = AddOp->getOperand(1);
5243 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5244 OtherAddOp = AddOp->getOperand(0);
5245 }
5246
5247 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00005248 // So at this point we know we have (Y -> OtherAddOp):
5249 // select C, (add X, Y), (sub X, Z)
5250 Value *NegVal; // Compute -Z
5251 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5252 NegVal = ConstantExpr::getNeg(C);
5253 } else {
5254 NegVal = InsertNewInstBefore(
5255 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00005256 }
Chris Lattner97f37a42006-02-24 18:05:58 +00005257
5258 Value *NewTrueOp = OtherAddOp;
5259 Value *NewFalseOp = NegVal;
5260 if (AddOp != TI)
5261 std::swap(NewTrueOp, NewFalseOp);
5262 Instruction *NewSel =
5263 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5264
5265 NewSel = InsertNewInstBefore(NewSel, SI);
5266 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00005267 }
5268 }
5269 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005270
Chris Lattnere576b912004-04-09 23:46:01 +00005271 // See if we can fold the select into one of our operands.
5272 if (SI.getType()->isInteger()) {
5273 // See the comment above GetSelectFoldableOperands for a description of the
5274 // transformation we are doing here.
5275 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5276 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5277 !isa<Constant>(FalseVal))
5278 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5279 unsigned OpToFold = 0;
5280 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5281 OpToFold = 1;
5282 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5283 OpToFold = 2;
5284 }
5285
5286 if (OpToFold) {
5287 Constant *C = GetSelectFoldableConstant(TVI);
5288 std::string Name = TVI->getName(); TVI->setName("");
5289 Instruction *NewSel =
5290 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5291 Name);
5292 InsertNewInstBefore(NewSel, SI);
5293 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5294 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5295 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5296 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5297 else {
5298 assert(0 && "Unknown instruction!!");
5299 }
5300 }
5301 }
Chris Lattnera96879a2004-09-29 17:40:11 +00005302
Chris Lattnere576b912004-04-09 23:46:01 +00005303 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5304 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5305 !isa<Constant>(TrueVal))
5306 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5307 unsigned OpToFold = 0;
5308 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5309 OpToFold = 1;
5310 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5311 OpToFold = 2;
5312 }
5313
5314 if (OpToFold) {
5315 Constant *C = GetSelectFoldableConstant(FVI);
5316 std::string Name = FVI->getName(); FVI->setName("");
5317 Instruction *NewSel =
5318 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5319 Name);
5320 InsertNewInstBefore(NewSel, SI);
5321 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5322 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5323 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5324 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5325 else {
5326 assert(0 && "Unknown instruction!!");
5327 }
5328 }
5329 }
5330 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00005331
5332 if (BinaryOperator::isNot(CondVal)) {
5333 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5334 SI.setOperand(1, FalseVal);
5335 SI.setOperand(2, TrueVal);
5336 return &SI;
5337 }
5338
Chris Lattner3d69f462004-03-12 05:52:32 +00005339 return 0;
5340}
5341
Chris Lattner95a959d2006-03-06 20:18:44 +00005342/// GetKnownAlignment - If the specified pointer has an alignment that we can
5343/// determine, return it, otherwise return 0.
5344static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5345 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5346 unsigned Align = GV->getAlignment();
5347 if (Align == 0 && TD)
5348 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5349 return Align;
5350 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5351 unsigned Align = AI->getAlignment();
5352 if (Align == 0 && TD) {
5353 if (isa<AllocaInst>(AI))
5354 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5355 else if (isa<MallocInst>(AI)) {
5356 // Malloc returns maximally aligned memory.
5357 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5358 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5359 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5360 }
5361 }
5362 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00005363 } else if (isa<CastInst>(V) ||
5364 (isa<ConstantExpr>(V) &&
5365 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5366 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00005367 if (isa<PointerType>(CI->getOperand(0)->getType()))
5368 return GetKnownAlignment(CI->getOperand(0), TD);
5369 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00005370 } else if (isa<GetElementPtrInst>(V) ||
5371 (isa<ConstantExpr>(V) &&
5372 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5373 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00005374 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5375 if (BaseAlignment == 0) return 0;
5376
5377 // If all indexes are zero, it is just the alignment of the base pointer.
5378 bool AllZeroOperands = true;
5379 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5380 if (!isa<Constant>(GEPI->getOperand(i)) ||
5381 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5382 AllZeroOperands = false;
5383 break;
5384 }
5385 if (AllZeroOperands)
5386 return BaseAlignment;
5387
5388 // Otherwise, if the base alignment is >= the alignment we expect for the
5389 // base pointer type, then we know that the resultant pointer is aligned at
5390 // least as much as its type requires.
5391 if (!TD) return 0;
5392
5393 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5394 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00005395 <= BaseAlignment) {
5396 const Type *GEPTy = GEPI->getType();
5397 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5398 }
Chris Lattner95a959d2006-03-06 20:18:44 +00005399 return 0;
5400 }
5401 return 0;
5402}
5403
Chris Lattner3d69f462004-03-12 05:52:32 +00005404
Chris Lattner8b0ea312006-01-13 20:11:04 +00005405/// visitCallInst - CallInst simplification. This mostly only handles folding
5406/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5407/// the heavy lifting.
5408///
Chris Lattner9fe38862003-06-19 17:00:31 +00005409Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00005410 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5411 if (!II) return visitCallSite(&CI);
5412
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005413 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5414 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00005415 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005416 bool Changed = false;
5417
5418 // memmove/cpy/set of zero bytes is a noop.
5419 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5420 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5421
Chris Lattner35b9e482004-10-12 04:52:52 +00005422 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5423 if (CI->getRawValue() == 1) {
5424 // Replace the instruction with just byte operations. We would
5425 // transform other cases to loads/stores, but we don't know if
5426 // alignment is sufficient.
5427 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005428 }
5429
Chris Lattner35b9e482004-10-12 04:52:52 +00005430 // If we have a memmove and the source operation is a constant global,
5431 // then the source and dest pointers can't alias, so we can change this
5432 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00005433 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005434 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5435 if (GVSrc->isConstant()) {
5436 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00005437 const char *Name;
5438 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5439 Type::UIntTy)
5440 Name = "llvm.memcpy.i32";
5441 else
5442 Name = "llvm.memcpy.i64";
5443 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00005444 CI.getCalledFunction()->getFunctionType());
5445 CI.setOperand(0, MemCpy);
5446 Changed = true;
5447 }
Chris Lattner95a959d2006-03-06 20:18:44 +00005448 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005449
Chris Lattner95a959d2006-03-06 20:18:44 +00005450 // If we can determine a pointer alignment that is bigger than currently
5451 // set, update the alignment.
5452 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5453 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5454 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5455 unsigned Align = std::min(Alignment1, Alignment2);
5456 if (MI->getAlignment()->getRawValue() < Align) {
5457 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5458 Changed = true;
5459 }
5460 } else if (isa<MemSetInst>(MI)) {
5461 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5462 if (MI->getAlignment()->getRawValue() < Alignment) {
5463 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5464 Changed = true;
5465 }
5466 }
5467
Chris Lattner8b0ea312006-01-13 20:11:04 +00005468 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00005469 } else {
5470 switch (II->getIntrinsicID()) {
5471 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00005472 case Intrinsic::ppc_altivec_lvx:
5473 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00005474 case Intrinsic::x86_sse_loadu_ps:
5475 case Intrinsic::x86_sse2_loadu_pd:
5476 case Intrinsic::x86_sse2_loadu_dq:
5477 // Turn PPC lvx -> load if the pointer is known aligned.
5478 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00005479 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00005480 Value *Ptr = InsertCastBefore(II->getOperand(1),
5481 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00005482 return new LoadInst(Ptr);
5483 }
5484 break;
5485 case Intrinsic::ppc_altivec_stvx:
5486 case Intrinsic::ppc_altivec_stvxl:
5487 // Turn stvx -> store if the pointer is known aligned.
5488 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00005489 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5490 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00005491 return new StoreInst(II->getOperand(1), Ptr);
5492 }
5493 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00005494 case Intrinsic::x86_sse_storeu_ps:
5495 case Intrinsic::x86_sse2_storeu_pd:
5496 case Intrinsic::x86_sse2_storeu_dq:
5497 case Intrinsic::x86_sse2_storel_dq:
5498 // Turn X86 storeu -> store if the pointer is known aligned.
5499 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5500 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5501 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5502 return new StoreInst(II->getOperand(2), Ptr);
5503 }
5504 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00005505 case Intrinsic::ppc_altivec_vperm:
5506 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5507 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5508 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5509
5510 // Check that all of the elements are integer constants or undefs.
5511 bool AllEltsOk = true;
5512 for (unsigned i = 0; i != 16; ++i) {
5513 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5514 !isa<UndefValue>(Mask->getOperand(i))) {
5515 AllEltsOk = false;
5516 break;
5517 }
5518 }
5519
5520 if (AllEltsOk) {
5521 // Cast the input vectors to byte vectors.
5522 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5523 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5524 Value *Result = UndefValue::get(Op0->getType());
5525
5526 // Only extract each element once.
5527 Value *ExtractedElts[32];
5528 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5529
5530 for (unsigned i = 0; i != 16; ++i) {
5531 if (isa<UndefValue>(Mask->getOperand(i)))
5532 continue;
5533 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5534 Idx &= 31; // Match the hardware behavior.
5535
5536 if (ExtractedElts[Idx] == 0) {
5537 Instruction *Elt =
5538 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5539 ConstantUInt::get(Type::UIntTy, Idx&15),
5540 "tmp");
5541 InsertNewInstBefore(Elt, CI);
5542 ExtractedElts[Idx] = Elt;
5543 }
5544
5545 // Insert this value into the result vector.
5546 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5547 ConstantUInt::get(Type::UIntTy, i),
5548 "tmp");
5549 InsertNewInstBefore(cast<Instruction>(Result), CI);
5550 }
5551 return new CastInst(Result, CI.getType());
5552 }
5553 }
5554 break;
5555
Chris Lattnera728ddc2006-01-13 21:28:09 +00005556 case Intrinsic::stackrestore: {
5557 // If the save is right next to the restore, remove the restore. This can
5558 // happen when variable allocas are DCE'd.
5559 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5560 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5561 BasicBlock::iterator BI = SS;
5562 if (&*++BI == II)
5563 return EraseInstFromFunction(CI);
5564 }
5565 }
5566
5567 // If the stack restore is in a return/unwind block and if there are no
5568 // allocas or calls between the restore and the return, nuke the restore.
5569 TerminatorInst *TI = II->getParent()->getTerminator();
5570 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5571 BasicBlock::iterator BI = II;
5572 bool CannotRemove = false;
5573 for (++BI; &*BI != TI; ++BI) {
5574 if (isa<AllocaInst>(BI) ||
5575 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5576 CannotRemove = true;
5577 break;
5578 }
5579 }
5580 if (!CannotRemove)
5581 return EraseInstFromFunction(CI);
5582 }
5583 break;
5584 }
5585 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005586 }
5587
Chris Lattner8b0ea312006-01-13 20:11:04 +00005588 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005589}
5590
5591// InvokeInst simplification
5592//
5593Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00005594 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005595}
5596
Chris Lattnera44d8a22003-10-07 22:32:43 +00005597// visitCallSite - Improvements for call and invoke instructions.
5598//
5599Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00005600 bool Changed = false;
5601
5602 // If the callee is a constexpr cast of a function, attempt to move the cast
5603 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00005604 if (transformConstExprCastCall(CS)) return 0;
5605
Chris Lattner6c266db2003-10-07 22:54:13 +00005606 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00005607
Chris Lattner08b22ec2005-05-13 07:09:09 +00005608 if (Function *CalleeF = dyn_cast<Function>(Callee))
5609 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5610 Instruction *OldCall = CS.getInstruction();
5611 // If the call and callee calling conventions don't match, this call must
5612 // be unreachable, as the call is undefined.
5613 new StoreInst(ConstantBool::True,
5614 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5615 if (!OldCall->use_empty())
5616 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5617 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5618 return EraseInstFromFunction(*OldCall);
5619 return 0;
5620 }
5621
Chris Lattner17be6352004-10-18 02:59:09 +00005622 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5623 // This instruction is not reachable, just remove it. We insert a store to
5624 // undef so that we know that this code is not reachable, despite the fact
5625 // that we can't modify the CFG here.
5626 new StoreInst(ConstantBool::True,
5627 UndefValue::get(PointerType::get(Type::BoolTy)),
5628 CS.getInstruction());
5629
5630 if (!CS.getInstruction()->use_empty())
5631 CS.getInstruction()->
5632 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5633
5634 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5635 // Don't break the CFG, insert a dummy cond branch.
5636 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5637 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00005638 }
Chris Lattner17be6352004-10-18 02:59:09 +00005639 return EraseInstFromFunction(*CS.getInstruction());
5640 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005641
Chris Lattner6c266db2003-10-07 22:54:13 +00005642 const PointerType *PTy = cast<PointerType>(Callee->getType());
5643 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5644 if (FTy->isVarArg()) {
5645 // See if we can optimize any arguments passed through the varargs area of
5646 // the call.
5647 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5648 E = CS.arg_end(); I != E; ++I)
5649 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5650 // If this cast does not effect the value passed through the varargs
5651 // area, we can eliminate the use of the cast.
5652 Value *Op = CI->getOperand(0);
5653 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5654 *I = Op;
5655 Changed = true;
5656 }
5657 }
5658 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005659
Chris Lattner6c266db2003-10-07 22:54:13 +00005660 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00005661}
5662
Chris Lattner9fe38862003-06-19 17:00:31 +00005663// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5664// attempt to move the cast to the arguments of the call/invoke.
5665//
5666bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5667 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5668 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00005669 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00005670 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00005671 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00005672 Instruction *Caller = CS.getInstruction();
5673
5674 // Okay, this is a cast from a function to a different type. Unless doing so
5675 // would cause a type conversion of one of our arguments, change this call to
5676 // be a direct call with arguments casted to the appropriate types.
5677 //
5678 const FunctionType *FT = Callee->getFunctionType();
5679 const Type *OldRetTy = Caller->getType();
5680
Chris Lattnerf78616b2004-01-14 06:06:08 +00005681 // Check to see if we are changing the return type...
5682 if (OldRetTy != FT->getReturnType()) {
5683 if (Callee->isExternal() &&
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00005684 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
5685 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharth7a31b972006-04-20 15:41:37 +00005686 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00005687 && !Caller->use_empty())
Chris Lattnerf78616b2004-01-14 06:06:08 +00005688 return false; // Cannot transform this return value...
5689
5690 // If the callsite is an invoke instruction, and the return value is used by
5691 // a PHI node in a successor, we cannot change the return type of the call
5692 // because there is no place to put the cast instruction (without breaking
5693 // the critical edge). Bail out in this case.
5694 if (!Caller->use_empty())
5695 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5696 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5697 UI != E; ++UI)
5698 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5699 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005700 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00005701 return false;
5702 }
Chris Lattner9fe38862003-06-19 17:00:31 +00005703
5704 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5705 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005706
Chris Lattner9fe38862003-06-19 17:00:31 +00005707 CallSite::arg_iterator AI = CS.arg_begin();
5708 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5709 const Type *ParamTy = FT->getParamType(i);
5710 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanfd939082005-04-21 23:48:37 +00005711 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00005712 }
5713
5714 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5715 Callee->isExternal())
5716 return false; // Do not delete arguments unless we have a function body...
5717
5718 // Okay, we decided that this is a safe thing to do: go ahead and start
5719 // inserting cast instructions as necessary...
5720 std::vector<Value*> Args;
5721 Args.reserve(NumActualArgs);
5722
5723 AI = CS.arg_begin();
5724 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5725 const Type *ParamTy = FT->getParamType(i);
5726 if ((*AI)->getType() == ParamTy) {
5727 Args.push_back(*AI);
5728 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00005729 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5730 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00005731 }
5732 }
5733
5734 // If the function takes more arguments than the call was taking, add them
5735 // now...
5736 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5737 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5738
5739 // If we are removing arguments to the function, emit an obnoxious warning...
5740 if (FT->getNumParams() < NumActualArgs)
5741 if (!FT->isVarArg()) {
5742 std::cerr << "WARNING: While resolving call to function '"
5743 << Callee->getName() << "' arguments were dropped!\n";
5744 } else {
5745 // Add all of the arguments in their promoted form to the arg list...
5746 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5747 const Type *PTy = getPromotedType((*AI)->getType());
5748 if (PTy != (*AI)->getType()) {
5749 // Must promote to pass through va_arg area!
5750 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5751 InsertNewInstBefore(Cast, *Caller);
5752 Args.push_back(Cast);
5753 } else {
5754 Args.push_back(*AI);
5755 }
5756 }
5757 }
5758
5759 if (FT->getReturnType() == Type::VoidTy)
5760 Caller->setName(""); // Void type should not have a name...
5761
5762 Instruction *NC;
5763 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005764 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00005765 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00005766 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005767 } else {
5768 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00005769 if (cast<CallInst>(Caller)->isTailCall())
5770 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00005771 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005772 }
5773
5774 // Insert a cast of the return type as necessary...
5775 Value *NV = NC;
5776 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5777 if (NV->getType() != Type::VoidTy) {
5778 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00005779
5780 // If this is an invoke instruction, we should insert it after the first
5781 // non-phi, instruction in the normal successor block.
5782 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5783 BasicBlock::iterator I = II->getNormalDest()->begin();
5784 while (isa<PHINode>(I)) ++I;
5785 InsertNewInstBefore(NC, *I);
5786 } else {
5787 // Otherwise, it's a call, just insert cast right after the call instr
5788 InsertNewInstBefore(NC, *Caller);
5789 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005790 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00005791 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00005792 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00005793 }
5794 }
5795
5796 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5797 Caller->replaceAllUsesWith(NV);
5798 Caller->getParent()->getInstList().erase(Caller);
5799 removeFromWorkList(Caller);
5800 return true;
5801}
5802
5803
Chris Lattnerbac32862004-11-14 19:13:23 +00005804// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5805// operator and they all are only used by the PHI, PHI together their
5806// inputs, and do the operation once, to the result of the PHI.
5807Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5808 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5809
5810 // Scan the instruction, looking for input operations that can be folded away.
5811 // If all input operands to the phi are the same instruction (e.g. a cast from
5812 // the same type or "+42") we can pull the operation through the PHI, reducing
5813 // code size and simplifying code.
5814 Constant *ConstantOp = 0;
5815 const Type *CastSrcTy = 0;
5816 if (isa<CastInst>(FirstInst)) {
5817 CastSrcTy = FirstInst->getOperand(0)->getType();
5818 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5819 // Can fold binop or shift if the RHS is a constant.
5820 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5821 if (ConstantOp == 0) return 0;
5822 } else {
5823 return 0; // Cannot fold this operation.
5824 }
5825
5826 // Check to see if all arguments are the same operation.
5827 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5828 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5829 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5830 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5831 return 0;
5832 if (CastSrcTy) {
5833 if (I->getOperand(0)->getType() != CastSrcTy)
5834 return 0; // Cast operation must match.
5835 } else if (I->getOperand(1) != ConstantOp) {
5836 return 0;
5837 }
5838 }
5839
5840 // Okay, they are all the same operation. Create a new PHI node of the
5841 // correct type, and PHI together all of the LHS's of the instructions.
5842 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5843 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00005844 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00005845
5846 Value *InVal = FirstInst->getOperand(0);
5847 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00005848
5849 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00005850 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5851 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5852 if (NewInVal != InVal)
5853 InVal = 0;
5854 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5855 }
5856
5857 Value *PhiVal;
5858 if (InVal) {
5859 // The new PHI unions all of the same values together. This is really
5860 // common, so we handle it intelligently here for compile-time speed.
5861 PhiVal = InVal;
5862 delete NewPN;
5863 } else {
5864 InsertNewInstBefore(NewPN, PN);
5865 PhiVal = NewPN;
5866 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005867
Chris Lattnerbac32862004-11-14 19:13:23 +00005868 // Insert and return the new operation.
5869 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005870 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00005871 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005872 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005873 else
5874 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00005875 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005876}
Chris Lattnera1be5662002-05-02 17:06:02 +00005877
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005878/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5879/// that is dead.
5880static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5881 if (PN->use_empty()) return true;
5882 if (!PN->hasOneUse()) return false;
5883
5884 // Remember this node, and if we find the cycle, return.
5885 if (!PotentiallyDeadPHIs.insert(PN).second)
5886 return true;
5887
5888 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5889 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005890
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005891 return false;
5892}
5893
Chris Lattner473945d2002-05-06 18:06:38 +00005894// PHINode simplification
5895//
Chris Lattner7e708292002-06-25 16:13:24 +00005896Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner68ee7362005-08-05 01:04:30 +00005897 if (Value *V = PN.hasConstantValue())
5898 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00005899
5900 // If the only user of this instruction is a cast instruction, and all of the
5901 // incoming values are constants, change this PHI to merge together the casted
5902 // constants.
5903 if (PN.hasOneUse())
5904 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5905 if (CI->getType() != PN.getType()) { // noop casts will be folded
5906 bool AllConstant = true;
5907 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5908 if (!isa<Constant>(PN.getIncomingValue(i))) {
5909 AllConstant = false;
5910 break;
5911 }
5912 if (AllConstant) {
5913 // Make a new PHI with all casted values.
5914 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5915 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5916 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5917 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5918 PN.getIncomingBlock(i));
5919 }
5920
5921 // Update the cast instruction.
5922 CI->setOperand(0, New);
5923 WorkList.push_back(CI); // revisit the cast instruction to fold.
5924 WorkList.push_back(New); // Make sure to revisit the new Phi
5925 return &PN; // PN is now dead!
5926 }
5927 }
Chris Lattnerbac32862004-11-14 19:13:23 +00005928
5929 // If all PHI operands are the same operation, pull them through the PHI,
5930 // reducing code size.
5931 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5932 PN.getIncomingValue(0)->hasOneUse())
5933 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5934 return Result;
5935
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005936 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5937 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5938 // PHI)... break the cycle.
5939 if (PN.hasOneUse())
5940 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5941 std::set<PHINode*> PotentiallyDeadPHIs;
5942 PotentiallyDeadPHIs.insert(&PN);
5943 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5944 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5945 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005946
Chris Lattner60921c92003-12-19 05:58:40 +00005947 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00005948}
5949
Chris Lattner28977af2004-04-05 01:30:19 +00005950static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5951 Instruction *InsertPoint,
5952 InstCombiner *IC) {
5953 unsigned PS = IC->getTargetData().getPointerSize();
5954 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00005955 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5956 // We must insert a cast to ensure we sign-extend.
5957 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5958 V->getName()), *InsertPoint);
5959 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5960 *InsertPoint);
5961}
5962
Chris Lattnera1be5662002-05-02 17:06:02 +00005963
Chris Lattner7e708292002-06-25 16:13:24 +00005964Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00005965 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00005966 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00005967 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005968 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00005969 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005970
Chris Lattnere87597f2004-10-16 18:11:37 +00005971 if (isa<UndefValue>(GEP.getOperand(0)))
5972 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5973
Chris Lattnerc6bd1952004-02-22 05:25:17 +00005974 bool HasZeroPointerIndex = false;
5975 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5976 HasZeroPointerIndex = C->isNullValue();
5977
5978 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00005979 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00005980
Chris Lattner28977af2004-04-05 01:30:19 +00005981 // Eliminate unneeded casts for indices.
5982 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005983 gep_type_iterator GTI = gep_type_begin(GEP);
5984 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5985 if (isa<SequentialType>(*GTI)) {
5986 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5987 Value *Src = CI->getOperand(0);
5988 const Type *SrcTy = Src->getType();
5989 const Type *DestTy = CI->getType();
5990 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005991 if (SrcTy->getPrimitiveSizeInBits() ==
5992 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005993 // We can always eliminate a cast from ulong or long to the other.
5994 // We can always eliminate a cast from uint to int or the other on
5995 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00005996 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00005997 MadeChange = true;
5998 GEP.setOperand(i, Src);
5999 }
6000 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6001 SrcTy->getPrimitiveSize() == 4) {
6002 // We can always eliminate a cast from int to [u]long. We can
6003 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6004 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00006005 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00006006 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006007 MadeChange = true;
6008 GEP.setOperand(i, Src);
6009 }
Chris Lattner28977af2004-04-05 01:30:19 +00006010 }
6011 }
6012 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006013 // If we are using a wider index than needed for this platform, shrink it
6014 // to what we need. If the incoming value needs a cast instruction,
6015 // insert it. This explicit cast can make subsequent optimizations more
6016 // obvious.
6017 Value *Op = GEP.getOperand(i);
6018 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00006019 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00006020 GEP.setOperand(i, ConstantExpr::getCast(C,
6021 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00006022 MadeChange = true;
6023 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006024 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6025 Op->getName()), GEP);
6026 GEP.setOperand(i, Op);
6027 MadeChange = true;
6028 }
Chris Lattner67769e52004-07-20 01:48:15 +00006029
6030 // If this is a constant idx, make sure to canonicalize it to be a signed
6031 // operand, otherwise CSE and other optimizations are pessimized.
6032 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6033 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6034 CUI->getType()->getSignedVersion()));
6035 MadeChange = true;
6036 }
Chris Lattner28977af2004-04-05 01:30:19 +00006037 }
6038 if (MadeChange) return &GEP;
6039
Chris Lattner90ac28c2002-08-02 19:29:35 +00006040 // Combine Indices - If the source pointer to this getelementptr instruction
6041 // is a getelementptr instruction, combine the indices of the two
6042 // getelementptr instructions into a single instruction.
6043 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00006044 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00006045 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00006046 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00006047
6048 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00006049 // Note that if our source is a gep chain itself that we wait for that
6050 // chain to be resolved before we perform this transformation. This
6051 // avoids us creating a TON of code in some cases.
6052 //
6053 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6054 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6055 return 0; // Wait until our source is folded to completion.
6056
Chris Lattner90ac28c2002-08-02 19:29:35 +00006057 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00006058
6059 // Find out whether the last index in the source GEP is a sequential idx.
6060 bool EndsWithSequential = false;
6061 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6062 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00006063 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00006064
Chris Lattner90ac28c2002-08-02 19:29:35 +00006065 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00006066 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00006067 // Replace: gep (gep %P, long B), long A, ...
6068 // With: T = long A+B; gep %P, T, ...
6069 //
Chris Lattner620ce142004-05-07 22:09:22 +00006070 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00006071 if (SO1 == Constant::getNullValue(SO1->getType())) {
6072 Sum = GO1;
6073 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6074 Sum = SO1;
6075 } else {
6076 // If they aren't the same type, convert both to an integer of the
6077 // target's pointer size.
6078 if (SO1->getType() != GO1->getType()) {
6079 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6080 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6081 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6082 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6083 } else {
6084 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00006085 if (SO1->getType()->getPrimitiveSize() == PS) {
6086 // Convert GO1 to SO1's type.
6087 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6088
6089 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6090 // Convert SO1 to GO1's type.
6091 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6092 } else {
6093 const Type *PT = TD->getIntPtrType();
6094 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6095 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6096 }
6097 }
6098 }
Chris Lattner620ce142004-05-07 22:09:22 +00006099 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6100 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6101 else {
Chris Lattner48595f12004-06-10 02:07:29 +00006102 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6103 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00006104 }
Chris Lattner28977af2004-04-05 01:30:19 +00006105 }
Chris Lattner620ce142004-05-07 22:09:22 +00006106
6107 // Recycle the GEP we already have if possible.
6108 if (SrcGEPOperands.size() == 2) {
6109 GEP.setOperand(0, SrcGEPOperands[0]);
6110 GEP.setOperand(1, Sum);
6111 return &GEP;
6112 } else {
6113 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6114 SrcGEPOperands.end()-1);
6115 Indices.push_back(Sum);
6116 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6117 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006118 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00006119 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006120 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00006121 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00006122 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6123 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00006124 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6125 }
6126
6127 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00006128 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00006129
Chris Lattner620ce142004-05-07 22:09:22 +00006130 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00006131 // GEP of global variable. If all of the indices for this GEP are
6132 // constants, we can promote this to a constexpr instead of an instruction.
6133
6134 // Scan for nonconstants...
6135 std::vector<Constant*> Indices;
6136 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6137 for (; I != E && isa<Constant>(*I); ++I)
6138 Indices.push_back(cast<Constant>(*I));
6139
6140 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00006141 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00006142
6143 // Replace all uses of the GEP with the new constexpr...
6144 return ReplaceInstUsesWith(GEP, CE);
6145 }
Chris Lattnereed48272005-09-13 00:40:14 +00006146 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6147 if (!isa<PointerType>(X->getType())) {
6148 // Not interesting. Source pointer must be a cast from pointer.
6149 } else if (HasZeroPointerIndex) {
6150 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6151 // into : GEP [10 x ubyte]* X, long 0, ...
6152 //
6153 // This occurs when the program declares an array extern like "int X[];"
6154 //
6155 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6156 const PointerType *XTy = cast<PointerType>(X->getType());
6157 if (const ArrayType *XATy =
6158 dyn_cast<ArrayType>(XTy->getElementType()))
6159 if (const ArrayType *CATy =
6160 dyn_cast<ArrayType>(CPTy->getElementType()))
6161 if (CATy->getElementType() == XATy->getElementType()) {
6162 // At this point, we know that the cast source type is a pointer
6163 // to an array of the same type as the destination pointer
6164 // array. Because the array type is never stepped over (there
6165 // is a leading zero) we can fold the cast into this GEP.
6166 GEP.setOperand(0, X);
6167 return &GEP;
6168 }
6169 } else if (GEP.getNumOperands() == 2) {
6170 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00006171 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6172 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00006173 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6174 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6175 if (isa<ArrayType>(SrcElTy) &&
6176 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6177 TD->getTypeSize(ResElTy)) {
6178 Value *V = InsertNewInstBefore(
6179 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6180 GEP.getOperand(1), GEP.getName()), GEP);
6181 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006182 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00006183
6184 // Transform things like:
6185 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6186 // (where tmp = 8*tmp2) into:
6187 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6188
6189 if (isa<ArrayType>(SrcElTy) &&
6190 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6191 uint64_t ArrayEltSize =
6192 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6193
6194 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6195 // allow either a mul, shift, or constant here.
6196 Value *NewIdx = 0;
6197 ConstantInt *Scale = 0;
6198 if (ArrayEltSize == 1) {
6199 NewIdx = GEP.getOperand(1);
6200 Scale = ConstantInt::get(NewIdx->getType(), 1);
6201 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00006202 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006203 Scale = CI;
6204 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6205 if (Inst->getOpcode() == Instruction::Shl &&
6206 isa<ConstantInt>(Inst->getOperand(1))) {
6207 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6208 if (Inst->getType()->isSigned())
6209 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6210 else
6211 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6212 NewIdx = Inst->getOperand(0);
6213 } else if (Inst->getOpcode() == Instruction::Mul &&
6214 isa<ConstantInt>(Inst->getOperand(1))) {
6215 Scale = cast<ConstantInt>(Inst->getOperand(1));
6216 NewIdx = Inst->getOperand(0);
6217 }
6218 }
6219
6220 // If the index will be to exactly the right offset with the scale taken
6221 // out, perform the transformation.
6222 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6223 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6224 Scale = ConstantSInt::get(C->getType(),
Chris Lattner6e2f8432005-09-14 17:32:56 +00006225 (int64_t)C->getRawValue() /
6226 (int64_t)ArrayEltSize);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006227 else
6228 Scale = ConstantUInt::get(Scale->getType(),
6229 Scale->getRawValue() / ArrayEltSize);
6230 if (Scale->getRawValue() != 1) {
6231 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6232 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6233 NewIdx = InsertNewInstBefore(Sc, GEP);
6234 }
6235
6236 // Insert the new GEP instruction.
6237 Instruction *Idx =
6238 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6239 NewIdx, GEP.getName());
6240 Idx = InsertNewInstBefore(Idx, GEP);
6241 return new CastInst(Idx, GEP.getType());
6242 }
6243 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006244 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006245 }
6246
Chris Lattner8a2a3112001-12-14 16:52:21 +00006247 return 0;
6248}
6249
Chris Lattner0864acf2002-11-04 16:18:53 +00006250Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6251 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6252 if (AI.isArrayAllocation()) // Check C != 1
6253 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6254 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00006255 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00006256
6257 // Create and insert the replacement instruction...
6258 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00006259 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00006260 else {
6261 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00006262 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00006263 }
Chris Lattner7c881df2004-03-19 06:08:10 +00006264
6265 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00006266
Chris Lattner0864acf2002-11-04 16:18:53 +00006267 // Scan to the end of the allocation instructions, to skip over a block of
6268 // allocas if possible...
6269 //
6270 BasicBlock::iterator It = New;
6271 while (isa<AllocationInst>(*It)) ++It;
6272
6273 // Now that I is pointing to the first non-allocation-inst in the block,
6274 // insert our getelementptr instruction...
6275 //
Chris Lattner693787a2005-05-04 19:10:26 +00006276 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6277 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6278 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00006279
6280 // Now make everything use the getelementptr instead of the original
6281 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00006282 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00006283 } else if (isa<UndefValue>(AI.getArraySize())) {
6284 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00006285 }
Chris Lattner7c881df2004-03-19 06:08:10 +00006286
6287 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6288 // Note that we only do this for alloca's, because malloc should allocate and
6289 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00006290 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00006291 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00006292 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6293
Chris Lattner0864acf2002-11-04 16:18:53 +00006294 return 0;
6295}
6296
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006297Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6298 Value *Op = FI.getOperand(0);
6299
6300 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6301 if (CastInst *CI = dyn_cast<CastInst>(Op))
6302 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6303 FI.setOperand(0, CI->getOperand(0));
6304 return &FI;
6305 }
6306
Chris Lattner17be6352004-10-18 02:59:09 +00006307 // free undef -> unreachable.
6308 if (isa<UndefValue>(Op)) {
6309 // Insert a new store to null because we cannot modify the CFG here.
6310 new StoreInst(ConstantBool::True,
6311 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6312 return EraseInstFromFunction(FI);
6313 }
6314
Chris Lattner6160e852004-02-28 04:57:37 +00006315 // If we have 'free null' delete the instruction. This can happen in stl code
6316 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00006317 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006318 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00006319
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006320 return 0;
6321}
6322
6323
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006324/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00006325static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6326 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00006327 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00006328
6329 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00006330 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00006331 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00006332
Chris Lattnera1c35382006-04-02 05:37:12 +00006333 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6334 isa<PackedType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00006335 // If the source is an array, the code below will not succeed. Check to
6336 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6337 // constants.
6338 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6339 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6340 if (ASrcTy->getNumElements() != 0) {
6341 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6342 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6343 SrcTy = cast<PointerType>(CastOp->getType());
6344 SrcPTy = SrcTy->getElementType();
6345 }
6346
Chris Lattnera1c35382006-04-02 05:37:12 +00006347 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6348 isa<PackedType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00006349 // Do not allow turning this into a load of an integer, which is then
6350 // casted to a pointer, this pessimizes pointer analysis a lot.
6351 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006352 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00006353 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00006354
Chris Lattnerf9527852005-01-31 04:50:46 +00006355 // Okay, we are casting from one integer or pointer type to another of
6356 // the same size. Instead of casting the pointer before the load, cast
6357 // the result of the loaded value.
6358 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6359 CI->getName(),
6360 LI.isVolatile()),LI);
6361 // Now cast the result of the load.
6362 return new CastInst(NewLoad, LI.getType());
6363 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00006364 }
6365 }
6366 return 0;
6367}
6368
Chris Lattnerc10aced2004-09-19 18:43:46 +00006369/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00006370/// from this value cannot trap. If it is not obviously safe to load from the
6371/// specified pointer, we do a quick local scan of the basic block containing
6372/// ScanFrom, to determine if the address is already accessed.
6373static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6374 // If it is an alloca or global variable, it is always safe to load from.
6375 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6376
6377 // Otherwise, be a little bit agressive by scanning the local block where we
6378 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006379 // from/to. If so, the previous load or store would have already trapped,
6380 // so there is no harm doing an extra load (also, CSE will later eliminate
6381 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00006382 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6383
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006384 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00006385 --BBI;
6386
6387 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6388 if (LI->getOperand(0) == V) return true;
6389 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6390 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00006391
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006392 }
Chris Lattner8a375202004-09-19 19:18:10 +00006393 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00006394}
6395
Chris Lattner833b8a42003-06-26 05:06:25 +00006396Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6397 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00006398
Chris Lattner37366c12005-05-01 04:24:53 +00006399 // load (cast X) --> cast (load X) iff safe
6400 if (CastInst *CI = dyn_cast<CastInst>(Op))
6401 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6402 return Res;
6403
6404 // None of the following transforms are legal for volatile loads.
6405 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00006406
Chris Lattner62f254d2005-09-12 22:00:15 +00006407 if (&LI.getParent()->front() != &LI) {
6408 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00006409 // If the instruction immediately before this is a store to the same
6410 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00006411 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6412 if (SI->getOperand(1) == LI.getOperand(0))
6413 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00006414 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6415 if (LIB->getOperand(0) == LI.getOperand(0))
6416 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00006417 }
Chris Lattner37366c12005-05-01 04:24:53 +00006418
6419 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6420 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6421 isa<UndefValue>(GEPI->getOperand(0))) {
6422 // Insert a new store to null instruction before the load to indicate
6423 // that this code is not reachable. We do this instead of inserting
6424 // an unreachable instruction directly because we cannot modify the
6425 // CFG.
6426 new StoreInst(UndefValue::get(LI.getType()),
6427 Constant::getNullValue(Op->getType()), &LI);
6428 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6429 }
6430
Chris Lattnere87597f2004-10-16 18:11:37 +00006431 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00006432 // load null/undef -> undef
6433 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00006434 // Insert a new store to null instruction before the load to indicate that
6435 // this code is not reachable. We do this instead of inserting an
6436 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00006437 new StoreInst(UndefValue::get(LI.getType()),
6438 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00006439 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00006440 }
Chris Lattner833b8a42003-06-26 05:06:25 +00006441
Chris Lattnere87597f2004-10-16 18:11:37 +00006442 // Instcombine load (constant global) into the value loaded.
6443 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6444 if (GV->isConstant() && !GV->isExternal())
6445 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00006446
Chris Lattnere87597f2004-10-16 18:11:37 +00006447 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6448 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6449 if (CE->getOpcode() == Instruction::GetElementPtr) {
6450 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6451 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00006452 if (Constant *V =
6453 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00006454 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00006455 if (CE->getOperand(0)->isNullValue()) {
6456 // Insert a new store to null instruction before the load to indicate
6457 // that this code is not reachable. We do this instead of inserting
6458 // an unreachable instruction directly because we cannot modify the
6459 // CFG.
6460 new StoreInst(UndefValue::get(LI.getType()),
6461 Constant::getNullValue(Op->getType()), &LI);
6462 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6463 }
6464
Chris Lattnere87597f2004-10-16 18:11:37 +00006465 } else if (CE->getOpcode() == Instruction::Cast) {
6466 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6467 return Res;
6468 }
6469 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00006470
Chris Lattner37366c12005-05-01 04:24:53 +00006471 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00006472 // Change select and PHI nodes to select values instead of addresses: this
6473 // helps alias analysis out a lot, allows many others simplifications, and
6474 // exposes redundancy in the code.
6475 //
6476 // Note that we cannot do the transformation unless we know that the
6477 // introduced loads cannot trap! Something like this is valid as long as
6478 // the condition is always false: load (select bool %C, int* null, int* %G),
6479 // but it would not be valid if we transformed it to load from null
6480 // unconditionally.
6481 //
6482 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6483 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00006484 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6485 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00006486 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006487 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00006488 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006489 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00006490 return new SelectInst(SI->getCondition(), V1, V2);
6491 }
6492
Chris Lattner684fe212004-09-23 15:46:00 +00006493 // load (select (cond, null, P)) -> load P
6494 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6495 if (C->isNullValue()) {
6496 LI.setOperand(0, SI->getOperand(2));
6497 return &LI;
6498 }
6499
6500 // load (select (cond, P, null)) -> load P
6501 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6502 if (C->isNullValue()) {
6503 LI.setOperand(0, SI->getOperand(1));
6504 return &LI;
6505 }
6506
Chris Lattnerc10aced2004-09-19 18:43:46 +00006507 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6508 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006509 bool Safe = PN->getParent() == LI.getParent();
6510
6511 // Scan all of the instructions between the PHI and the load to make
6512 // sure there are no instructions that might possibly alter the value
6513 // loaded from the PHI.
6514 if (Safe) {
6515 BasicBlock::iterator I = &LI;
6516 for (--I; !isa<PHINode>(I); --I)
6517 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6518 Safe = false;
6519 break;
6520 }
6521 }
6522
6523 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00006524 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006525 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00006526 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006527
Chris Lattnerc10aced2004-09-19 18:43:46 +00006528 if (Safe) {
6529 // Create the PHI.
6530 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6531 InsertNewInstBefore(NewPN, *PN);
6532 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6533
6534 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6535 BasicBlock *BB = PN->getIncomingBlock(i);
6536 Value *&TheLoad = LoadMap[BB];
6537 if (TheLoad == 0) {
6538 Value *InVal = PN->getIncomingValue(i);
6539 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6540 InVal->getName()+".val"),
6541 *BB->getTerminator());
6542 }
6543 NewPN->addIncoming(TheLoad, BB);
6544 }
6545 return ReplaceInstUsesWith(LI, NewPN);
6546 }
6547 }
6548 }
Chris Lattner833b8a42003-06-26 05:06:25 +00006549 return 0;
6550}
6551
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006552/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6553/// when possible.
6554static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6555 User *CI = cast<User>(SI.getOperand(1));
6556 Value *CastOp = CI->getOperand(0);
6557
6558 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6559 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6560 const Type *SrcPTy = SrcTy->getElementType();
6561
6562 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6563 // If the source is an array, the code below will not succeed. Check to
6564 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6565 // constants.
6566 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6567 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6568 if (ASrcTy->getNumElements() != 0) {
6569 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6570 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6571 SrcTy = cast<PointerType>(CastOp->getType());
6572 SrcPTy = SrcTy->getElementType();
6573 }
6574
6575 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006576 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006577 IC.getTargetData().getTypeSize(DestPTy)) {
6578
6579 // Okay, we are casting from one integer or pointer type to another of
6580 // the same size. Instead of casting the pointer before the store, cast
6581 // the value to be stored.
6582 Value *NewCast;
6583 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6584 NewCast = ConstantExpr::getCast(C, SrcPTy);
6585 else
6586 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6587 SrcPTy,
6588 SI.getOperand(0)->getName()+".c"), SI);
6589
6590 return new StoreInst(NewCast, CastOp);
6591 }
6592 }
6593 }
6594 return 0;
6595}
6596
Chris Lattner2f503e62005-01-31 05:36:43 +00006597Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6598 Value *Val = SI.getOperand(0);
6599 Value *Ptr = SI.getOperand(1);
6600
6601 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00006602 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00006603 ++NumCombined;
6604 return 0;
6605 }
6606
Chris Lattner9ca96412006-02-08 03:25:32 +00006607 // Do really simple DSE, to catch cases where there are several consequtive
6608 // stores to the same location, separated by a few arithmetic operations. This
6609 // situation often occurs with bitfield accesses.
6610 BasicBlock::iterator BBI = &SI;
6611 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6612 --ScanInsts) {
6613 --BBI;
6614
6615 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6616 // Prev store isn't volatile, and stores to the same location?
6617 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6618 ++NumDeadStore;
6619 ++BBI;
6620 EraseInstFromFunction(*PrevSI);
6621 continue;
6622 }
6623 break;
6624 }
6625
6626 // Don't skip over loads or things that can modify memory.
6627 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6628 break;
6629 }
6630
6631
6632 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00006633
6634 // store X, null -> turns into 'unreachable' in SimplifyCFG
6635 if (isa<ConstantPointerNull>(Ptr)) {
6636 if (!isa<UndefValue>(Val)) {
6637 SI.setOperand(0, UndefValue::get(Val->getType()));
6638 if (Instruction *U = dyn_cast<Instruction>(Val))
6639 WorkList.push_back(U); // Dropped a use.
6640 ++NumCombined;
6641 }
6642 return 0; // Do not modify these!
6643 }
6644
6645 // store undef, Ptr -> noop
6646 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00006647 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00006648 ++NumCombined;
6649 return 0;
6650 }
6651
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006652 // If the pointer destination is a cast, see if we can fold the cast into the
6653 // source instead.
6654 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6655 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6656 return Res;
6657 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6658 if (CE->getOpcode() == Instruction::Cast)
6659 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6660 return Res;
6661
Chris Lattner408902b2005-09-12 23:23:25 +00006662
6663 // If this store is the last instruction in the basic block, and if the block
6664 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00006665 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00006666 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6667 if (BI->isUnconditional()) {
6668 // Check to see if the successor block has exactly two incoming edges. If
6669 // so, see if the other predecessor contains a store to the same location.
6670 // if so, insert a PHI node (if needed) and move the stores down.
6671 BasicBlock *Dest = BI->getSuccessor(0);
6672
6673 pred_iterator PI = pred_begin(Dest);
6674 BasicBlock *Other = 0;
6675 if (*PI != BI->getParent())
6676 Other = *PI;
6677 ++PI;
6678 if (PI != pred_end(Dest)) {
6679 if (*PI != BI->getParent())
6680 if (Other)
6681 Other = 0;
6682 else
6683 Other = *PI;
6684 if (++PI != pred_end(Dest))
6685 Other = 0;
6686 }
6687 if (Other) { // If only one other pred...
6688 BBI = Other->getTerminator();
6689 // Make sure this other block ends in an unconditional branch and that
6690 // there is an instruction before the branch.
6691 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6692 BBI != Other->begin()) {
6693 --BBI;
6694 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6695
6696 // If this instruction is a store to the same location.
6697 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6698 // Okay, we know we can perform this transformation. Insert a PHI
6699 // node now if we need it.
6700 Value *MergedVal = OtherStore->getOperand(0);
6701 if (MergedVal != SI.getOperand(0)) {
6702 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6703 PN->reserveOperandSpace(2);
6704 PN->addIncoming(SI.getOperand(0), SI.getParent());
6705 PN->addIncoming(OtherStore->getOperand(0), Other);
6706 MergedVal = InsertNewInstBefore(PN, Dest->front());
6707 }
6708
6709 // Advance to a place where it is safe to insert the new store and
6710 // insert it.
6711 BBI = Dest->begin();
6712 while (isa<PHINode>(BBI)) ++BBI;
6713 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6714 OtherStore->isVolatile()), *BBI);
6715
6716 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00006717 EraseInstFromFunction(SI);
6718 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00006719 ++NumCombined;
6720 return 0;
6721 }
6722 }
6723 }
6724 }
6725
Chris Lattner2f503e62005-01-31 05:36:43 +00006726 return 0;
6727}
6728
6729
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006730Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6731 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00006732 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006733 BasicBlock *TrueDest;
6734 BasicBlock *FalseDest;
6735 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6736 !isa<Constant>(X)) {
6737 // Swap Destinations and condition...
6738 BI.setCondition(X);
6739 BI.setSuccessor(0, FalseDest);
6740 BI.setSuccessor(1, TrueDest);
6741 return &BI;
6742 }
6743
6744 // Cannonicalize setne -> seteq
6745 Instruction::BinaryOps Op; Value *Y;
6746 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6747 TrueDest, FalseDest)))
6748 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6749 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6750 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6751 std::string Name = I->getName(); I->setName("");
6752 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6753 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00006754 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006755 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00006756 BI.setSuccessor(0, FalseDest);
6757 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006758 removeFromWorkList(I);
6759 I->getParent()->getInstList().erase(I);
6760 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00006761 return &BI;
6762 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006763
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006764 return 0;
6765}
Chris Lattner0864acf2002-11-04 16:18:53 +00006766
Chris Lattner46238a62004-07-03 00:26:11 +00006767Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6768 Value *Cond = SI.getCondition();
6769 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6770 if (I->getOpcode() == Instruction::Add)
6771 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6772 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6773 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00006774 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00006775 AddRHS));
6776 SI.setOperand(0, I->getOperand(0));
6777 WorkList.push_back(I);
6778 return &SI;
6779 }
6780 }
6781 return 0;
6782}
6783
Chris Lattner220b0cf2006-03-05 00:22:33 +00006784/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6785/// is to leave as a vector operation.
6786static bool CheapToScalarize(Value *V, bool isConstant) {
6787 if (isa<ConstantAggregateZero>(V))
6788 return true;
6789 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6790 if (isConstant) return true;
6791 // If all elts are the same, we can extract.
6792 Constant *Op0 = C->getOperand(0);
6793 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6794 if (C->getOperand(i) != Op0)
6795 return false;
6796 return true;
6797 }
6798 Instruction *I = dyn_cast<Instruction>(V);
6799 if (!I) return false;
6800
6801 // Insert element gets simplified to the inserted element or is deleted if
6802 // this is constant idx extract element and its a constant idx insertelt.
6803 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6804 isa<ConstantInt>(I->getOperand(2)))
6805 return true;
6806 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6807 return true;
6808 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6809 if (BO->hasOneUse() &&
6810 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6811 CheapToScalarize(BO->getOperand(1), isConstant)))
6812 return true;
6813
6814 return false;
6815}
6816
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006817/// FindScalarElement - Given a vector and an element number, see if the scalar
6818/// value is already around as a register, for example if it were inserted then
6819/// extracted from the vector.
6820static Value *FindScalarElement(Value *V, unsigned EltNo) {
6821 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
6822 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00006823 unsigned Width = PTy->getNumElements();
6824 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006825 return UndefValue::get(PTy->getElementType());
6826
6827 if (isa<UndefValue>(V))
6828 return UndefValue::get(PTy->getElementType());
6829 else if (isa<ConstantAggregateZero>(V))
6830 return Constant::getNullValue(PTy->getElementType());
6831 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
6832 return CP->getOperand(EltNo);
6833 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
6834 // If this is an insert to a variable element, we don't know what it is.
6835 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
6836 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
6837
6838 // If this is an insert to the element we are looking for, return the
6839 // inserted value.
6840 if (EltNo == IIElt) return III->getOperand(1);
6841
6842 // Otherwise, the insertelement doesn't modify the value, recurse on its
6843 // vector input.
6844 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00006845 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
6846 if (isa<ConstantAggregateZero>(SVI->getOperand(2))) {
6847 return FindScalarElement(SVI->getOperand(0), 0);
6848 } else if (ConstantPacked *CP =
6849 dyn_cast<ConstantPacked>(SVI->getOperand(2))) {
6850 if (isa<UndefValue>(CP->getOperand(EltNo)))
6851 return UndefValue::get(PTy->getElementType());
6852 unsigned InEl = cast<ConstantUInt>(CP->getOperand(EltNo))->getValue();
6853 if (InEl < Width)
6854 return FindScalarElement(SVI->getOperand(0), InEl);
6855 else
6856 return FindScalarElement(SVI->getOperand(1), InEl - Width);
6857 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006858 }
6859
6860 // Otherwise, we don't know.
6861 return 0;
6862}
6863
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006864Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006865
Chris Lattner1f13c882006-03-31 18:25:14 +00006866 // If packed val is undef, replace extract with scalar undef.
6867 if (isa<UndefValue>(EI.getOperand(0)))
6868 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
6869
6870 // If packed val is constant 0, replace extract with scalar 0.
6871 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
6872 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
6873
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006874 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6875 // If packed val is constant with uniform operands, replace EI
6876 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00006877 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006878 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00006879 if (C->getOperand(i) != op0) {
6880 op0 = 0;
6881 break;
6882 }
6883 if (op0)
6884 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006885 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00006886
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006887 // If extracting a specified index from the vector, see if we can recursively
6888 // find a previously computed scalar that was inserted into the vector.
Chris Lattner389a6f52006-04-10 23:06:36 +00006889 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006890 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
6891 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00006892 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006893
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006894 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6895 if (I->hasOneUse()) {
6896 // Push extractelement into predecessor operation if legal and
6897 // profitable to do so
6898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00006899 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
6900 if (CheapToScalarize(BO, isConstantElt)) {
6901 ExtractElementInst *newEI0 =
6902 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6903 EI.getName()+".lhs");
6904 ExtractElementInst *newEI1 =
6905 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6906 EI.getName()+".rhs");
6907 InsertNewInstBefore(newEI0, EI);
6908 InsertNewInstBefore(newEI1, EI);
6909 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6910 }
6911 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006912 Value *Ptr = InsertCastBefore(I->getOperand(0),
6913 PointerType::get(EI.getType()), EI);
6914 GetElementPtrInst *GEP =
6915 new GetElementPtrInst(Ptr, EI.getOperand(1),
6916 I->getName() + ".gep");
6917 InsertNewInstBefore(GEP, EI);
6918 return new LoadInst(GEP);
Chris Lattner220b0cf2006-03-05 00:22:33 +00006919 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
6920 // Extracting the inserted element?
6921 if (IE->getOperand(2) == EI.getOperand(1))
6922 return ReplaceInstUsesWith(EI, IE->getOperand(1));
6923 // If the inserted and extracted elements are constants, they must not
Chris Lattnerdf084ff2006-03-30 22:02:40 +00006924 // be the same value, extract from the pre-inserted value instead.
6925 if (isa<Constant>(IE->getOperand(2)) &&
6926 isa<Constant>(EI.getOperand(1))) {
6927 AddUsesToWorkList(EI);
6928 EI.setOperand(0, IE->getOperand(0));
6929 return &EI;
6930 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006931 }
6932 }
6933 return 0;
6934}
6935
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00006936/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
6937/// elements from either LHS or RHS, return the shuffle mask and true.
6938/// Otherwise, return false.
6939static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
6940 std::vector<Constant*> &Mask) {
6941 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
6942 "Invalid CollectSingleShuffleElements");
6943 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
6944
6945 if (isa<UndefValue>(V)) {
6946 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
6947 return true;
6948 } else if (V == LHS) {
6949 for (unsigned i = 0; i != NumElts; ++i)
6950 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
6951 return true;
6952 } else if (V == RHS) {
6953 for (unsigned i = 0; i != NumElts; ++i)
6954 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
6955 return true;
6956 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
6957 // If this is an insert of an extract from some other vector, include it.
6958 Value *VecOp = IEI->getOperand(0);
6959 Value *ScalarOp = IEI->getOperand(1);
6960 Value *IdxOp = IEI->getOperand(2);
6961
6962 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
6963 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
6964 EI->getOperand(0)->getType() == V->getType()) {
6965 unsigned ExtractedIdx =
6966 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
6967 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
6968
6969 // This must be extracting from either LHS or RHS.
6970 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
6971 // Okay, we can handle this if the vector we are insertinting into is
6972 // transitively ok.
6973 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
6974 // If so, update the mask to reflect the inserted value.
6975 if (EI->getOperand(0) == LHS) {
6976 Mask[InsertedIdx & (NumElts-1)] =
6977 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
6978 } else {
6979 assert(EI->getOperand(0) == RHS);
6980 Mask[InsertedIdx & (NumElts-1)] =
6981 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
6982
6983 }
6984 return true;
6985 }
6986 }
6987 }
6988 }
6989 }
6990 // TODO: Handle shufflevector here!
6991
6992 return false;
6993}
6994
6995/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
6996/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
6997/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00006998static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00006999 Value *&RHS) {
7000 assert(isa<PackedType>(V->getType()) &&
7001 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00007002 "Invalid shuffle!");
7003 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7004
7005 if (isa<UndefValue>(V)) {
7006 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7007 return V;
7008 } else if (isa<ConstantAggregateZero>(V)) {
7009 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7010 return V;
7011 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7012 // If this is an insert of an extract from some other vector, include it.
7013 Value *VecOp = IEI->getOperand(0);
7014 Value *ScalarOp = IEI->getOperand(1);
7015 Value *IdxOp = IEI->getOperand(2);
7016
7017 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7018 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7019 EI->getOperand(0)->getType() == V->getType()) {
7020 unsigned ExtractedIdx =
7021 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7022 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7023
7024 // Either the extracted from or inserted into vector must be RHSVec,
7025 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007026 if (EI->getOperand(0) == RHS || RHS == 0) {
7027 RHS = EI->getOperand(0);
7028 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00007029 Mask[InsertedIdx & (NumElts-1)] =
7030 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7031 return V;
7032 }
7033
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007034 if (VecOp == RHS) {
7035 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00007036 // Everything but the extracted element is replaced with the RHS.
7037 for (unsigned i = 0; i != NumElts; ++i) {
7038 if (i != InsertedIdx)
7039 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7040 }
7041 return V;
7042 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007043
7044 // If this insertelement is a chain that comes from exactly these two
7045 // vectors, return the vector and the effective shuffle.
7046 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7047 return EI->getOperand(0);
7048
Chris Lattnerefb47352006-04-15 01:39:45 +00007049 }
7050 }
7051 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007052 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00007053
7054 // Otherwise, can't do anything fancy. Return an identity vector.
7055 for (unsigned i = 0; i != NumElts; ++i)
7056 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7057 return V;
7058}
7059
7060Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7061 Value *VecOp = IE.getOperand(0);
7062 Value *ScalarOp = IE.getOperand(1);
7063 Value *IdxOp = IE.getOperand(2);
7064
7065 // If the inserted element was extracted from some other vector, and if the
7066 // indexes are constant, try to turn this into a shufflevector operation.
7067 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7068 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7069 EI->getOperand(0)->getType() == IE.getType()) {
7070 unsigned NumVectorElts = IE.getType()->getNumElements();
7071 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7072 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7073
7074 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7075 return ReplaceInstUsesWith(IE, VecOp);
7076
7077 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7078 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7079
7080 // If we are extracting a value from a vector, then inserting it right
7081 // back into the same place, just use the input vector.
7082 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7083 return ReplaceInstUsesWith(IE, VecOp);
7084
7085 // We could theoretically do this for ANY input. However, doing so could
7086 // turn chains of insertelement instructions into a chain of shufflevector
7087 // instructions, and right now we do not merge shufflevectors. As such,
7088 // only do this in a situation where it is clear that there is benefit.
7089 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7090 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7091 // the values of VecOp, except then one read from EIOp0.
7092 // Build a new shuffle mask.
7093 std::vector<Constant*> Mask;
7094 if (isa<UndefValue>(VecOp))
7095 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7096 else {
7097 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7098 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7099 NumVectorElts));
7100 }
7101 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7102 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7103 ConstantPacked::get(Mask));
7104 }
7105
7106 // If this insertelement isn't used by some other insertelement, turn it
7107 // (and any insertelements it points to), into one big shuffle.
7108 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7109 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007110 Value *RHS = 0;
7111 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7112 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7113 // We now have a shuffle of LHS, RHS, Mask.
7114 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00007115 }
7116 }
7117 }
7118
7119 return 0;
7120}
7121
7122
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007123Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7124 Value *LHS = SVI.getOperand(0);
7125 Value *RHS = SVI.getOperand(1);
7126 Constant *Mask = cast<Constant>(SVI.getOperand(2));
7127
7128 bool MadeChange = false;
7129
7130 if (isa<UndefValue>(Mask))
7131 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7132
Chris Lattnerefb47352006-04-15 01:39:45 +00007133 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7134 // the undef, change them to undefs.
7135
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007136 // Canonicalize shuffle(x,x) -> shuffle(x,undef)
7137 if (LHS == RHS) {
7138 if (isa<UndefValue>(LHS)) {
7139 // shuffle(undef,undef,mask) -> undef.
7140 return ReplaceInstUsesWith(SVI, LHS);
7141 }
7142
7143 if (!isa<ConstantAggregateZero>(Mask)) {
7144 // Remap any references to RHS to use LHS.
7145 ConstantPacked *CP = cast<ConstantPacked>(Mask);
7146 std::vector<Constant*> Elts;
7147 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7148 Elts.push_back(CP->getOperand(i));
7149 if (isa<UndefValue>(CP->getOperand(i)))
7150 continue;
7151 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7152 if (MV >= e)
7153 Elts.back() = ConstantUInt::get(Type::UIntTy, MV & (e-1));
7154 }
7155 Mask = ConstantPacked::get(Elts);
7156 }
7157 SVI.setOperand(1, UndefValue::get(RHS->getType()));
7158 SVI.setOperand(2, Mask);
7159 MadeChange = true;
7160 }
7161
Chris Lattner706126d2006-04-16 00:03:56 +00007162 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7163 if (isa<UndefValue>(LHS)) {
7164 // shuffle(undef,x,<0,0,0,0>) -> undef.
7165 if (isa<ConstantAggregateZero>(Mask))
7166 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7167
7168 ConstantPacked *CPM = cast<ConstantPacked>(Mask);
7169 std::vector<Constant*> Elts;
7170 for (unsigned i = 0, e = CPM->getNumOperands(); i != e; ++i) {
7171 if (isa<UndefValue>(CPM->getOperand(i)))
7172 Elts.push_back(CPM->getOperand(i));
7173 else {
7174 unsigned EltNo = cast<ConstantUInt>(CPM->getOperand(i))->getRawValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007175 if (EltNo >= e)
7176 Elts.push_back(ConstantUInt::get(Type::UIntTy, EltNo-e));
Chris Lattner706126d2006-04-16 00:03:56 +00007177 else // Referring to the undef.
7178 Elts.push_back(UndefValue::get(Type::UIntTy));
7179 }
7180 }
7181 return new ShuffleVectorInst(RHS, LHS, ConstantPacked::get(Elts));
7182 }
7183
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007184 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Mask)) {
7185 bool isLHSID = true, isRHSID = true;
7186
7187 // Analyze the shuffle.
7188 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7189 if (isa<UndefValue>(CP->getOperand(i)))
7190 continue;
7191 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7192
7193 // Is this an identity shuffle of the LHS value?
7194 isLHSID &= (MV == i);
7195
7196 // Is this an identity shuffle of the RHS value?
7197 isRHSID &= (MV-e == i);
7198 }
7199
7200 // Eliminate identity shuffles.
7201 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7202 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
7203 }
7204
7205 return MadeChange ? &SVI : 0;
7206}
7207
7208
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007209
Chris Lattner62b14df2002-09-02 04:59:56 +00007210void InstCombiner::removeFromWorkList(Instruction *I) {
7211 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7212 WorkList.end());
7213}
7214
Chris Lattnerea1c4542004-12-08 23:43:58 +00007215
7216/// TryToSinkInstruction - Try to move the specified instruction from its
7217/// current block into the beginning of DestBlock, which can only happen if it's
7218/// safe to move the instruction past all of the instructions between it and the
7219/// end of its block.
7220static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7221 assert(I->hasOneUse() && "Invariants didn't hold!");
7222
Chris Lattner108e9022005-10-27 17:13:11 +00007223 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7224 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00007225
Chris Lattnerea1c4542004-12-08 23:43:58 +00007226 // Do not sink alloca instructions out of the entry block.
7227 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7228 return false;
7229
Chris Lattner96a52a62004-12-09 07:14:34 +00007230 // We can only sink load instructions if there is nothing between the load and
7231 // the end of block that could change the value.
7232 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00007233 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7234 Scan != E; ++Scan)
7235 if (Scan->mayWriteToMemory())
7236 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00007237 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00007238
7239 BasicBlock::iterator InsertPos = DestBlock->begin();
7240 while (isa<PHINode>(InsertPos)) ++InsertPos;
7241
Chris Lattner4bc5f802005-08-08 19:11:57 +00007242 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00007243 ++NumSunkInst;
7244 return true;
7245}
7246
Chris Lattner7e708292002-06-25 16:13:24 +00007247bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007248 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00007249 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00007250
Chris Lattnerb3d59702005-07-07 20:40:38 +00007251 {
7252 // Populate the worklist with the reachable instructions.
7253 std::set<BasicBlock*> Visited;
7254 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
7255 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
7256 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
7257 WorkList.push_back(I);
Jeff Cohen00b168892005-07-27 06:12:32 +00007258
Chris Lattnerb3d59702005-07-07 20:40:38 +00007259 // Do a quick scan over the function. If we find any blocks that are
7260 // unreachable, remove any instructions inside of them. This prevents
7261 // the instcombine code from having to deal with some bad special cases.
7262 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7263 if (!Visited.count(BB)) {
7264 Instruction *Term = BB->getTerminator();
7265 while (Term != BB->begin()) { // Remove instrs bottom-up
7266 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00007267
Chris Lattnerb3d59702005-07-07 20:40:38 +00007268 DEBUG(std::cerr << "IC: DCE: " << *I);
7269 ++NumDeadInst;
7270
7271 if (!I->use_empty())
7272 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7273 I->eraseFromParent();
7274 }
7275 }
7276 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00007277
7278 while (!WorkList.empty()) {
7279 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7280 WorkList.pop_back();
7281
Misha Brukmana3bbcb52002-10-29 23:06:16 +00007282 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00007283 // Check to see if we can DIE the instruction...
7284 if (isInstructionTriviallyDead(I)) {
7285 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00007286 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007287 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00007288 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00007289
Chris Lattnerad5fec12005-01-28 19:32:01 +00007290 DEBUG(std::cerr << "IC: DCE: " << *I);
7291
7292 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00007293 removeFromWorkList(I);
7294 continue;
7295 }
Chris Lattner62b14df2002-09-02 04:59:56 +00007296
Misha Brukmana3bbcb52002-10-29 23:06:16 +00007297 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00007298 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00007299 Value* Ptr = I->getOperand(0);
Chris Lattner061718c2004-10-16 19:44:59 +00007300 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00007301 cast<Constant>(Ptr)->isNullValue() &&
7302 !isa<ConstantPointerNull>(C) &&
7303 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner061718c2004-10-16 19:44:59 +00007304 // If this is a constant expr gep that is effectively computing an
7305 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
7306 bool isFoldableGEP = true;
7307 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
7308 if (!isa<ConstantInt>(I->getOperand(i)))
7309 isFoldableGEP = false;
7310 if (isFoldableGEP) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00007311 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner061718c2004-10-16 19:44:59 +00007312 std::vector<Value*>(I->op_begin()+1, I->op_end()));
7313 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00007314 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00007315 C = ConstantExpr::getCast(C, I->getType());
7316 }
7317 }
7318
Chris Lattnerad5fec12005-01-28 19:32:01 +00007319 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7320
Chris Lattner62b14df2002-09-02 04:59:56 +00007321 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007322 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00007323 ReplaceInstUsesWith(*I, C);
7324
Chris Lattner62b14df2002-09-02 04:59:56 +00007325 ++NumConstProp;
Chris Lattner4bb7c022003-10-06 17:11:01 +00007326 I->getParent()->getInstList().erase(I);
Chris Lattner60610002003-10-07 15:17:02 +00007327 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007328 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00007329 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00007330
Chris Lattnerea1c4542004-12-08 23:43:58 +00007331 // See if we can trivially sink this instruction to a successor basic block.
7332 if (I->hasOneUse()) {
7333 BasicBlock *BB = I->getParent();
7334 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7335 if (UserParent != BB) {
7336 bool UserIsSuccessor = false;
7337 // See if the user is one of our successors.
7338 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7339 if (*SI == UserParent) {
7340 UserIsSuccessor = true;
7341 break;
7342 }
7343
7344 // If the user is one of our immediate successors, and if that successor
7345 // only has us as a predecessors (we'd have to split the critical edge
7346 // otherwise), we can keep going.
7347 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7348 next(pred_begin(UserParent)) == pred_end(UserParent))
7349 // Okay, the CFG is simple enough, try to sink this instruction.
7350 Changed |= TryToSinkInstruction(I, UserParent);
7351 }
7352 }
7353
Chris Lattner8a2a3112001-12-14 16:52:21 +00007354 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00007355 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00007356 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007357 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00007358 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00007359 DEBUG(std::cerr << "IC: Old = " << *I
7360 << " New = " << *Result);
7361
Chris Lattnerf523d062004-06-09 05:08:07 +00007362 // Everything uses the new instruction now.
7363 I->replaceAllUsesWith(Result);
7364
7365 // Push the new instruction and any users onto the worklist.
7366 WorkList.push_back(Result);
7367 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007368
7369 // Move the name to the new instruction first...
7370 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00007371 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007372
7373 // Insert the new instruction into the basic block...
7374 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00007375 BasicBlock::iterator InsertPos = I;
7376
7377 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7378 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7379 ++InsertPos;
7380
7381 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007382
Chris Lattner00d51312004-05-01 23:27:23 +00007383 // Make sure that we reprocess all operands now that we reduced their
7384 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00007385 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7386 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7387 WorkList.push_back(OpI);
7388
Chris Lattnerf523d062004-06-09 05:08:07 +00007389 // Instructions can end up on the worklist more than once. Make sure
7390 // we do not process an instruction that has been deleted.
7391 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007392
7393 // Erase the old instruction.
7394 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00007395 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00007396 DEBUG(std::cerr << "IC: MOD = " << *I);
7397
Chris Lattner90ac28c2002-08-02 19:29:35 +00007398 // If the instruction was modified, it's possible that it is now dead.
7399 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00007400 if (isInstructionTriviallyDead(I)) {
7401 // Make sure we process all operands now that we are reducing their
7402 // use counts.
7403 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7404 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7405 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00007406
Chris Lattner00d51312004-05-01 23:27:23 +00007407 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007408 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00007409 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00007410 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00007411 } else {
7412 WorkList.push_back(Result);
7413 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00007414 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00007415 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007416 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007417 }
7418 }
7419
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007420 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00007421}
7422
Brian Gaeke96d4bf72004-07-27 17:43:21 +00007423FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007424 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00007425}
Brian Gaeked0fde302003-11-11 22:41:34 +00007426