blob: aabc3e558dd961cb28c00653e46f598b5850f84c [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"
Reid Spencer551ccae2004-09-01 22:55:40 +000051#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000053#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000054#include <iostream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000055using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000056using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000057
Chris Lattnerdd841ae2002-04-18 17:39:14 +000058namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000059 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner9ca96412006-02-08 03:25:32 +000062 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattnerea1c4542004-12-08 23:43:58 +000063 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000064
Chris Lattnerf57b8452002-04-27 06:56:12 +000065 class InstCombiner : public FunctionPass,
Chris Lattnerdd841ae2002-04-18 17:39:14 +000066 public InstVisitor<InstCombiner, Instruction*> {
67 // Worklist of all of the instructions that need to be simplified.
68 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000069 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000070
Chris Lattner7bcc0e72004-02-28 05:22:00 +000071 /// AddUsersToWorkList - When an instruction is simplified, add all users of
72 /// the instruction to the work lists because they might get more simplified
73 /// now.
74 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +000075 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000076 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000077 UI != UE; ++UI)
78 WorkList.push_back(cast<Instruction>(*UI));
79 }
80
Chris Lattner7bcc0e72004-02-28 05:22:00 +000081 /// AddUsesToWorkList - When an instruction is simplified, add operands to
82 /// the work lists because they might get more simplified now.
83 ///
84 void AddUsesToWorkList(Instruction &I) {
85 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
86 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
87 WorkList.push_back(Op);
88 }
89
Chris Lattner62b14df2002-09-02 04:59:56 +000090 // removeFromWorkList - remove all instances of I from the worklist.
91 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000092 public:
Chris Lattner7e708292002-06-25 16:13:24 +000093 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +000094
Chris Lattner97e52e42002-04-28 21:27:06 +000095 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +000096 AU.addRequired<TargetData>();
Chris Lattnercb2610e2002-10-21 20:00:28 +000097 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +000098 }
99
Chris Lattner28977af2004-04-05 01:30:19 +0000100 TargetData &getTargetData() const { return *TD; }
101
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000102 // Visitation implementation - Implement instruction combining for different
103 // instruction types. The semantics are as follows:
104 // Return Value:
105 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000106 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000107 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000108 //
Chris Lattner7e708292002-06-25 16:13:24 +0000109 Instruction *visitAdd(BinaryOperator &I);
110 Instruction *visitSub(BinaryOperator &I);
111 Instruction *visitMul(BinaryOperator &I);
112 Instruction *visitDiv(BinaryOperator &I);
113 Instruction *visitRem(BinaryOperator &I);
114 Instruction *visitAnd(BinaryOperator &I);
115 Instruction *visitOr (BinaryOperator &I);
116 Instruction *visitXor(BinaryOperator &I);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000117 Instruction *visitSetCondInst(SetCondInst &I);
118 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
119
Chris Lattner574da9b2005-01-13 20:14:25 +0000120 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
121 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000122 Instruction *visitShiftInst(ShiftInst &I);
Chris Lattner4d5542c2006-01-06 07:12:35 +0000123 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
124 ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000125 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000126 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
127 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000128 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000129 Instruction *visitCallInst(CallInst &CI);
130 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000131 Instruction *visitPHINode(PHINode &PN);
132 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000133 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000134 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000135 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000136 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000137 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000138 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000139 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000141 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000142
143 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000144 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000145
Chris Lattner9fe38862003-06-19 17:00:31 +0000146 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000147 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000148 bool transformConstExprCastCall(CallSite CS);
149
Chris Lattner28977af2004-04-05 01:30:19 +0000150 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000151 // InsertNewInstBefore - insert an instruction New before instruction Old
152 // in the program. Add the new instruction to the worklist.
153 //
Chris Lattner955f3312004-09-28 21:48:02 +0000154 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000155 assert(New && New->getParent() == 0 &&
156 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000157 BasicBlock *BB = Old.getParent();
158 BB->getInstList().insert(&Old, New); // Insert inst
159 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000160 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000161 }
162
Chris Lattner0c967662004-09-24 15:21:34 +0000163 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
164 /// This also adds the cast to the worklist. Finally, this returns the
165 /// cast.
166 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
167 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000168
Chris Lattnere2ed0572006-04-06 19:19:17 +0000169 if (Constant *CV = dyn_cast<Constant>(V))
170 return ConstantExpr::getCast(CV, Ty);
171
Chris Lattner0c967662004-09-24 15:21:34 +0000172 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
173 WorkList.push_back(C);
174 return C;
175 }
176
Chris Lattner8b170942002-08-09 23:47:40 +0000177 // ReplaceInstUsesWith - This method is to be used when an instruction is
178 // found to be dead, replacable with another preexisting expression. Here
179 // we add all uses of I to the worklist, replace all uses of I with the new
180 // value, then return I, so that the inst combiner will know that I was
181 // modified.
182 //
183 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000184 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000185 if (&I != V) {
186 I.replaceAllUsesWith(V);
187 return &I;
188 } else {
189 // If we are replacing the instruction with itself, this must be in a
190 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000191 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000192 return &I;
193 }
Chris Lattner8b170942002-08-09 23:47:40 +0000194 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000195
Chris Lattner6dce1a72006-02-07 06:56:34 +0000196 // UpdateValueUsesWith - This method is to be used when an value is
197 // found to be replacable with another preexisting expression or was
198 // updated. Here we add all uses of I to the worklist, replace all uses of
199 // I with the new value (unless the instruction was just updated), then
200 // return true, so that the inst combiner will know that I was modified.
201 //
202 bool UpdateValueUsesWith(Value *Old, Value *New) {
203 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
204 if (Old != New)
205 Old->replaceAllUsesWith(New);
206 if (Instruction *I = dyn_cast<Instruction>(Old))
207 WorkList.push_back(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000208 if (Instruction *I = dyn_cast<Instruction>(New))
209 WorkList.push_back(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000210 return true;
211 }
212
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000213 // EraseInstFromFunction - When dealing with an instruction that has side
214 // effects or produces a void value, we can't rely on DCE to delete the
215 // instruction. Instead, visit methods should return the value returned by
216 // this function.
217 Instruction *EraseInstFromFunction(Instruction &I) {
218 assert(I.use_empty() && "Cannot erase instruction that is used!");
219 AddUsesToWorkList(I);
220 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000221 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000222 return 0; // Don't do anything with FI
223 }
224
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000225 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000226 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
227 /// InsertBefore instruction. This is specialized a bit to avoid inserting
228 /// casts that are known to not do anything...
229 ///
230 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
231 Instruction *InsertBefore);
232
Chris Lattnerc8802d22003-03-11 00:12:48 +0000233 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000234 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000235 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000236
Chris Lattner255d8912006-02-11 09:31:47 +0000237 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
238 uint64_t &KnownZero, uint64_t &KnownOne,
239 unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000240
241 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
242 // PHI node as operand #0, see if we can fold the instruction into the PHI
243 // (which is only possible if all operands to the PHI are constants).
244 Instruction *FoldOpIntoPhi(Instruction &I);
245
Chris Lattnerbac32862004-11-14 19:13:23 +0000246 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
247 // operator and they all are only used by the PHI, PHI together their
248 // inputs, and do the operation once, to the result of the PHI.
249 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
250
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000251 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
252 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000253
254 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
255 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000256 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
257 bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000258 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000259 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000260
Chris Lattnera6275cc2002-07-26 21:12:46 +0000261 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000262}
263
Chris Lattner4f98c562003-03-10 21:43:22 +0000264// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000265// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000266static unsigned getComplexity(Value *V) {
267 if (isa<Instruction>(V)) {
268 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000269 return 3;
270 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000271 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000272 if (isa<Argument>(V)) return 3;
273 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000274}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000275
Chris Lattnerc8802d22003-03-11 00:12:48 +0000276// isOnlyUse - Return true if this instruction will be deleted if we stop using
277// it.
278static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000279 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000280}
281
Chris Lattner4cb170c2004-02-23 06:38:22 +0000282// getPromotedType - Return the specified type promoted as it would be to pass
283// though a va_arg area...
284static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000285 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000286 case Type::SByteTyID:
287 case Type::ShortTyID: return Type::IntTy;
288 case Type::UByteTyID:
289 case Type::UShortTyID: return Type::UIntTy;
290 case Type::FloatTyID: return Type::DoubleTy;
291 default: return Ty;
292 }
293}
294
Chris Lattnereed48272005-09-13 00:40:14 +0000295/// isCast - If the specified operand is a CastInst or a constant expr cast,
296/// return the operand value, otherwise return null.
297static Value *isCast(Value *V) {
298 if (CastInst *I = dyn_cast<CastInst>(V))
299 return I->getOperand(0);
300 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
301 if (CE->getOpcode() == Instruction::Cast)
302 return CE->getOperand(0);
303 return 0;
304}
305
Chris Lattner33a61132006-05-06 09:00:16 +0000306enum CastType {
307 Noop = 0,
308 Truncate = 1,
309 Signext = 2,
310 Zeroext = 3
311};
312
313/// getCastType - In the future, we will split the cast instruction into these
314/// various types. Until then, we have to do the analysis here.
315static CastType getCastType(const Type *Src, const Type *Dest) {
316 assert(Src->isIntegral() && Dest->isIntegral() &&
317 "Only works on integral types!");
318 unsigned SrcSize = Src->getPrimitiveSizeInBits();
319 unsigned DestSize = Dest->getPrimitiveSizeInBits();
320
321 if (SrcSize == DestSize) return Noop;
322 if (SrcSize > DestSize) return Truncate;
323 if (Src->isSigned()) return Signext;
324 return Zeroext;
325}
326
327
328// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
329// instruction.
330//
331static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
332 const Type *DstTy, TargetData *TD) {
333
334 // It is legal to eliminate the instruction if casting A->B->A if the sizes
335 // are identical and the bits don't get reinterpreted (for example
336 // int->float->int would not be allowed).
337 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
338 return true;
339
340 // If we are casting between pointer and integer types, treat pointers as
341 // integers of the appropriate size for the code below.
342 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
343 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
344 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
345
346 // Allow free casting and conversion of sizes as long as the sign doesn't
347 // change...
348 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
349 CastType FirstCast = getCastType(SrcTy, MidTy);
350 CastType SecondCast = getCastType(MidTy, DstTy);
351
352 // Capture the effect of these two casts. If the result is a legal cast,
353 // the CastType is stored here, otherwise a special code is used.
354 static const unsigned CastResult[] = {
355 // First cast is noop
356 0, 1, 2, 3,
357 // First cast is a truncate
358 1, 1, 4, 4, // trunc->extend is not safe to eliminate
359 // First cast is a sign ext
360 2, 5, 2, 4, // signext->zeroext never ok
361 // First cast is a zero ext
362 3, 5, 3, 3,
363 };
364
365 unsigned Result = CastResult[FirstCast*4+SecondCast];
366 switch (Result) {
367 default: assert(0 && "Illegal table value!");
368 case 0:
369 case 1:
370 case 2:
371 case 3:
372 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
373 // truncates, we could eliminate more casts.
374 return (unsigned)getCastType(SrcTy, DstTy) == Result;
375 case 4:
376 return false; // Not possible to eliminate this here.
377 case 5:
378 // Sign or zero extend followed by truncate is always ok if the result
379 // is a truncate or noop.
380 CastType ResultCast = getCastType(SrcTy, DstTy);
381 if (ResultCast == Noop || ResultCast == Truncate)
382 return true;
383 // Otherwise we are still growing the value, we are only safe if the
384 // result will match the sign/zeroextendness of the result.
385 return ResultCast == FirstCast;
386 }
387 }
388
389 // If this is a cast from 'float -> double -> integer', cast from
390 // 'float -> integer' directly, as the value isn't changed by the
391 // float->double conversion.
392 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
393 DstTy->isIntegral() &&
394 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
395 return true;
396
397 // Packed type conversions don't modify bits.
398 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
399 return true;
400
401 return false;
402}
403
404/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
405/// in any code being generated. It does not require codegen if V is simple
406/// enough or if the cast can be folded into other casts.
407static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
408 if (V->getType() == Ty || isa<Constant>(V)) return false;
409
410 // If this is a noop cast, it isn't real codegen.
411 if (V->getType()->isLosslesslyConvertibleTo(Ty))
412 return false;
413
414 // If this is another cast that can be elimianted, it isn't codegen either.
415 if (const CastInst *CI = dyn_cast<CastInst>(V))
416 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
417 TD))
418 return false;
419 return true;
420}
421
422/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
423/// InsertBefore instruction. This is specialized a bit to avoid inserting
424/// casts that are known to not do anything...
425///
426Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
427 Instruction *InsertBefore) {
428 if (V->getType() == DestTy) return V;
429 if (Constant *C = dyn_cast<Constant>(V))
430 return ConstantExpr::getCast(C, DestTy);
431
432 CastInst *CI = new CastInst(V, DestTy, V->getName());
433 InsertNewInstBefore(CI, *InsertBefore);
434 return CI;
435}
436
Chris Lattner4f98c562003-03-10 21:43:22 +0000437// SimplifyCommutative - This performs a few simplifications for commutative
438// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000439//
Chris Lattner4f98c562003-03-10 21:43:22 +0000440// 1. Order operands such that they are listed from right (least complex) to
441// left (most complex). This puts constants before unary operators before
442// binary operators.
443//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000444// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
445// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000446//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000447bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000448 bool Changed = false;
449 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
450 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000451
Chris Lattner4f98c562003-03-10 21:43:22 +0000452 if (!I.isAssociative()) return Changed;
453 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000454 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
455 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
456 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000457 Constant *Folded = ConstantExpr::get(I.getOpcode(),
458 cast<Constant>(I.getOperand(1)),
459 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000460 I.setOperand(0, Op->getOperand(0));
461 I.setOperand(1, Folded);
462 return true;
463 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
464 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
465 isOnlyUse(Op) && isOnlyUse(Op1)) {
466 Constant *C1 = cast<Constant>(Op->getOperand(1));
467 Constant *C2 = cast<Constant>(Op1->getOperand(1));
468
469 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000470 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000471 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
472 Op1->getOperand(0),
473 Op1->getName(), &I);
474 WorkList.push_back(New);
475 I.setOperand(0, New);
476 I.setOperand(1, Folded);
477 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000478 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000479 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000480 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000481}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000482
Chris Lattner8d969642003-03-10 23:06:50 +0000483// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
484// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000485//
Chris Lattner8d969642003-03-10 23:06:50 +0000486static inline Value *dyn_castNegVal(Value *V) {
487 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000488 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000489
Chris Lattner0ce85802004-12-14 20:08:06 +0000490 // Constants can be considered to be negated values if they can be folded.
491 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
492 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000493 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000494}
495
Chris Lattner8d969642003-03-10 23:06:50 +0000496static inline Value *dyn_castNotVal(Value *V) {
497 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000498 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000499
500 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000501 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000502 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000503 return 0;
504}
505
Chris Lattnerc8802d22003-03-11 00:12:48 +0000506// dyn_castFoldableMul - If this value is a multiply that can be folded into
507// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000508// non-constant operand of the multiply, and set CST to point to the multiplier.
509// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000510//
Chris Lattner50af16a2004-11-13 19:50:12 +0000511static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000512 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000513 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000514 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000515 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000516 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000517 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000518 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000519 // The multiplier is really 1 << CST.
520 Constant *One = ConstantInt::get(V->getType(), 1);
521 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
522 return I->getOperand(0);
523 }
524 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000525 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000526}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000527
Chris Lattner574da9b2005-01-13 20:14:25 +0000528/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
529/// expression, return it.
530static User *dyn_castGetElementPtr(Value *V) {
531 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
532 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
533 if (CE->getOpcode() == Instruction::GetElementPtr)
534 return cast<User>(V);
535 return false;
536}
537
Chris Lattner955f3312004-09-28 21:48:02 +0000538// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000539static ConstantInt *AddOne(ConstantInt *C) {
540 return cast<ConstantInt>(ConstantExpr::getAdd(C,
541 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000542}
Chris Lattnera96879a2004-09-29 17:40:11 +0000543static ConstantInt *SubOne(ConstantInt *C) {
544 return cast<ConstantInt>(ConstantExpr::getSub(C,
545 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000546}
547
Chris Lattner255d8912006-02-11 09:31:47 +0000548/// GetConstantInType - Return a ConstantInt with the specified type and value.
549///
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000550static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Chris Lattner255d8912006-02-11 09:31:47 +0000551 if (Ty->isUnsigned())
552 return ConstantUInt::get(Ty, Val);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000553 else if (Ty->getTypeID() == Type::BoolTyID)
554 return ConstantBool::get(Val);
Chris Lattner255d8912006-02-11 09:31:47 +0000555 int64_t SVal = Val;
556 SVal <<= 64-Ty->getPrimitiveSizeInBits();
557 SVal >>= 64-Ty->getPrimitiveSizeInBits();
558 return ConstantSInt::get(Ty, SVal);
559}
560
561
Chris Lattner68d5ff22006-02-09 07:38:58 +0000562/// ComputeMaskedBits - Determine which of the bits specified in Mask are
563/// known to be either zero or one and return them in the KnownZero/KnownOne
564/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
565/// processing.
566static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
567 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000568 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
569 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000570 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000571 // optimized based on the contradictory assumption that it is non-zero.
572 // Because instcombine aggressively folds operations with undef args anyway,
573 // this won't lose us code quality.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000574 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
575 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000576 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000577 KnownZero = ~KnownOne & Mask;
578 return;
579 }
580
581 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000582 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000583 return; // Limit search depth.
584
585 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000586 Instruction *I = dyn_cast<Instruction>(V);
587 if (!I) return;
588
Chris Lattnere3158302006-05-04 17:33:35 +0000589 Mask &= V->getType()->getIntegralTypeMask();
590
Chris Lattner255d8912006-02-11 09:31:47 +0000591 switch (I->getOpcode()) {
592 case Instruction::And:
593 // If either the LHS or the RHS are Zero, the result is zero.
594 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
595 Mask &= ~KnownZero;
596 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
597 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
598 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
599
600 // Output known-1 bits are only known if set in both the LHS & RHS.
601 KnownOne &= KnownOne2;
602 // Output known-0 are known to be clear if zero in either the LHS | RHS.
603 KnownZero |= KnownZero2;
604 return;
605 case Instruction::Or:
606 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
607 Mask &= ~KnownOne;
608 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
609 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
610 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
611
612 // Output known-0 bits are only known if clear in both the LHS & RHS.
613 KnownZero &= KnownZero2;
614 // Output known-1 are known to be set if set in either the LHS | RHS.
615 KnownOne |= KnownOne2;
616 return;
617 case Instruction::Xor: {
618 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
619 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
620 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
621 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
622
623 // Output known-0 bits are known if clear or set in both the LHS & RHS.
624 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
625 // Output known-1 are known to be set if set in only one of the LHS, RHS.
626 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
627 KnownZero = KnownZeroOut;
628 return;
629 }
630 case Instruction::Select:
631 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
632 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
633 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
634 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
635
636 // Only known if known in both the LHS and RHS.
637 KnownOne &= KnownOne2;
638 KnownZero &= KnownZero2;
639 return;
640 case Instruction::Cast: {
641 const Type *SrcTy = I->getOperand(0)->getType();
642 if (!SrcTy->isIntegral()) return;
643
644 // If this is an integer truncate or noop, just look in the input.
645 if (SrcTy->getPrimitiveSizeInBits() >=
646 I->getType()->getPrimitiveSizeInBits()) {
647 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000648 return;
649 }
Chris Lattner68d5ff22006-02-09 07:38:58 +0000650
Chris Lattner255d8912006-02-11 09:31:47 +0000651 // Sign or Zero extension. Compute the bits in the result that are not
652 // present in the input.
653 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
654 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000655
Chris Lattner255d8912006-02-11 09:31:47 +0000656 // Handle zero extension.
657 if (!SrcTy->isSigned()) {
658 Mask &= SrcTy->getIntegralTypeMask();
659 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
660 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
661 // The top bits are known to be zero.
662 KnownZero |= NewBits;
663 } else {
664 // Sign extension.
665 Mask &= SrcTy->getIntegralTypeMask();
666 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
667 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000668
Chris Lattner255d8912006-02-11 09:31:47 +0000669 // If the sign bit of the input is known set or clear, then we know the
670 // top bits of the result.
671 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
672 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner68d5ff22006-02-09 07:38:58 +0000673 KnownZero |= NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000674 KnownOne &= ~NewBits;
675 } else if (KnownOne & InSignBit) { // Input sign bit known set
676 KnownOne |= NewBits;
677 KnownZero &= ~NewBits;
678 } else { // Input sign bit unknown
679 KnownZero &= ~NewBits;
680 KnownOne &= ~NewBits;
681 }
682 }
683 return;
684 }
685 case Instruction::Shl:
686 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
687 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
688 Mask >>= SA->getValue();
689 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
690 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
691 KnownZero <<= SA->getValue();
692 KnownOne <<= SA->getValue();
693 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
694 return;
695 }
696 break;
697 case Instruction::Shr:
698 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
699 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
700 // Compute the new bits that are at the top now.
701 uint64_t HighBits = (1ULL << SA->getValue())-1;
702 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
703
704 if (I->getType()->isUnsigned()) { // Unsigned shift right.
705 Mask <<= SA->getValue();
706 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
707 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
708 KnownZero >>= SA->getValue();
709 KnownOne >>= SA->getValue();
710 KnownZero |= HighBits; // high bits known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000711 } else {
Chris Lattner255d8912006-02-11 09:31:47 +0000712 Mask <<= SA->getValue();
713 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
714 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
715 KnownZero >>= SA->getValue();
716 KnownOne >>= SA->getValue();
717
718 // Handle the sign bits.
719 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
720 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
721
722 if (KnownZero & SignBit) { // New bits are known zero.
723 KnownZero |= HighBits;
724 } else if (KnownOne & SignBit) { // New bits are known one.
725 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000726 }
727 }
728 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000729 }
Chris Lattner255d8912006-02-11 09:31:47 +0000730 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000731 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000732}
733
734/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
735/// this predicate to simplify operations downstream. Mask is known to be zero
736/// for bits that V cannot have.
737static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000738 uint64_t KnownZero, KnownOne;
739 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
740 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
741 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000742}
743
Chris Lattner255d8912006-02-11 09:31:47 +0000744/// ShrinkDemandedConstant - Check to see if the specified operand of the
745/// specified instruction is a constant integer. If so, check to see if there
746/// are any bits set in the constant that are not demanded. If so, shrink the
747/// constant and return true.
748static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
749 uint64_t Demanded) {
750 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
751 if (!OpC) return false;
752
753 // If there are no bits set that aren't demanded, nothing to do.
754 if ((~Demanded & OpC->getZExtValue()) == 0)
755 return false;
756
757 // This is producing any bits that are not needed, shrink the RHS.
758 uint64_t Val = Demanded & OpC->getZExtValue();
759 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
760 return true;
761}
762
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000763// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
764// set of known zero and one bits, compute the maximum and minimum values that
765// could have the specified known zero and known one bits, returning them in
766// min/max.
767static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
768 uint64_t KnownZero,
769 uint64_t KnownOne,
770 int64_t &Min, int64_t &Max) {
771 uint64_t TypeBits = Ty->getIntegralTypeMask();
772 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
773
774 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
775
776 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
777 // bit if it is unknown.
778 Min = KnownOne;
779 Max = KnownOne|UnknownBits;
780
781 if (SignBit & UnknownBits) { // Sign bit is unknown
782 Min |= SignBit;
783 Max &= ~SignBit;
784 }
785
786 // Sign extend the min/max values.
787 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
788 Min = (Min << ShAmt) >> ShAmt;
789 Max = (Max << ShAmt) >> ShAmt;
790}
791
792// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
793// a set of known zero and one bits, compute the maximum and minimum values that
794// could have the specified known zero and known one bits, returning them in
795// min/max.
796static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
797 uint64_t KnownZero,
798 uint64_t KnownOne,
799 uint64_t &Min,
800 uint64_t &Max) {
801 uint64_t TypeBits = Ty->getIntegralTypeMask();
802 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
803
804 // The minimum value is when the unknown bits are all zeros.
805 Min = KnownOne;
806 // The maximum value is when the unknown bits are all ones.
807 Max = KnownOne|UnknownBits;
808}
Chris Lattner255d8912006-02-11 09:31:47 +0000809
810
811/// SimplifyDemandedBits - Look at V. At this point, we know that only the
812/// DemandedMask bits of the result of V are ever used downstream. If we can
813/// use this information to simplify V, do so and return true. Otherwise,
814/// analyze the expression and return a mask of KnownOne and KnownZero bits for
815/// the expression (used to simplify the caller). The KnownZero/One bits may
816/// only be accurate for those bits in the DemandedMask.
817bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
818 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +0000819 unsigned Depth) {
Chris Lattner255d8912006-02-11 09:31:47 +0000820 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
821 // We know all of the bits for a constant!
822 KnownOne = CI->getZExtValue() & DemandedMask;
823 KnownZero = ~KnownOne & DemandedMask;
824 return false;
825 }
826
827 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000828 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +0000829 if (Depth != 0) { // Not at the root.
830 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
831 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000832 return false;
Chris Lattner255d8912006-02-11 09:31:47 +0000833 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000834 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +0000835 // just set the DemandedMask to all bits.
836 DemandedMask = V->getType()->getIntegralTypeMask();
837 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner74c51a02006-02-07 08:05:22 +0000838 if (V != UndefValue::get(V->getType()))
839 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
840 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000841 } else if (Depth == 6) { // Limit search depth.
842 return false;
843 }
844
845 Instruction *I = dyn_cast<Instruction>(V);
846 if (!I) return false; // Only analyze instructions.
847
Chris Lattnere3158302006-05-04 17:33:35 +0000848 DemandedMask &= V->getType()->getIntegralTypeMask();
849
Chris Lattner255d8912006-02-11 09:31:47 +0000850 uint64_t KnownZero2, KnownOne2;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000851 switch (I->getOpcode()) {
852 default: break;
853 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +0000854 // If either the LHS or the RHS are Zero, the result is zero.
855 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
856 KnownZero, KnownOne, Depth+1))
857 return true;
858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
859
860 // If something is known zero on the RHS, the bits aren't demanded on the
861 // LHS.
862 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
863 KnownZero2, KnownOne2, Depth+1))
864 return true;
865 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
866
867 // If all of the demanded bits are known one on one side, return the other.
868 // These bits cannot contribute to the result of the 'and'.
869 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
870 return UpdateValueUsesWith(I, I->getOperand(0));
871 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
872 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000873
874 // If all of the demanded bits in the inputs are known zeros, return zero.
875 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
876 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
877
Chris Lattner255d8912006-02-11 09:31:47 +0000878 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000879 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +0000880 return UpdateValueUsesWith(I, I);
881
882 // Output known-1 bits are only known if set in both the LHS & RHS.
883 KnownOne &= KnownOne2;
884 // Output known-0 are known to be clear if zero in either the LHS | RHS.
885 KnownZero |= KnownZero2;
886 break;
887 case Instruction::Or:
888 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
889 KnownZero, KnownOne, Depth+1))
890 return true;
891 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
892 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
893 KnownZero2, KnownOne2, Depth+1))
894 return true;
895 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
896
897 // If all of the demanded bits are known zero on one side, return the other.
898 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +0000899 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +0000900 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +0000901 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +0000902 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000903
904 // If all of the potentially set bits on one side are known to be set on
905 // the other side, just use the 'other' side.
906 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
907 (DemandedMask & (~KnownZero)))
908 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +0000909 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
910 (DemandedMask & (~KnownZero2)))
911 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +0000912
913 // If the RHS is a constant, see if we can simplify it.
914 if (ShrinkDemandedConstant(I, 1, DemandedMask))
915 return UpdateValueUsesWith(I, I);
916
917 // Output known-0 bits are only known if clear in both the LHS & RHS.
918 KnownZero &= KnownZero2;
919 // Output known-1 are known to be set if set in either the LHS | RHS.
920 KnownOne |= KnownOne2;
921 break;
922 case Instruction::Xor: {
923 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
924 KnownZero, KnownOne, Depth+1))
925 return true;
926 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
927 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
928 KnownZero2, KnownOne2, Depth+1))
929 return true;
930 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
931
932 // If all of the demanded bits are known zero on one side, return the other.
933 // These bits cannot contribute to the result of the 'xor'.
934 if ((DemandedMask & KnownZero) == DemandedMask)
935 return UpdateValueUsesWith(I, I->getOperand(0));
936 if ((DemandedMask & KnownZero2) == DemandedMask)
937 return UpdateValueUsesWith(I, I->getOperand(1));
938
939 // Output known-0 bits are known if clear or set in both the LHS & RHS.
940 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
941 // Output known-1 are known to be set if set in only one of the LHS, RHS.
942 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
943
944 // If all of the unknown bits are known to be zero on one side or the other
945 // (but not both) turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000946 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner255d8912006-02-11 09:31:47 +0000947 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
948 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
949 Instruction *Or =
950 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
951 I->getName());
952 InsertNewInstBefore(Or, *I);
953 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000954 }
955 }
Chris Lattner255d8912006-02-11 09:31:47 +0000956
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000957 // If all of the demanded bits on one side are known, and all of the set
958 // bits on that side are also known to be set on the other side, turn this
959 // into an AND, as we know the bits will be cleared.
960 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
961 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
962 if ((KnownOne & KnownOne2) == KnownOne) {
963 Constant *AndC = GetConstantInType(I->getType(),
964 ~KnownOne & DemandedMask);
965 Instruction *And =
966 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
967 InsertNewInstBefore(And, *I);
968 return UpdateValueUsesWith(I, And);
969 }
970 }
971
Chris Lattner255d8912006-02-11 09:31:47 +0000972 // If the RHS is a constant, see if we can simplify it.
973 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
974 if (ShrinkDemandedConstant(I, 1, DemandedMask))
975 return UpdateValueUsesWith(I, I);
976
977 KnownZero = KnownZeroOut;
978 KnownOne = KnownOneOut;
979 break;
980 }
981 case Instruction::Select:
982 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
983 KnownZero, KnownOne, Depth+1))
984 return true;
985 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
986 KnownZero2, KnownOne2, Depth+1))
987 return true;
988 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
989 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
990
991 // If the operands are constants, see if we can simplify them.
992 if (ShrinkDemandedConstant(I, 1, DemandedMask))
993 return UpdateValueUsesWith(I, I);
994 if (ShrinkDemandedConstant(I, 2, DemandedMask))
995 return UpdateValueUsesWith(I, I);
996
997 // Only known if known in both the LHS and RHS.
998 KnownOne &= KnownOne2;
999 KnownZero &= KnownZero2;
1000 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001001 case Instruction::Cast: {
1002 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +00001003 if (!SrcTy->isIntegral()) return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001004
Chris Lattner255d8912006-02-11 09:31:47 +00001005 // If this is an integer truncate or noop, just look in the input.
1006 if (SrcTy->getPrimitiveSizeInBits() >=
1007 I->getType()->getPrimitiveSizeInBits()) {
1008 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009 KnownZero, KnownOne, Depth+1))
1010 return true;
1011 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1012 break;
1013 }
1014
1015 // Sign or Zero extension. Compute the bits in the result that are not
1016 // present in the input.
1017 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1018 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1019
1020 // Handle zero extension.
1021 if (!SrcTy->isSigned()) {
1022 DemandedMask &= SrcTy->getIntegralTypeMask();
1023 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1024 KnownZero, KnownOne, Depth+1))
1025 return true;
1026 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1027 // The top bits are known to be zero.
1028 KnownZero |= NewBits;
1029 } else {
1030 // Sign extension.
Chris Lattnerf345fe42006-02-13 22:41:07 +00001031 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1032 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1033
1034 // If any of the sign extended bits are demanded, we know that the sign
1035 // bit is demanded.
1036 if (NewBits & DemandedMask)
1037 InputDemandedBits |= InSignBit;
1038
1039 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner255d8912006-02-11 09:31:47 +00001040 KnownZero, KnownOne, Depth+1))
1041 return true;
1042 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1043
1044 // If the sign bit of the input is known set or clear, then we know the
1045 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +00001046
Chris Lattner255d8912006-02-11 09:31:47 +00001047 // If the input sign bit is known zero, or if the NewBits are not demanded
1048 // convert this into a zero extension.
1049 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner6dce1a72006-02-07 06:56:34 +00001050 // Convert to unsigned first.
Chris Lattnerd89d8882006-02-07 19:07:40 +00001051 Instruction *NewVal;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001052 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattnerd89d8882006-02-07 19:07:40 +00001053 I->getOperand(0)->getName());
1054 InsertNewInstBefore(NewVal, *I);
Chris Lattner255d8912006-02-11 09:31:47 +00001055 // Then cast that to the destination type.
Chris Lattnerd89d8882006-02-07 19:07:40 +00001056 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1057 InsertNewInstBefore(NewVal, *I);
Chris Lattner6dce1a72006-02-07 06:56:34 +00001058 return UpdateValueUsesWith(I, NewVal);
Chris Lattner255d8912006-02-11 09:31:47 +00001059 } else if (KnownOne & InSignBit) { // Input sign bit known set
1060 KnownOne |= NewBits;
1061 KnownZero &= ~NewBits;
1062 } else { // Input sign bit unknown
1063 KnownZero &= ~NewBits;
1064 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001065 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001066 }
Chris Lattner255d8912006-02-11 09:31:47 +00001067 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001068 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001069 case Instruction::Shl:
Chris Lattner255d8912006-02-11 09:31:47 +00001070 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1071 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1072 KnownZero, KnownOne, Depth+1))
1073 return true;
1074 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1075 KnownZero <<= SA->getValue();
1076 KnownOne <<= SA->getValue();
1077 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1078 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001079 break;
1080 case Instruction::Shr:
Chris Lattner255d8912006-02-11 09:31:47 +00001081 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1082 unsigned ShAmt = SA->getValue();
1083
1084 // Compute the new bits that are at the top now.
1085 uint64_t HighBits = (1ULL << ShAmt)-1;
1086 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
Chris Lattnerc15637b2006-02-13 06:09:08 +00001087 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner255d8912006-02-11 09:31:47 +00001088 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +00001089 if (SimplifyDemandedBits(I->getOperand(0),
1090 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +00001091 KnownZero, KnownOne, Depth+1))
1092 return true;
1093 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +00001094 KnownZero &= TypeMask;
1095 KnownOne &= TypeMask;
Chris Lattner255d8912006-02-11 09:31:47 +00001096 KnownZero >>= ShAmt;
1097 KnownOne >>= ShAmt;
1098 KnownZero |= HighBits; // high bits known zero.
1099 } else { // Signed shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +00001100 if (SimplifyDemandedBits(I->getOperand(0),
1101 (DemandedMask << ShAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +00001102 KnownZero, KnownOne, Depth+1))
1103 return true;
1104 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +00001105 KnownZero &= TypeMask;
1106 KnownOne &= TypeMask;
Chris Lattner255d8912006-02-11 09:31:47 +00001107 KnownZero >>= SA->getValue();
1108 KnownOne >>= SA->getValue();
1109
1110 // Handle the sign bits.
1111 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1112 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1113
1114 // If the input sign bit is known to be zero, or if none of the top bits
1115 // are demanded, turn this into an unsigned shift right.
1116 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1117 // Convert the input to unsigned.
1118 Instruction *NewVal;
1119 NewVal = new CastInst(I->getOperand(0),
1120 I->getType()->getUnsignedVersion(),
1121 I->getOperand(0)->getName());
1122 InsertNewInstBefore(NewVal, *I);
1123 // Perform the unsigned shift right.
1124 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1125 InsertNewInstBefore(NewVal, *I);
1126 // Then cast that to the destination type.
1127 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1128 InsertNewInstBefore(NewVal, *I);
1129 return UpdateValueUsesWith(I, NewVal);
1130 } else if (KnownOne & SignBit) { // New bits are known one.
1131 KnownOne |= HighBits;
1132 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001133 }
Chris Lattner255d8912006-02-11 09:31:47 +00001134 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001135 break;
1136 }
Chris Lattner255d8912006-02-11 09:31:47 +00001137
1138 // If the client is only demanding bits that we know, return the known
1139 // constant.
1140 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1141 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001142 return false;
1143}
1144
Chris Lattner955f3312004-09-28 21:48:02 +00001145// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1146// true when both operands are equal...
1147//
1148static bool isTrueWhenEqual(Instruction &I) {
1149 return I.getOpcode() == Instruction::SetEQ ||
1150 I.getOpcode() == Instruction::SetGE ||
1151 I.getOpcode() == Instruction::SetLE;
1152}
Chris Lattner564a7272003-08-13 19:01:45 +00001153
1154/// AssociativeOpt - Perform an optimization on an associative operator. This
1155/// function is designed to check a chain of associative operators for a
1156/// potential to apply a certain optimization. Since the optimization may be
1157/// applicable if the expression was reassociated, this checks the chain, then
1158/// reassociates the expression as necessary to expose the optimization
1159/// opportunity. This makes use of a special Functor, which must define
1160/// 'shouldApply' and 'apply' methods.
1161///
1162template<typename Functor>
1163Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1164 unsigned Opcode = Root.getOpcode();
1165 Value *LHS = Root.getOperand(0);
1166
1167 // Quick check, see if the immediate LHS matches...
1168 if (F.shouldApply(LHS))
1169 return F.apply(Root);
1170
1171 // Otherwise, if the LHS is not of the same opcode as the root, return.
1172 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001173 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001174 // Should we apply this transform to the RHS?
1175 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1176
1177 // If not to the RHS, check to see if we should apply to the LHS...
1178 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1179 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1180 ShouldApply = true;
1181 }
1182
1183 // If the functor wants to apply the optimization to the RHS of LHSI,
1184 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1185 if (ShouldApply) {
1186 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001187
Chris Lattner564a7272003-08-13 19:01:45 +00001188 // Now all of the instructions are in the current basic block, go ahead
1189 // and perform the reassociation.
1190 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1191
1192 // First move the selected RHS to the LHS of the root...
1193 Root.setOperand(0, LHSI->getOperand(1));
1194
1195 // Make what used to be the LHS of the root be the user of the root...
1196 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001197 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001198 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1199 return 0;
1200 }
Chris Lattner65725312004-04-16 18:08:07 +00001201 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001202 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001203 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1204 BasicBlock::iterator ARI = &Root; ++ARI;
1205 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1206 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001207
1208 // Now propagate the ExtraOperand down the chain of instructions until we
1209 // get to LHSI.
1210 while (TmpLHSI != LHSI) {
1211 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001212 // Move the instruction to immediately before the chain we are
1213 // constructing to avoid breaking dominance properties.
1214 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1215 BB->getInstList().insert(ARI, NextLHSI);
1216 ARI = NextLHSI;
1217
Chris Lattner564a7272003-08-13 19:01:45 +00001218 Value *NextOp = NextLHSI->getOperand(1);
1219 NextLHSI->setOperand(1, ExtraOperand);
1220 TmpLHSI = NextLHSI;
1221 ExtraOperand = NextOp;
1222 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001223
Chris Lattner564a7272003-08-13 19:01:45 +00001224 // Now that the instructions are reassociated, have the functor perform
1225 // the transformation...
1226 return F.apply(Root);
1227 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001228
Chris Lattner564a7272003-08-13 19:01:45 +00001229 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1230 }
1231 return 0;
1232}
1233
1234
1235// AddRHS - Implements: X + X --> X << 1
1236struct AddRHS {
1237 Value *RHS;
1238 AddRHS(Value *rhs) : RHS(rhs) {}
1239 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1240 Instruction *apply(BinaryOperator &Add) const {
1241 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1242 ConstantInt::get(Type::UByteTy, 1));
1243 }
1244};
1245
1246// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1247// iff C1&C2 == 0
1248struct AddMaskingAnd {
1249 Constant *C2;
1250 AddMaskingAnd(Constant *c) : C2(c) {}
1251 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001252 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001253 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001254 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001255 }
1256 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001257 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001258 }
1259};
1260
Chris Lattner6e7ba452005-01-01 16:22:27 +00001261static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001262 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001263 if (isa<CastInst>(I)) {
1264 if (Constant *SOC = dyn_cast<Constant>(SO))
1265 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001266
Chris Lattner6e7ba452005-01-01 16:22:27 +00001267 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1268 SO->getName() + ".cast"), I);
1269 }
1270
Chris Lattner2eefe512004-04-09 19:05:30 +00001271 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001272 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1273 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001274
Chris Lattner2eefe512004-04-09 19:05:30 +00001275 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1276 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001277 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1278 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001279 }
1280
1281 Value *Op0 = SO, *Op1 = ConstOperand;
1282 if (!ConstIsRHS)
1283 std::swap(Op0, Op1);
1284 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001285 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1286 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1287 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1288 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +00001289 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001290 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001291 abort();
1292 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001293 return IC->InsertNewInstBefore(New, I);
1294}
1295
1296// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1297// constant as the other operand, try to fold the binary operator into the
1298// select arguments. This also works for Cast instructions, which obviously do
1299// not have a second operand.
1300static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1301 InstCombiner *IC) {
1302 // Don't modify shared select instructions
1303 if (!SI->hasOneUse()) return 0;
1304 Value *TV = SI->getOperand(1);
1305 Value *FV = SI->getOperand(2);
1306
1307 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001308 // Bool selects with constant operands can be folded to logical ops.
1309 if (SI->getType() == Type::BoolTy) return 0;
1310
Chris Lattner6e7ba452005-01-01 16:22:27 +00001311 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1312 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1313
1314 return new SelectInst(SI->getCondition(), SelectTrueVal,
1315 SelectFalseVal);
1316 }
1317 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001318}
1319
Chris Lattner4e998b22004-09-29 05:07:12 +00001320
1321/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1322/// node as operand #0, see if we can fold the instruction into the PHI (which
1323/// is only possible if all operands to the PHI are constants).
1324Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1325 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001326 unsigned NumPHIValues = PN->getNumIncomingValues();
1327 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1328 !isa<Constant>(PN->getIncomingValue(0))) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001329
1330 // Check to see if all of the operands of the PHI are constants. If not, we
1331 // cannot do the transformation.
Chris Lattnerbac32862004-11-14 19:13:23 +00001332 for (unsigned i = 1; i != NumPHIValues; ++i)
Chris Lattner4e998b22004-09-29 05:07:12 +00001333 if (!isa<Constant>(PN->getIncomingValue(i)))
1334 return 0;
1335
1336 // Okay, we can do the transformation: create the new PHI node.
1337 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1338 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +00001339 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001340 InsertNewInstBefore(NewPN, *PN);
1341
1342 // Next, add all of the operands to the PHI.
1343 if (I.getNumOperands() == 2) {
1344 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001345 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001346 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1347 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1348 PN->getIncomingBlock(i));
1349 }
1350 } else {
1351 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1352 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001353 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner4e998b22004-09-29 05:07:12 +00001354 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1355 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1356 PN->getIncomingBlock(i));
1357 }
1358 }
1359 return ReplaceInstUsesWith(I, NewPN);
1360}
1361
Chris Lattner7e708292002-06-25 16:13:24 +00001362Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001363 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001364 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001365
Chris Lattner66331a42004-04-10 22:01:55 +00001366 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001367 // X + undef -> undef
1368 if (isa<UndefValue>(RHS))
1369 return ReplaceInstUsesWith(I, RHS);
1370
Chris Lattner66331a42004-04-10 22:01:55 +00001371 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +00001372 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1373 if (RHSC->isNullValue())
1374 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001375 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1376 if (CFP->isExactlyValue(-0.0))
1377 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001378 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001379
Chris Lattner66331a42004-04-10 22:01:55 +00001380 // X + (signbit) --> X ^ signbit
1381 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner74c51a02006-02-07 08:05:22 +00001382 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00001383 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001384 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +00001385 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001386
1387 if (isa<PHINode>(LHS))
1388 if (Instruction *NV = FoldOpIntoPhi(I))
1389 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001390
Chris Lattner4f637d42006-01-06 17:59:59 +00001391 ConstantInt *XorRHS = 0;
1392 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +00001393 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1394 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1395 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1396 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1397
1398 uint64_t C0080Val = 1ULL << 31;
1399 int64_t CFF80Val = -C0080Val;
1400 unsigned Size = 32;
1401 do {
1402 if (TySizeBits > Size) {
1403 bool Found = false;
1404 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1405 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1406 if (RHSSExt == CFF80Val) {
1407 if (XorRHS->getZExtValue() == C0080Val)
1408 Found = true;
1409 } else if (RHSZExt == C0080Val) {
1410 if (XorRHS->getSExtValue() == CFF80Val)
1411 Found = true;
1412 }
1413 if (Found) {
1414 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00001415 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00001416 Mask <<= 64-(TySizeBits-Size);
Chris Lattner68d5ff22006-02-09 07:38:58 +00001417 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00001418 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00001419 Size = 0; // Not a sign ext, but can't be any others either.
1420 goto FoundSExt;
1421 }
1422 }
1423 Size >>= 1;
1424 C0080Val >>= Size;
1425 CFF80Val >>= Size;
1426 } while (Size >= 8);
1427
1428FoundSExt:
1429 const Type *MiddleType = 0;
1430 switch (Size) {
1431 default: break;
1432 case 32: MiddleType = Type::IntTy; break;
1433 case 16: MiddleType = Type::ShortTy; break;
1434 case 8: MiddleType = Type::SByteTy; break;
1435 }
1436 if (MiddleType) {
1437 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1438 InsertNewInstBefore(NewTrunc, I);
1439 return new CastInst(NewTrunc, I.getType());
1440 }
1441 }
Chris Lattner66331a42004-04-10 22:01:55 +00001442 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001443
Chris Lattner564a7272003-08-13 19:01:45 +00001444 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +00001445 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001446 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001447
1448 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1449 if (RHSI->getOpcode() == Instruction::Sub)
1450 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1451 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1452 }
1453 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1454 if (LHSI->getOpcode() == Instruction::Sub)
1455 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1456 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1457 }
Robert Bocchino71698282004-07-27 21:02:21 +00001458 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001459
Chris Lattner5c4afb92002-05-08 22:46:53 +00001460 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00001461 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001462 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001463
1464 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001465 if (!isa<Constant>(RHS))
1466 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001467 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001468
Misha Brukmanfd939082005-04-21 23:48:37 +00001469
Chris Lattner50af16a2004-11-13 19:50:12 +00001470 ConstantInt *C2;
1471 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1472 if (X == RHS) // X*C + X --> X * (C+1)
1473 return BinaryOperator::createMul(RHS, AddOne(C2));
1474
1475 // X*C1 + X*C2 --> X * (C1+C2)
1476 ConstantInt *C1;
1477 if (X == dyn_castFoldableMul(RHS, C1))
1478 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001479 }
1480
1481 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00001482 if (dyn_castFoldableMul(RHS, C2) == LHS)
1483 return BinaryOperator::createMul(LHS, AddOne(C2));
1484
Chris Lattnerad3448c2003-02-18 19:57:07 +00001485
Chris Lattner564a7272003-08-13 19:01:45 +00001486 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001487 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +00001488 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00001489
Chris Lattner6b032052003-10-02 15:11:26 +00001490 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001491 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001492 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1493 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1494 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00001495 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001496
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001497 // (X & FF00) + xx00 -> (X+xx00) & FF00
1498 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1499 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1500 if (Anded == CRHS) {
1501 // See if all bits from the first bit set in the Add RHS up are included
1502 // in the mask. First, get the rightmost bit.
1503 uint64_t AddRHSV = CRHS->getRawValue();
1504
1505 // Form a mask of all bits from the lowest bit added through the top.
1506 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +00001507 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001508
1509 // See if the and mask includes all of these bits.
1510 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001511
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001512 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1513 // Okay, the xform is safe. Insert the new add pronto.
1514 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1515 LHS->getName()), I);
1516 return BinaryOperator::createAnd(NewAdd, C2);
1517 }
1518 }
1519 }
1520
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001521 // Try to fold constant add into select arguments.
1522 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001523 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001524 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00001525 }
1526
Chris Lattner7e708292002-06-25 16:13:24 +00001527 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001528}
1529
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001530// isSignBit - Return true if the value represented by the constant only has the
1531// highest order bit set.
1532static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001533 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnerf52d6812005-04-24 17:46:05 +00001534 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001535}
1536
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001537/// RemoveNoopCast - Strip off nonconverting casts from the value.
1538///
1539static Value *RemoveNoopCast(Value *V) {
1540 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1541 const Type *CTy = CI->getType();
1542 const Type *OpTy = CI->getOperand(0)->getType();
1543 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001544 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001545 return RemoveNoopCast(CI->getOperand(0));
1546 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1547 return RemoveNoopCast(CI->getOperand(0));
1548 }
1549 return V;
1550}
1551
Chris Lattner7e708292002-06-25 16:13:24 +00001552Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001553 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001554
Chris Lattner233f7dc2002-08-12 21:17:25 +00001555 if (Op0 == Op1) // sub X, X -> 0
1556 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001557
Chris Lattner233f7dc2002-08-12 21:17:25 +00001558 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001559 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001560 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001561
Chris Lattnere87597f2004-10-16 18:11:37 +00001562 if (isa<UndefValue>(Op0))
1563 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1564 if (isa<UndefValue>(Op1))
1565 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1566
Chris Lattnerd65460f2003-11-05 01:06:05 +00001567 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1568 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001569 if (C->isAllOnesValue())
1570 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001571
Chris Lattnerd65460f2003-11-05 01:06:05 +00001572 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001573 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001574 if (match(Op1, m_Not(m_Value(X))))
1575 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001576 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001577 // -((uint)X >> 31) -> ((int)X >> 31)
1578 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001579 if (C->isNullValue()) {
1580 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1581 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +00001582 if (SI->getOpcode() == Instruction::Shr)
1583 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1584 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001585 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +00001586 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001587 else
Chris Lattner5dd04022004-06-17 18:16:02 +00001588 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001589 // Check to see if we are shifting out everything but the sign bit.
Chris Lattner484d3cf2005-04-24 06:59:08 +00001590 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +00001591 // Ok, the transformation is safe. Insert a cast of the incoming
1592 // value, then the new shift, then the new cast.
1593 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1594 SI->getOperand(0)->getName());
1595 Value *InV = InsertNewInstBefore(FirstCast, I);
1596 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1597 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001598 if (NewShift->getType() == I.getType())
1599 return NewShift;
1600 else {
1601 InV = InsertNewInstBefore(NewShift, I);
1602 return new CastInst(NewShift, I.getType());
1603 }
Chris Lattner9c290672004-03-12 23:53:13 +00001604 }
1605 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001606 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001607
1608 // Try to fold constant sub into select arguments.
1609 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001610 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001611 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001612
1613 if (isa<PHINode>(Op0))
1614 if (Instruction *NV = FoldOpIntoPhi(I))
1615 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00001616 }
1617
Chris Lattner43d84d62005-04-07 16:15:25 +00001618 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1619 if (Op1I->getOpcode() == Instruction::Add &&
1620 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +00001621 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001622 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001623 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001624 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001625 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1626 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1627 // C1-(X+C2) --> (C1-C2)-X
1628 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1629 Op1I->getOperand(0));
1630 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001631 }
1632
Chris Lattnerfd059242003-10-15 16:48:29 +00001633 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001634 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1635 // is not used by anyone else...
1636 //
Chris Lattner0517e722004-02-02 20:09:56 +00001637 if (Op1I->getOpcode() == Instruction::Sub &&
1638 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001639 // Swap the two operands of the subexpr...
1640 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1641 Op1I->setOperand(0, IIOp1);
1642 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001643
Chris Lattnera2881962003-02-18 19:28:33 +00001644 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00001645 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001646 }
1647
1648 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1649 //
1650 if (Op1I->getOpcode() == Instruction::And &&
1651 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1652 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1653
Chris Lattnerf523d062004-06-09 05:08:07 +00001654 Value *NewNot =
1655 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001656 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001657 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001658
Chris Lattner91ccc152004-10-06 15:08:25 +00001659 // -(X sdiv C) -> (X sdiv -C)
1660 if (Op1I->getOpcode() == Instruction::Div)
1661 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
Chris Lattner43d84d62005-04-07 16:15:25 +00001662 if (CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00001663 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +00001664 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00001665 ConstantExpr::getNeg(DivRHS));
1666
Chris Lattnerad3448c2003-02-18 19:57:07 +00001667 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001668 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00001669 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001670 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00001671 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00001672 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001673 }
Chris Lattner40371712002-05-09 01:29:19 +00001674 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001675 }
Chris Lattnera2881962003-02-18 19:28:33 +00001676
Chris Lattner7edc8c22005-04-07 17:14:51 +00001677 if (!Op0->getType()->isFloatingPoint())
1678 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1679 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001680 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1681 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1682 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1683 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00001684 } else if (Op0I->getOpcode() == Instruction::Sub) {
1685 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1686 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001687 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001688
Chris Lattner50af16a2004-11-13 19:50:12 +00001689 ConstantInt *C1;
1690 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1691 if (X == Op1) { // X*C - X --> X * (C-1)
1692 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1693 return BinaryOperator::createMul(Op1, CP1);
1694 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001695
Chris Lattner50af16a2004-11-13 19:50:12 +00001696 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1697 if (X == dyn_castFoldableMul(Op1, C2))
1698 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1699 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00001700 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001701}
1702
Chris Lattner4cb170c2004-02-23 06:38:22 +00001703/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1704/// really just returns true if the most significant (sign) bit is set.
1705static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1706 if (RHS->getType()->isSigned()) {
1707 // True if source is LHS < 0 or LHS <= -1
1708 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1709 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1710 } else {
1711 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1712 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1713 // the size of the integer type.
1714 if (Opcode == Instruction::SetGE)
Chris Lattner484d3cf2005-04-24 06:59:08 +00001715 return RHSC->getValue() ==
1716 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001717 if (Opcode == Instruction::SetGT)
1718 return RHSC->getValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00001719 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00001720 }
1721 return false;
1722}
1723
Chris Lattner7e708292002-06-25 16:13:24 +00001724Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001725 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00001726 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001727
Chris Lattnere87597f2004-10-16 18:11:37 +00001728 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1729 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1730
Chris Lattner233f7dc2002-08-12 21:17:25 +00001731 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00001732 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1733 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00001734
1735 // ((X << C1)*C2) == (X * (C2 << C1))
1736 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1737 if (SI->getOpcode() == Instruction::Shl)
1738 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001739 return BinaryOperator::createMul(SI->getOperand(0),
1740 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00001741
Chris Lattner515c97c2003-09-11 22:24:54 +00001742 if (CI->isNullValue())
1743 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1744 if (CI->equalsInt(1)) // X * 1 == X
1745 return ReplaceInstUsesWith(I, Op0);
1746 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00001747 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00001748
Chris Lattner515c97c2003-09-11 22:24:54 +00001749 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001750 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1751 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00001752 return new ShiftInst(Instruction::Shl, Op0,
1753 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001754 }
Robert Bocchino71698282004-07-27 21:02:21 +00001755 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00001756 if (Op1F->isNullValue())
1757 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00001758
Chris Lattnera2881962003-02-18 19:28:33 +00001759 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1760 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1761 if (Op1F->getValue() == 1.0)
1762 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1763 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00001764
1765 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1766 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1767 isa<ConstantInt>(Op0I->getOperand(1))) {
1768 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1769 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1770 Op1, "tmp");
1771 InsertNewInstBefore(Add, I);
1772 Value *C1C2 = ConstantExpr::getMul(Op1,
1773 cast<Constant>(Op0I->getOperand(1)));
1774 return BinaryOperator::createAdd(Add, C1C2);
1775
1776 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001777
1778 // Try to fold constant mul into select arguments.
1779 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001780 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001781 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001782
1783 if (isa<PHINode>(Op0))
1784 if (Instruction *NV = FoldOpIntoPhi(I))
1785 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001786 }
1787
Chris Lattnera4f445b2003-03-10 23:23:04 +00001788 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1789 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001790 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00001791
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001792 // If one of the operands of the multiply is a cast from a boolean value, then
1793 // we know the bool is either zero or one, so this is a 'masking' multiply.
1794 // See if we can simplify things based on how the boolean was originally
1795 // formed.
1796 CastInst *BoolCast = 0;
1797 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1798 if (CI->getOperand(0)->getType() == Type::BoolTy)
1799 BoolCast = CI;
1800 if (!BoolCast)
1801 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1802 if (CI->getOperand(0)->getType() == Type::BoolTy)
1803 BoolCast = CI;
1804 if (BoolCast) {
1805 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1806 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1807 const Type *SCOpTy = SCIOp0->getType();
1808
Chris Lattner4cb170c2004-02-23 06:38:22 +00001809 // If the setcc is true iff the sign bit of X is set, then convert this
1810 // multiply into a shift/and combination.
1811 if (isa<ConstantInt>(SCIOp1) &&
1812 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001813 // Shift the X value right to turn it into "all signbits".
1814 Constant *Amt = ConstantUInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00001815 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00001816 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00001817 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00001818 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1819 SCIOp0->getName()), I);
1820 }
1821
1822 Value *V =
1823 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1824 BoolCast->getOperand(0)->getName()+
1825 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001826
1827 // If the multiply type is not the same as the source type, sign extend
1828 // or truncate to the multiply type.
1829 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00001830 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001831
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001832 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00001833 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00001834 }
1835 }
1836 }
1837
Chris Lattner7e708292002-06-25 16:13:24 +00001838 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001839}
1840
Chris Lattner7e708292002-06-25 16:13:24 +00001841Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00001842 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00001843
Chris Lattner857e8cd2004-12-12 21:48:58 +00001844 if (isa<UndefValue>(Op0)) // undef / X -> 0
1845 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1846 if (isa<UndefValue>(Op1))
1847 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1848
1849 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001850 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00001851 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001852 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00001853
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001854 // div X, -1 == -X
1855 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001856 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00001857
Chris Lattner857e8cd2004-12-12 21:48:58 +00001858 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00001859 if (LHS->getOpcode() == Instruction::Div)
1860 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00001861 // (X / C1) / C2 -> X / (C1*C2)
1862 return BinaryOperator::createDiv(LHS->getOperand(0),
1863 ConstantExpr::getMul(RHS, LHSRHS));
1864 }
1865
Chris Lattnera2881962003-02-18 19:28:33 +00001866 // Check to see if this is an unsigned division with an exact power of 2,
1867 // if so, convert to a right shift.
1868 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1869 if (uint64_t Val = C->getValue()) // Don't break X / 0
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001870 if (isPowerOf2_64(Val)) {
1871 uint64_t C = Log2_64(Val);
Chris Lattner857e8cd2004-12-12 21:48:58 +00001872 return new ShiftInst(Instruction::Shr, Op0,
Chris Lattnera2881962003-02-18 19:28:33 +00001873 ConstantUInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001874 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001875
Chris Lattnera052f822004-10-09 02:50:40 +00001876 // -X/C -> X/-C
1877 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00001878 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00001879 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1880
Chris Lattner857e8cd2004-12-12 21:48:58 +00001881 if (!RHS->isNullValue()) {
1882 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001883 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00001884 return R;
1885 if (isa<PHINode>(Op0))
1886 if (Instruction *NV = FoldOpIntoPhi(I))
1887 return NV;
1888 }
Chris Lattnera2881962003-02-18 19:28:33 +00001889 }
1890
Chris Lattner857e8cd2004-12-12 21:48:58 +00001891 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1892 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1893 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1894 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1895 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1896 if (STO->getValue() == 0) { // Couldn't be this argument.
1897 I.setOperand(1, SFO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001898 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001899 } else if (SFO->getValue() == 0) {
Chris Lattnerf9c775c2005-06-16 04:55:52 +00001900 I.setOperand(1, STO);
Misha Brukmanfd939082005-04-21 23:48:37 +00001901 return &I;
Chris Lattner857e8cd2004-12-12 21:48:58 +00001902 }
1903
Chris Lattnerbf70b832005-04-08 04:03:26 +00001904 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00001905 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1906 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
Chris Lattnerbf70b832005-04-08 04:03:26 +00001907 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1908 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1909 TC, SI->getName()+".t");
1910 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00001911
Chris Lattnerbf70b832005-04-08 04:03:26 +00001912 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1913 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1914 FC, SI->getName()+".f");
1915 FSI = InsertNewInstBefore(FSI, I);
1916 return new SelectInst(SI->getOperand(0), TSI, FSI);
1917 }
Chris Lattner857e8cd2004-12-12 21:48:58 +00001918 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001919
Chris Lattnera2881962003-02-18 19:28:33 +00001920 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00001921 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00001922 if (LHS->equalsInt(0))
1923 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1924
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001925 if (I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00001926 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001927 // unsigned inputs), turn this into a udiv.
Chris Lattner3bedbd92006-02-07 07:27:52 +00001928 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1929 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001930 const Type *NTy = Op0->getType()->getUnsignedVersion();
1931 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1932 InsertNewInstBefore(LHS, I);
1933 Value *RHS;
1934 if (Constant *R = dyn_cast<Constant>(Op1))
1935 RHS = ConstantExpr::getCast(R, NTy);
1936 else
1937 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1938 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1939 InsertNewInstBefore(Div, I);
1940 return new CastInst(Div, I.getType());
1941 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00001942 } else {
1943 // Known to be an unsigned division.
1944 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1945 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1946 if (RHSI->getOpcode() == Instruction::Shl &&
1947 isa<ConstantUInt>(RHSI->getOperand(0))) {
1948 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1949 if (isPowerOf2_64(C1)) {
1950 unsigned C2 = Log2_64(C1);
1951 Value *Add = RHSI->getOperand(1);
1952 if (C2) {
1953 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1954 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1955 "tmp"), I);
1956 }
1957 return new ShiftInst(Instruction::Shr, Op0, Add);
1958 }
1959 }
1960 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00001961 }
1962
Chris Lattner3f5b8772002-05-06 16:14:14 +00001963 return 0;
1964}
1965
1966
Chris Lattnerdb3f8732006-03-02 06:50:58 +00001967/// GetFactor - If we can prove that the specified value is at least a multiple
1968/// of some factor, return that factor.
1969static Constant *GetFactor(Value *V) {
1970 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1971 return CI;
1972
1973 // Unless we can be tricky, we know this is a multiple of 1.
1974 Constant *Result = ConstantInt::get(V->getType(), 1);
1975
1976 Instruction *I = dyn_cast<Instruction>(V);
1977 if (!I) return Result;
1978
1979 if (I->getOpcode() == Instruction::Mul) {
1980 // Handle multiplies by a constant, etc.
1981 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1982 GetFactor(I->getOperand(1)));
1983 } else if (I->getOpcode() == Instruction::Shl) {
1984 // (X<<C) -> X * (1 << C)
1985 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1986 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1987 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1988 }
1989 } else if (I->getOpcode() == Instruction::And) {
1990 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1991 // X & 0xFFF0 is known to be a multiple of 16.
1992 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1993 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1994 return ConstantExpr::getShl(Result,
1995 ConstantUInt::get(Type::UByteTy, Zeros));
1996 }
1997 } else if (I->getOpcode() == Instruction::Cast) {
1998 Value *Op = I->getOperand(0);
1999 // Only handle int->int casts.
2000 if (!Op->getType()->isInteger()) return Result;
2001 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2002 }
2003 return Result;
2004}
2005
Chris Lattner7e708292002-06-25 16:13:24 +00002006Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002007 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002008
2009 // 0 % X == 0, we don't need to preserve faults!
2010 if (Constant *LHS = dyn_cast<Constant>(Op0))
2011 if (LHS->isNullValue())
2012 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2013
2014 if (isa<UndefValue>(Op0)) // undef % X -> 0
2015 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2016 if (isa<UndefValue>(Op1))
2017 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2018
Chris Lattner11a49f22005-11-05 07:28:37 +00002019 if (I.getType()->isSigned()) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002020 if (Value *RHSNeg = dyn_castNegVal(Op1))
Chris Lattner1e3564e2004-07-06 07:11:42 +00002021 if (!isa<ConstantSInt>(RHSNeg) ||
Chris Lattnerb49f3062004-08-09 21:05:48 +00002022 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00002023 // X % -Y -> X % Y
2024 AddUsesToWorkList(I);
2025 I.setOperand(1, RHSNeg);
2026 return &I;
2027 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002028
2029 // If the top bits of both operands are zero (i.e. we can prove they are
2030 // unsigned inputs), turn this into a urem.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002031 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2032 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattner11a49f22005-11-05 07:28:37 +00002033 const Type *NTy = Op0->getType()->getUnsignedVersion();
2034 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2035 InsertNewInstBefore(LHS, I);
2036 Value *RHS;
2037 if (Constant *R = dyn_cast<Constant>(Op1))
2038 RHS = ConstantExpr::getCast(R, NTy);
2039 else
2040 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2041 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2042 InsertNewInstBefore(Rem, I);
2043 return new CastInst(Rem, I.getType());
2044 }
2045 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002046
Chris Lattner857e8cd2004-12-12 21:48:58 +00002047 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002048 // X % 0 == undef, we don't need to preserve faults!
2049 if (RHS->equalsInt(0))
2050 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2051
Chris Lattnera2881962003-02-18 19:28:33 +00002052 if (RHS->equalsInt(1)) // X % 1 == 0
2053 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2054
2055 // Check to see if this is an unsigned remainder with an exact power of 2,
2056 // if so, convert to a bitwise and.
2057 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002058 if (isPowerOf2_64(C->getValue()))
2059 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattner857e8cd2004-12-12 21:48:58 +00002060
Chris Lattner97943922006-02-28 05:49:21 +00002061 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2062 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2063 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2064 return R;
2065 } else if (isa<PHINode>(Op0I)) {
2066 if (Instruction *NV = FoldOpIntoPhi(I))
2067 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002068 }
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002069
2070 // X*C1%C2 --> 0 iff C1%C2 == 0
2071 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2072 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002073 }
Chris Lattnera2881962003-02-18 19:28:33 +00002074 }
2075
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002076 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2077 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2078 if (I.getType()->isUnsigned() &&
2079 RHSI->getOpcode() == Instruction::Shl &&
2080 isa<ConstantUInt>(RHSI->getOperand(0))) {
2081 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2082 if (isPowerOf2_64(C1)) {
2083 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2084 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2085 "tmp"), I);
2086 return BinaryOperator::createAnd(Op0, Add);
2087 }
2088 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002089
2090 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2091 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2092 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2093 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2094 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
2095 if (STO->getValue() == 0) { // Couldn't be this argument.
2096 I.setOperand(1, SFO);
2097 return &I;
2098 } else if (SFO->getValue() == 0) {
2099 I.setOperand(1, STO);
2100 return &I;
2101 }
2102
2103 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2104 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2105 SubOne(STO), SI->getName()+".t"), I);
2106 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2107 SubOne(SFO), SI->getName()+".f"), I);
2108 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2109 }
2110 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002111 }
2112
Chris Lattner3f5b8772002-05-06 16:14:14 +00002113 return 0;
2114}
2115
Chris Lattner8b170942002-08-09 23:47:40 +00002116// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002117static bool isMaxValueMinusOne(const ConstantInt *C) {
Chris Lattner1a074fc2006-02-07 07:00:41 +00002118 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2119 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002120
2121 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00002122
Chris Lattner8b170942002-08-09 23:47:40 +00002123 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00002124 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002125 int64_t Val = INT64_MAX; // All ones
2126 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2127 return CS->getValue() == Val-1;
2128}
2129
2130// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002131static bool isMinValuePlusOne(const ConstantInt *C) {
Chris Lattner8b170942002-08-09 23:47:40 +00002132 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2133 return CU->getValue() == 1;
2134
2135 const ConstantSInt *CS = cast<ConstantSInt>(C);
Misha Brukmanfd939082005-04-21 23:48:37 +00002136
2137 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00002138 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002139 int64_t Val = -1; // All ones
2140 Val <<= TypeBits-1; // Shift over to the right spot
2141 return CS->getValue() == Val+1;
2142}
2143
Chris Lattner457dd822004-06-09 07:59:58 +00002144// isOneBitSet - Return true if there is exactly one bit set in the specified
2145// constant.
2146static bool isOneBitSet(const ConstantInt *CI) {
2147 uint64_t V = CI->getRawValue();
2148 return V && (V & (V-1)) == 0;
2149}
2150
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002151#if 0 // Currently unused
2152// isLowOnes - Return true if the constant is of the form 0+1+.
2153static bool isLowOnes(const ConstantInt *CI) {
2154 uint64_t V = CI->getRawValue();
2155
2156 // There won't be bits set in parts that the type doesn't contain.
2157 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2158
2159 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2160 return U && V && (U & V) == 0;
2161}
2162#endif
2163
2164// isHighOnes - Return true if the constant is of the form 1+0+.
2165// This is the same as lowones(~X).
2166static bool isHighOnes(const ConstantInt *CI) {
2167 uint64_t V = ~CI->getRawValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002168 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002169
2170 // There won't be bits set in parts that the type doesn't contain.
2171 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2172
2173 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2174 return U && V && (U & V) == 0;
2175}
2176
2177
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002178/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2179/// are carefully arranged to allow folding of expressions such as:
2180///
2181/// (A < B) | (A > B) --> (A != B)
2182///
2183/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2184/// represents that the comparison is true if A == B, and bit value '1' is true
2185/// if A < B.
2186///
2187static unsigned getSetCondCode(const SetCondInst *SCI) {
2188 switch (SCI->getOpcode()) {
2189 // False -> 0
2190 case Instruction::SetGT: return 1;
2191 case Instruction::SetEQ: return 2;
2192 case Instruction::SetGE: return 3;
2193 case Instruction::SetLT: return 4;
2194 case Instruction::SetNE: return 5;
2195 case Instruction::SetLE: return 6;
2196 // True -> 7
2197 default:
2198 assert(0 && "Invalid SetCC opcode!");
2199 return 0;
2200 }
2201}
2202
2203/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2204/// opcode and two operands into either a constant true or false, or a brand new
2205/// SetCC instruction.
2206static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2207 switch (Opcode) {
2208 case 0: return ConstantBool::False;
2209 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2210 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2211 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2212 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2213 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2214 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2215 case 7: return ConstantBool::True;
2216 default: assert(0 && "Illegal SetCCCode!"); return 0;
2217 }
2218}
2219
2220// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2221struct FoldSetCCLogical {
2222 InstCombiner &IC;
2223 Value *LHS, *RHS;
2224 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2225 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2226 bool shouldApply(Value *V) const {
2227 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2228 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2229 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2230 return false;
2231 }
2232 Instruction *apply(BinaryOperator &Log) const {
2233 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2234 if (SCI->getOperand(0) != LHS) {
2235 assert(SCI->getOperand(1) == LHS);
2236 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2237 }
2238
2239 unsigned LHSCode = getSetCondCode(SCI);
2240 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2241 unsigned Code;
2242 switch (Log.getOpcode()) {
2243 case Instruction::And: Code = LHSCode & RHSCode; break;
2244 case Instruction::Or: Code = LHSCode | RHSCode; break;
2245 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002246 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002247 }
2248
2249 Value *RV = getSetCCValue(Code, LHS, RHS);
2250 if (Instruction *I = dyn_cast<Instruction>(RV))
2251 return I;
2252 // Otherwise, it's a constant boolean value...
2253 return IC.ReplaceInstUsesWith(Log, RV);
2254 }
2255};
2256
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002257// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2258// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2259// guaranteed to be either a shift instruction or a binary operator.
2260Instruction *InstCombiner::OptAndOp(Instruction *Op,
2261 ConstantIntegral *OpRHS,
2262 ConstantIntegral *AndRHS,
2263 BinaryOperator &TheAnd) {
2264 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002265 Constant *Together = 0;
2266 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00002267 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002268
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002269 switch (Op->getOpcode()) {
2270 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002271 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002272 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2273 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00002274 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002275 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002276 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002277 }
2278 break;
2279 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002280 if (Together == AndRHS) // (X | C) & C --> C
2281 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002282
Chris Lattner6e7ba452005-01-01 16:22:27 +00002283 if (Op->hasOneUse() && Together != OpRHS) {
2284 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2285 std::string Op0Name = Op->getName(); Op->setName("");
2286 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2287 InsertNewInstBefore(Or, TheAnd);
2288 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002289 }
2290 break;
2291 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002292 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002293 // Adding a one to a single bit bit-field should be turned into an XOR
2294 // of the bit. First thing to check is to see if this AND is with a
2295 // single bit constant.
Chris Lattner457dd822004-06-09 07:59:58 +00002296 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002297
2298 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002299 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002300
2301 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002302 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002303 // Ok, at this point, we know that we are masking the result of the
2304 // ADD down to exactly one bit. If the constant we are adding has
2305 // no bits set below this bit, then we can eliminate the ADD.
Chris Lattner457dd822004-06-09 07:59:58 +00002306 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002307
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002308 // Check to see if any bits below the one bit set in AndRHSV are set.
2309 if ((AddRHS & (AndRHSV-1)) == 0) {
2310 // If not, the only thing that can effect the output of the AND is
2311 // the bit specified by AndRHSV. If that bit is set, the effect of
2312 // the XOR is to toggle the bit. If it is clear, then the ADD has
2313 // no effect.
2314 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2315 TheAnd.setOperand(0, X);
2316 return &TheAnd;
2317 } else {
2318 std::string Name = Op->getName(); Op->setName("");
2319 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00002320 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002321 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002322 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002323 }
2324 }
2325 }
2326 }
2327 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002328
2329 case Instruction::Shl: {
2330 // We know that the AND will not produce any of the bits shifted in, so if
2331 // the anded constant includes them, clear them now!
2332 //
2333 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002334 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2335 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002336
Chris Lattner0c967662004-09-24 15:21:34 +00002337 if (CI == ShlMask) { // Masking out bits that the shift already masks
2338 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2339 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002340 TheAnd.setOperand(1, CI);
2341 return &TheAnd;
2342 }
2343 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002344 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002345 case Instruction::Shr:
2346 // We know that the AND will not produce any of the bits shifted in, so if
2347 // the anded constant includes them, clear them now! This only applies to
2348 // unsigned shifts, because a signed shr may bring in set bits!
2349 //
2350 if (AndRHS->getType()->isUnsigned()) {
2351 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002352 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2353 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2354
2355 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2356 return ReplaceInstUsesWith(TheAnd, Op);
2357 } else if (CI != AndRHS) {
2358 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00002359 return &TheAnd;
2360 }
Chris Lattner0c967662004-09-24 15:21:34 +00002361 } else { // Signed shr.
2362 // See if this is shifting in some sign extension, then masking it out
2363 // with an and.
2364 if (Op->hasOneUse()) {
2365 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2366 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2367 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00002368 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00002369 // Make the argument unsigned.
2370 Value *ShVal = Op->getOperand(0);
2371 ShVal = InsertCastBefore(ShVal,
2372 ShVal->getType()->getUnsignedVersion(),
2373 TheAnd);
2374 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2375 OpRHS, Op->getName()),
2376 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00002377 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2378 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2379 TheAnd.getName()),
2380 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00002381 return new CastInst(ShVal, Op->getType());
2382 }
2383 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002384 }
2385 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002386 }
2387 return 0;
2388}
2389
Chris Lattner8b170942002-08-09 23:47:40 +00002390
Chris Lattnera96879a2004-09-29 17:40:11 +00002391/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2392/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2393/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2394/// insert new instructions.
2395Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2396 bool Inside, Instruction &IB) {
2397 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2398 "Lo is not <= Hi in range emission code!");
2399 if (Inside) {
2400 if (Lo == Hi) // Trivially false.
2401 return new SetCondInst(Instruction::SetNE, V, V);
2402 if (cast<ConstantIntegral>(Lo)->isMinValue())
2403 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00002404
Chris Lattnera96879a2004-09-29 17:40:11 +00002405 Constant *AddCST = ConstantExpr::getNeg(Lo);
2406 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2407 InsertNewInstBefore(Add, IB);
2408 // Convert to unsigned for the comparison.
2409 const Type *UnsType = Add->getType()->getUnsignedVersion();
2410 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2411 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2412 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2413 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2414 }
2415
2416 if (Lo == Hi) // Trivially true.
2417 return new SetCondInst(Instruction::SetEQ, V, V);
2418
2419 Hi = SubOne(cast<ConstantInt>(Hi));
2420 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2421 return new SetCondInst(Instruction::SetGT, V, Hi);
2422
2423 // Emit X-Lo > Hi-Lo-1
2424 Constant *AddCST = ConstantExpr::getNeg(Lo);
2425 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2426 InsertNewInstBefore(Add, IB);
2427 // Convert to unsigned for the comparison.
2428 const Type *UnsType = Add->getType()->getUnsignedVersion();
2429 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2430 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2431 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2432 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2433}
2434
Chris Lattner7203e152005-09-18 07:22:02 +00002435// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2436// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2437// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2438// not, since all 1s are not contiguous.
2439static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2440 uint64_t V = Val->getRawValue();
2441 if (!isShiftedMask_64(V)) return false;
2442
2443 // look for the first zero bit after the run of ones
2444 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2445 // look for the first non-zero bit
2446 ME = 64-CountLeadingZeros_64(V);
2447 return true;
2448}
2449
2450
2451
2452/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2453/// where isSub determines whether the operator is a sub. If we can fold one of
2454/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002455///
2456/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2457/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2458/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2459///
2460/// return (A +/- B).
2461///
2462Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2463 ConstantIntegral *Mask, bool isSub,
2464 Instruction &I) {
2465 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2466 if (!LHSI || LHSI->getNumOperands() != 2 ||
2467 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2468
2469 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2470
2471 switch (LHSI->getOpcode()) {
2472 default: return 0;
2473 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00002474 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2475 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2476 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2477 break;
2478
2479 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2480 // part, we don't need any explicit masks to take them out of A. If that
2481 // is all N is, ignore it.
2482 unsigned MB, ME;
2483 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00002484 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2485 Mask >>= 64-MB+1;
2486 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002487 break;
2488 }
2489 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002490 return 0;
2491 case Instruction::Or:
2492 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002493 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2494 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2495 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002496 break;
2497 return 0;
2498 }
2499
2500 Instruction *New;
2501 if (isSub)
2502 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2503 else
2504 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2505 return InsertNewInstBefore(New, I);
2506}
2507
Chris Lattner7e708292002-06-25 16:13:24 +00002508Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002509 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002510 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002511
Chris Lattnere87597f2004-10-16 18:11:37 +00002512 if (isa<UndefValue>(Op1)) // X & undef -> 0
2513 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2514
Chris Lattner6e7ba452005-01-01 16:22:27 +00002515 // and X, X = X
2516 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002517 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002518
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002519 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002520 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00002521 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002522 if (!isa<PackedType>(I.getType()) &&
2523 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner255d8912006-02-11 09:31:47 +00002524 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00002525 return &I;
2526
Chris Lattner6e7ba452005-01-01 16:22:27 +00002527 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00002528 uint64_t AndRHSMask = AndRHS->getZExtValue();
2529 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00002530 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002531
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002532 // Optimize a variety of ((val OP C1) & C2) combinations...
2533 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2534 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002535 Value *Op0LHS = Op0I->getOperand(0);
2536 Value *Op0RHS = Op0I->getOperand(1);
2537 switch (Op0I->getOpcode()) {
2538 case Instruction::Xor:
2539 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002540 // If the mask is only needed on one incoming arm, push it up.
2541 if (Op0I->hasOneUse()) {
2542 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2543 // Not masking anything out for the LHS, move to RHS.
2544 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2545 Op0RHS->getName()+".masked");
2546 InsertNewInstBefore(NewRHS, I);
2547 return BinaryOperator::create(
2548 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002549 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00002550 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00002551 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2552 // Not masking anything out for the RHS, move to LHS.
2553 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2554 Op0LHS->getName()+".masked");
2555 InsertNewInstBefore(NewLHS, I);
2556 return BinaryOperator::create(
2557 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2558 }
2559 }
2560
Chris Lattner6e7ba452005-01-01 16:22:27 +00002561 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00002562 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00002563 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2564 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2565 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2566 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2567 return BinaryOperator::createAnd(V, AndRHS);
2568 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2569 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002570 break;
2571
2572 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002573 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2574 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2575 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2576 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2577 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00002578 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002579 }
2580
Chris Lattner58403262003-07-23 19:25:52 +00002581 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002582 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002583 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002584 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2585 const Type *SrcTy = CI->getOperand(0)->getType();
2586
Chris Lattner2b83af22005-08-07 07:03:10 +00002587 // If this is an integer truncation or change from signed-to-unsigned, and
2588 // if the source is an and/or with immediate, transform it. This
2589 // frequently occurs for bitfield accesses.
2590 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2591 if (SrcTy->getPrimitiveSizeInBits() >=
2592 I.getType()->getPrimitiveSizeInBits() &&
2593 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00002594 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00002595 if (CastOp->getOpcode() == Instruction::And) {
2596 // Change: and (cast (and X, C1) to T), C2
2597 // into : and (cast X to T), trunc(C1)&C2
2598 // This will folds the two ands together, which may allow other
2599 // simplifications.
2600 Instruction *NewCast =
2601 new CastInst(CastOp->getOperand(0), I.getType(),
2602 CastOp->getName()+".shrunk");
2603 NewCast = InsertNewInstBefore(NewCast, I);
2604
2605 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2606 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2607 return BinaryOperator::createAnd(NewCast, C3);
2608 } else if (CastOp->getOpcode() == Instruction::Or) {
2609 // Change: and (cast (or X, C1) to T), C2
2610 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2611 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2612 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2613 return ReplaceInstUsesWith(I, AndRHS);
2614 }
2615 }
Chris Lattner06782f82003-07-23 19:36:21 +00002616 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002617
2618 // Try to fold constant and into select arguments.
2619 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002620 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002621 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002622 if (isa<PHINode>(Op0))
2623 if (Instruction *NV = FoldOpIntoPhi(I))
2624 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002625 }
2626
Chris Lattner8d969642003-03-10 23:06:50 +00002627 Value *Op0NotVal = dyn_castNotVal(Op0);
2628 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002629
Chris Lattner5b62aa72004-06-18 06:07:51 +00002630 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2631 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2632
Misha Brukmancb6267b2004-07-30 12:50:08 +00002633 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00002634 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00002635 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2636 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002637 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00002638 return BinaryOperator::createNot(Or);
2639 }
Chris Lattner2082ad92006-02-13 23:07:23 +00002640
2641 {
2642 Value *A = 0, *B = 0;
2643 ConstantInt *C1 = 0, *C2 = 0;
2644 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2645 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2646 return ReplaceInstUsesWith(I, Op1);
2647 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2648 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2649 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00002650
2651 if (Op0->hasOneUse() &&
2652 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2653 if (A == Op1) { // (A^B)&A -> A&(A^B)
2654 I.swapOperands(); // Simplify below
2655 std::swap(Op0, Op1);
2656 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2657 cast<BinaryOperator>(Op0)->swapOperands();
2658 I.swapOperands(); // Simplify below
2659 std::swap(Op0, Op1);
2660 }
2661 }
2662 if (Op1->hasOneUse() &&
2663 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2664 if (B == Op0) { // B&(A^B) -> B&(B^A)
2665 cast<BinaryOperator>(Op1)->swapOperands();
2666 std::swap(A, B);
2667 }
2668 if (A == Op0) { // A&(A^B) -> A & ~B
2669 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2670 InsertNewInstBefore(NotB, I);
2671 return BinaryOperator::createAnd(A, NotB);
2672 }
2673 }
Chris Lattner2082ad92006-02-13 23:07:23 +00002674 }
2675
Chris Lattnera2881962003-02-18 19:28:33 +00002676
Chris Lattner955f3312004-09-28 21:48:02 +00002677 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2678 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002679 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2680 return R;
2681
Chris Lattner955f3312004-09-28 21:48:02 +00002682 Value *LHSVal, *RHSVal;
2683 ConstantInt *LHSCst, *RHSCst;
2684 Instruction::BinaryOps LHSCC, RHSCC;
2685 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2686 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2687 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2688 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002689 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00002690 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2691 // Ensure that the larger constant is on the RHS.
2692 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2693 SetCondInst *LHS = cast<SetCondInst>(Op0);
2694 if (cast<ConstantBool>(Cmp)->getValue()) {
2695 std::swap(LHS, RHS);
2696 std::swap(LHSCst, RHSCst);
2697 std::swap(LHSCC, RHSCC);
2698 }
2699
2700 // At this point, we know we have have two setcc instructions
2701 // comparing a value against two constants and and'ing the result
2702 // together. Because of the above check, we know that we only have
2703 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2704 // FoldSetCCLogical check above), that the two constants are not
2705 // equal.
2706 assert(LHSCst != RHSCst && "Compares not folded above?");
2707
2708 switch (LHSCC) {
2709 default: assert(0 && "Unknown integer condition code!");
2710 case Instruction::SetEQ:
2711 switch (RHSCC) {
2712 default: assert(0 && "Unknown integer condition code!");
2713 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2714 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2715 return ReplaceInstUsesWith(I, ConstantBool::False);
2716 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2717 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2718 return ReplaceInstUsesWith(I, LHS);
2719 }
2720 case Instruction::SetNE:
2721 switch (RHSCC) {
2722 default: assert(0 && "Unknown integer condition code!");
2723 case Instruction::SetLT:
2724 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2725 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2726 break; // (X != 13 & X < 15) -> no change
2727 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2728 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2729 return ReplaceInstUsesWith(I, RHS);
2730 case Instruction::SetNE:
2731 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2732 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2733 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2734 LHSVal->getName()+".off");
2735 InsertNewInstBefore(Add, I);
2736 const Type *UnsType = Add->getType()->getUnsignedVersion();
2737 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2738 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2739 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2740 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2741 }
2742 break; // (X != 13 & X != 15) -> no change
2743 }
2744 break;
2745 case Instruction::SetLT:
2746 switch (RHSCC) {
2747 default: assert(0 && "Unknown integer condition code!");
2748 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2749 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2750 return ReplaceInstUsesWith(I, ConstantBool::False);
2751 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2752 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2753 return ReplaceInstUsesWith(I, LHS);
2754 }
2755 case Instruction::SetGT:
2756 switch (RHSCC) {
2757 default: assert(0 && "Unknown integer condition code!");
2758 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2759 return ReplaceInstUsesWith(I, LHS);
2760 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2761 return ReplaceInstUsesWith(I, RHS);
2762 case Instruction::SetNE:
2763 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2764 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2765 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00002766 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2767 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00002768 }
2769 }
2770 }
2771 }
2772
Chris Lattner6fc205f2006-05-05 06:39:07 +00002773 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2774 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00002775 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00002776 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00002777 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00002778 // Only do this if the casts both really cause code to be generated.
2779 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2780 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00002781 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2782 Op1C->getOperand(0),
2783 I.getName());
2784 InsertNewInstBefore(NewOp, I);
2785 return new CastInst(NewOp, I.getType());
2786 }
2787 }
2788
Chris Lattner7e708292002-06-25 16:13:24 +00002789 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00002790}
2791
Chris Lattner7e708292002-06-25 16:13:24 +00002792Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002793 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002794 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002795
Chris Lattnere87597f2004-10-16 18:11:37 +00002796 if (isa<UndefValue>(Op1))
2797 return ReplaceInstUsesWith(I, // X | undef -> -1
2798 ConstantIntegral::getAllOnesValue(I.getType()));
2799
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002800 // or X, X = X
2801 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002802 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002803
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002804 // See if we can simplify any instructions used by the instruction whose sole
2805 // purpose is to compute bits we don't care about.
2806 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002807 if (!isa<PackedType>(I.getType()) &&
2808 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002809 KnownZero, KnownOne))
2810 return &I;
2811
Chris Lattner3f5b8772002-05-06 16:14:14 +00002812 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002813 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002814 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002815 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2816 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002817 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2818 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002819 InsertNewInstBefore(Or, I);
2820 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2821 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002822
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002823 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2824 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2825 std::string Op0Name = Op0->getName(); Op0->setName("");
2826 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2827 InsertNewInstBefore(Or, I);
2828 return BinaryOperator::createXor(Or,
2829 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002830 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002831
2832 // Try to fold constant and into select arguments.
2833 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002834 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002835 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002836 if (isa<PHINode>(Op0))
2837 if (Instruction *NV = FoldOpIntoPhi(I))
2838 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00002839 }
2840
Chris Lattner4f637d42006-01-06 17:59:59 +00002841 Value *A = 0, *B = 0;
2842 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002843
2844 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2845 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2846 return ReplaceInstUsesWith(I, Op1);
2847 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2848 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2849 return ReplaceInstUsesWith(I, Op0);
2850
Chris Lattner6e4c6492005-05-09 04:58:36 +00002851 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2852 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002853 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002854 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2855 Op0->setName("");
2856 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2857 }
2858
2859 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2860 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00002861 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00002862 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2863 Op0->setName("");
2864 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2865 }
2866
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002867 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002868 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002869 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2870
2871 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2872 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2873
2874
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002875 // If we have: ((V + N) & C1) | (V & C2)
2876 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2877 // replace with V+N.
2878 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002879 Value *V1 = 0, *V2 = 0;
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002880 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2881 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2882 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002883 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002884 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002885 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002886 return ReplaceInstUsesWith(I, A);
2887 }
2888 // Or commutes, try both ways.
2889 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2890 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2891 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002892 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002893 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00002894 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00002895 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00002896 }
2897 }
2898 }
Chris Lattner67ca7682003-08-12 19:11:07 +00002899
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002900 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2901 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00002902 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002903 ConstantIntegral::getAllOnesValue(I.getType()));
2904 } else {
2905 A = 0;
2906 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00002907 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002908 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2909 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00002910 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002911 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00002912
Misha Brukmancb6267b2004-07-30 12:50:08 +00002913 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002914 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2915 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2916 I.getName()+".demorgan"), I);
2917 return BinaryOperator::createNot(And);
2918 }
Chris Lattnera27231a2003-03-10 23:13:59 +00002919 }
Chris Lattnera2881962003-02-18 19:28:33 +00002920
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002921 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002922 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002923 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2924 return R;
2925
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002926 Value *LHSVal, *RHSVal;
2927 ConstantInt *LHSCst, *RHSCst;
2928 Instruction::BinaryOps LHSCC, RHSCC;
2929 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2930 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2931 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2932 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00002933 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002934 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2935 // Ensure that the larger constant is on the RHS.
2936 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2937 SetCondInst *LHS = cast<SetCondInst>(Op0);
2938 if (cast<ConstantBool>(Cmp)->getValue()) {
2939 std::swap(LHS, RHS);
2940 std::swap(LHSCst, RHSCst);
2941 std::swap(LHSCC, RHSCC);
2942 }
2943
2944 // At this point, we know we have have two setcc instructions
2945 // comparing a value against two constants and or'ing the result
2946 // together. Because of the above check, we know that we only have
2947 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2948 // FoldSetCCLogical check above), that the two constants are not
2949 // equal.
2950 assert(LHSCst != RHSCst && "Compares not folded above?");
2951
2952 switch (LHSCC) {
2953 default: assert(0 && "Unknown integer condition code!");
2954 case Instruction::SetEQ:
2955 switch (RHSCC) {
2956 default: assert(0 && "Unknown integer condition code!");
2957 case Instruction::SetEQ:
2958 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2959 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2960 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2961 LHSVal->getName()+".off");
2962 InsertNewInstBefore(Add, I);
2963 const Type *UnsType = Add->getType()->getUnsignedVersion();
2964 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2965 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2966 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2967 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2968 }
2969 break; // (X == 13 | X == 15) -> no change
2970
Chris Lattner240d6f42005-04-19 06:04:18 +00002971 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2972 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002973 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2974 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2975 return ReplaceInstUsesWith(I, RHS);
2976 }
2977 break;
2978 case Instruction::SetNE:
2979 switch (RHSCC) {
2980 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002981 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2982 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2983 return ReplaceInstUsesWith(I, LHS);
2984 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00002985 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002986 return ReplaceInstUsesWith(I, ConstantBool::True);
2987 }
2988 break;
2989 case Instruction::SetLT:
2990 switch (RHSCC) {
2991 default: assert(0 && "Unknown integer condition code!");
2992 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2993 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00002994 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2995 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00002996 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2997 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2998 return ReplaceInstUsesWith(I, RHS);
2999 }
3000 break;
3001 case Instruction::SetGT:
3002 switch (RHSCC) {
3003 default: assert(0 && "Unknown integer condition code!");
3004 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3005 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3006 return ReplaceInstUsesWith(I, LHS);
3007 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3008 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3009 return ReplaceInstUsesWith(I, ConstantBool::True);
3010 }
3011 }
3012 }
3013 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003014
3015 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3016 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003017 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003018 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003019 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003020 // Only do this if the casts both really cause code to be generated.
3021 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3022 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003023 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3024 Op1C->getOperand(0),
3025 I.getName());
3026 InsertNewInstBefore(NewOp, I);
3027 return new CastInst(NewOp, I.getType());
3028 }
3029 }
3030
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003031
Chris Lattner7e708292002-06-25 16:13:24 +00003032 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003033}
3034
Chris Lattnerc317d392004-02-16 01:20:27 +00003035// XorSelf - Implements: X ^ X --> 0
3036struct XorSelf {
3037 Value *RHS;
3038 XorSelf(Value *rhs) : RHS(rhs) {}
3039 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3040 Instruction *apply(BinaryOperator &Xor) const {
3041 return &Xor;
3042 }
3043};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003044
3045
Chris Lattner7e708292002-06-25 16:13:24 +00003046Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003047 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003048 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003049
Chris Lattnere87597f2004-10-16 18:11:37 +00003050 if (isa<UndefValue>(Op1))
3051 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3052
Chris Lattnerc317d392004-02-16 01:20:27 +00003053 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3054 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3055 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00003056 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003057 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003058
3059 // See if we can simplify any instructions used by the instruction whose sole
3060 // purpose is to compute bits we don't care about.
3061 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003062 if (!isa<PackedType>(I.getType()) &&
3063 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003064 KnownZero, KnownOne))
3065 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003066
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003067 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003068 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00003069 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003070 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattnerfd059242003-10-15 16:48:29 +00003071 if (RHS == ConstantBool::True && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00003072 return new SetCondInst(SCI->getInverseCondition(),
3073 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003074
Chris Lattnerd65460f2003-11-05 01:06:05 +00003075 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003076 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3077 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00003078 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3079 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003080 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00003081 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003082 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00003083
3084 // ~(~X & Y) --> (X | ~Y)
3085 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3086 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3087 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3088 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00003089 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00003090 Op0I->getOperand(1)->getName()+".not");
3091 InsertNewInstBefore(NotY, I);
3092 return BinaryOperator::createOr(Op0NotVal, NotY);
3093 }
3094 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003095
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003096 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003097 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003098 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003099 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00003100 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3101 return BinaryOperator::createSub(
3102 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003103 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00003104 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003105 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003106 } else if (Op0I->getOpcode() == Instruction::Or) {
3107 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3108 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3109 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3110 // Anything in both C1 and C2 is known to be zero, remove it from
3111 // NewRHS.
3112 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3113 NewRHS = ConstantExpr::getAnd(NewRHS,
3114 ConstantExpr::getNot(CommonBits));
3115 WorkList.push_back(Op0I);
3116 I.setOperand(0, Op0I->getOperand(0));
3117 I.setOperand(1, NewRHS);
3118 return &I;
3119 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003120 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003121 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003122
3123 // Try to fold constant and into select arguments.
3124 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003125 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003126 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003127 if (isa<PHINode>(Op0))
3128 if (Instruction *NV = FoldOpIntoPhi(I))
3129 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003130 }
3131
Chris Lattner8d969642003-03-10 23:06:50 +00003132 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003133 if (X == Op1)
3134 return ReplaceInstUsesWith(I,
3135 ConstantIntegral::getAllOnesValue(I.getType()));
3136
Chris Lattner8d969642003-03-10 23:06:50 +00003137 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003138 if (X == Op0)
3139 return ReplaceInstUsesWith(I,
3140 ConstantIntegral::getAllOnesValue(I.getType()));
3141
Chris Lattner64daab52006-04-01 08:03:55 +00003142 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00003143 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003144 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003145 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003146 I.swapOperands();
3147 std::swap(Op0, Op1);
3148 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003149 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003150 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003151 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003152 } else if (Op1I->getOpcode() == Instruction::Xor) {
3153 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3154 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3155 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3156 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003157 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3158 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3159 Op1I->swapOperands();
3160 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3161 I.swapOperands(); // Simplified below.
3162 std::swap(Op0, Op1);
3163 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003164 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003165
Chris Lattner64daab52006-04-01 08:03:55 +00003166 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00003167 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003168 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003169 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00003170 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00003171 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3172 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00003173 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00003174 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003175 } else if (Op0I->getOpcode() == Instruction::Xor) {
3176 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3177 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3178 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3179 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003180 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3181 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3182 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00003183 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3184 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00003185 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3186 InsertNewInstBefore(N, I);
3187 return BinaryOperator::createAnd(N, Op1);
3188 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003189 }
3190
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003191 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3192 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3193 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3194 return R;
3195
Chris Lattner6fc205f2006-05-05 06:39:07 +00003196 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3197 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003198 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003199 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003200 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003201 // Only do this if the casts both really cause code to be generated.
3202 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3203 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003204 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3205 Op1C->getOperand(0),
3206 I.getName());
3207 InsertNewInstBefore(NewOp, I);
3208 return new CastInst(NewOp, I.getType());
3209 }
3210 }
3211
Chris Lattner7e708292002-06-25 16:13:24 +00003212 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003213}
3214
Chris Lattnera96879a2004-09-29 17:40:11 +00003215/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3216/// overflowed for this type.
3217static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3218 ConstantInt *In2) {
3219 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3220 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3221}
3222
3223static bool isPositive(ConstantInt *C) {
3224 return cast<ConstantSInt>(C)->getValue() >= 0;
3225}
3226
3227/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3228/// overflowed for this type.
3229static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3230 ConstantInt *In2) {
3231 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3232
3233 if (In1->getType()->isUnsigned())
3234 return cast<ConstantUInt>(Result)->getValue() <
3235 cast<ConstantUInt>(In1)->getValue();
3236 if (isPositive(In1) != isPositive(In2))
3237 return false;
3238 if (isPositive(In1))
3239 return cast<ConstantSInt>(Result)->getValue() <
3240 cast<ConstantSInt>(In1)->getValue();
3241 return cast<ConstantSInt>(Result)->getValue() >
3242 cast<ConstantSInt>(In1)->getValue();
3243}
3244
Chris Lattner574da9b2005-01-13 20:14:25 +00003245/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3246/// code necessary to compute the offset from the base pointer (without adding
3247/// in the base pointer). Return the result as a signed integer of intptr size.
3248static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3249 TargetData &TD = IC.getTargetData();
3250 gep_type_iterator GTI = gep_type_begin(GEP);
3251 const Type *UIntPtrTy = TD.getIntPtrType();
3252 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3253 Value *Result = Constant::getNullValue(SIntPtrTy);
3254
3255 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00003256 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00003257
Chris Lattner574da9b2005-01-13 20:14:25 +00003258 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3259 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00003260 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattner574da9b2005-01-13 20:14:25 +00003261 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3262 SIntPtrTy);
3263 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3264 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003265 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00003266 Scale = ConstantExpr::getMul(OpC, Scale);
3267 if (Constant *RC = dyn_cast<Constant>(Result))
3268 Result = ConstantExpr::getAdd(RC, Scale);
3269 else {
3270 // Emit an add instruction.
3271 Result = IC.InsertNewInstBefore(
3272 BinaryOperator::createAdd(Result, Scale,
3273 GEP->getName()+".offs"), I);
3274 }
3275 }
3276 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00003277 // Convert to correct type.
3278 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3279 Op->getName()+".c"), I);
3280 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003281 // We'll let instcombine(mul) convert this to a shl if possible.
3282 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3283 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00003284
3285 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003286 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00003287 GEP->getName()+".offs"), I);
3288 }
3289 }
3290 return Result;
3291}
3292
3293/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3294/// else. At this point we know that the GEP is on the LHS of the comparison.
3295Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3296 Instruction::BinaryOps Cond,
3297 Instruction &I) {
3298 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00003299
3300 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3301 if (isa<PointerType>(CI->getOperand(0)->getType()))
3302 RHS = CI->getOperand(0);
3303
Chris Lattner574da9b2005-01-13 20:14:25 +00003304 Value *PtrBase = GEPLHS->getOperand(0);
3305 if (PtrBase == RHS) {
3306 // As an optimization, we don't actually have to compute the actual value of
3307 // OFFSET if this is a seteq or setne comparison, just return whether each
3308 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003309 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3310 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003311 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3312 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00003313 bool EmitIt = true;
3314 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3315 if (isa<UndefValue>(C)) // undef index -> undef.
3316 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3317 if (C->isNullValue())
3318 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003319 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3320 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00003321 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00003322 return ReplaceInstUsesWith(I, // No comparison is needed here.
3323 ConstantBool::get(Cond == Instruction::SetNE));
3324 }
3325
3326 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003327 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00003328 new SetCondInst(Cond, GEPLHS->getOperand(i),
3329 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3330 if (InVal == 0)
3331 InVal = Comp;
3332 else {
3333 InVal = InsertNewInstBefore(InVal, I);
3334 InsertNewInstBefore(Comp, I);
3335 if (Cond == Instruction::SetNE) // True if any are unequal
3336 InVal = BinaryOperator::createOr(InVal, Comp);
3337 else // True if all are equal
3338 InVal = BinaryOperator::createAnd(InVal, Comp);
3339 }
3340 }
3341 }
3342
3343 if (InVal)
3344 return InVal;
3345 else
3346 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3347 ConstantBool::get(Cond == Instruction::SetEQ));
3348 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003349
3350 // Only lower this if the setcc is the only user of the GEP or if we expect
3351 // the result to fold to a constant!
3352 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3353 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3354 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3355 return new SetCondInst(Cond, Offset,
3356 Constant::getNullValue(Offset->getType()));
3357 }
3358 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00003359 // If the base pointers are different, but the indices are the same, just
3360 // compare the base pointer.
3361 if (PtrBase != GEPRHS->getOperand(0)) {
3362 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00003363 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00003364 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00003365 if (IndicesTheSame)
3366 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3367 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3368 IndicesTheSame = false;
3369 break;
3370 }
3371
3372 // If all indices are the same, just compare the base pointers.
3373 if (IndicesTheSame)
3374 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3375 GEPRHS->getOperand(0));
3376
3377 // Otherwise, the base pointers are different and the indices are
3378 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00003379 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00003380 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003381
Chris Lattnere9d782b2005-01-13 22:25:21 +00003382 // If one of the GEPs has all zero indices, recurse.
3383 bool AllZeros = true;
3384 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3385 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3386 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3387 AllZeros = false;
3388 break;
3389 }
3390 if (AllZeros)
3391 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3392 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003393
3394 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003395 AllZeros = true;
3396 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3397 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3398 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3399 AllZeros = false;
3400 break;
3401 }
3402 if (AllZeros)
3403 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3404
Chris Lattner4401c9c2005-01-14 00:20:05 +00003405 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3406 // If the GEPs only differ by one index, compare it.
3407 unsigned NumDifferences = 0; // Keep track of # differences.
3408 unsigned DiffOperand = 0; // The operand that differs.
3409 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3410 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00003411 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3412 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003413 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00003414 NumDifferences = 2;
3415 break;
3416 } else {
3417 if (NumDifferences++) break;
3418 DiffOperand = i;
3419 }
3420 }
3421
3422 if (NumDifferences == 0) // SAME GEP?
3423 return ReplaceInstUsesWith(I, // No comparison is needed here.
3424 ConstantBool::get(Cond == Instruction::SetEQ));
3425 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003426 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3427 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00003428
3429 // Convert the operands to signed values to make sure to perform a
3430 // signed comparison.
3431 const Type *NewTy = LHSV->getType()->getSignedVersion();
3432 if (LHSV->getType() != NewTy)
3433 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3434 LHSV->getName()), I);
3435 if (RHSV->getType() != NewTy)
3436 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3437 RHSV->getName()), I);
3438 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003439 }
3440 }
3441
Chris Lattner574da9b2005-01-13 20:14:25 +00003442 // Only lower this if the setcc is the only user of the GEP or if we expect
3443 // the result to fold to a constant!
3444 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3445 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3446 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3447 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3448 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3449 return new SetCondInst(Cond, L, R);
3450 }
3451 }
3452 return 0;
3453}
3454
3455
Chris Lattner484d3cf2005-04-24 06:59:08 +00003456Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003457 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00003458 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3459 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00003460
3461 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00003462 if (Op0 == Op1)
3463 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00003464
Chris Lattnere87597f2004-10-16 18:11:37 +00003465 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3466 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3467
Chris Lattner711b3402004-11-14 07:33:16 +00003468 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3469 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00003470 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3471 isa<ConstantPointerNull>(Op0)) &&
3472 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00003473 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00003474 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3475
3476 // setcc's with boolean values can always be turned into bitwise operations
3477 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00003478 switch (I.getOpcode()) {
3479 default: assert(0 && "Invalid setcc instruction!");
3480 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00003481 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00003482 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00003483 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00003484 }
Chris Lattner5dbef222004-08-11 00:50:51 +00003485 case Instruction::SetNE:
3486 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00003487
Chris Lattner5dbef222004-08-11 00:50:51 +00003488 case Instruction::SetGT:
3489 std::swap(Op0, Op1); // Change setgt -> setlt
3490 // FALL THROUGH
3491 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3492 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3493 InsertNewInstBefore(Not, I);
3494 return BinaryOperator::createAnd(Not, Op1);
3495 }
3496 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00003497 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00003498 // FALL THROUGH
3499 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3500 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3501 InsertNewInstBefore(Not, I);
3502 return BinaryOperator::createOr(Not, Op1);
3503 }
3504 }
Chris Lattner8b170942002-08-09 23:47:40 +00003505 }
3506
Chris Lattner2be51ae2004-06-09 04:24:29 +00003507 // See if we are doing a comparison between a constant and an instruction that
3508 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00003509 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003510 // Check to see if we are comparing against the minimum or maximum value...
3511 if (CI->isMinValue()) {
3512 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3513 return ReplaceInstUsesWith(I, ConstantBool::False);
3514 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3515 return ReplaceInstUsesWith(I, ConstantBool::True);
3516 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3517 return BinaryOperator::createSetEQ(Op0, Op1);
3518 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3519 return BinaryOperator::createSetNE(Op0, Op1);
3520
3521 } else if (CI->isMaxValue()) {
3522 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3523 return ReplaceInstUsesWith(I, ConstantBool::False);
3524 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3525 return ReplaceInstUsesWith(I, ConstantBool::True);
3526 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3527 return BinaryOperator::createSetEQ(Op0, Op1);
3528 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3529 return BinaryOperator::createSetNE(Op0, Op1);
3530
3531 // Comparing against a value really close to min or max?
3532 } else if (isMinValuePlusOne(CI)) {
3533 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3534 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3535 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3536 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3537
3538 } else if (isMaxValueMinusOne(CI)) {
3539 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3540 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3541 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3542 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3543 }
3544
3545 // If we still have a setle or setge instruction, turn it into the
3546 // appropriate setlt or setgt instruction. Since the border cases have
3547 // already been handled above, this requires little checking.
3548 //
3549 if (I.getOpcode() == Instruction::SetLE)
3550 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3551 if (I.getOpcode() == Instruction::SetGE)
3552 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3553
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003554
3555 // See if we can fold the comparison based on bits known to be zero or one
3556 // in the input.
3557 uint64_t KnownZero, KnownOne;
3558 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3559 KnownZero, KnownOne, 0))
3560 return &I;
3561
3562 // Given the known and unknown bits, compute a range that the LHS could be
3563 // in.
3564 if (KnownOne | KnownZero) {
3565 if (Ty->isUnsigned()) { // Unsigned comparison.
3566 uint64_t Min, Max;
3567 uint64_t RHSVal = CI->getZExtValue();
3568 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3569 Min, Max);
3570 switch (I.getOpcode()) { // LE/GE have been folded already.
3571 default: assert(0 && "Unknown setcc opcode!");
3572 case Instruction::SetEQ:
3573 if (Max < RHSVal || Min > RHSVal)
3574 return ReplaceInstUsesWith(I, ConstantBool::False);
3575 break;
3576 case Instruction::SetNE:
3577 if (Max < RHSVal || Min > RHSVal)
3578 return ReplaceInstUsesWith(I, ConstantBool::True);
3579 break;
3580 case Instruction::SetLT:
3581 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3582 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3583 break;
3584 case Instruction::SetGT:
3585 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3586 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3587 break;
3588 }
3589 } else { // Signed comparison.
3590 int64_t Min, Max;
3591 int64_t RHSVal = CI->getSExtValue();
3592 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3593 Min, Max);
3594 switch (I.getOpcode()) { // LE/GE have been folded already.
3595 default: assert(0 && "Unknown setcc opcode!");
3596 case Instruction::SetEQ:
3597 if (Max < RHSVal || Min > RHSVal)
3598 return ReplaceInstUsesWith(I, ConstantBool::False);
3599 break;
3600 case Instruction::SetNE:
3601 if (Max < RHSVal || Min > RHSVal)
3602 return ReplaceInstUsesWith(I, ConstantBool::True);
3603 break;
3604 case Instruction::SetLT:
3605 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3606 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3607 break;
3608 case Instruction::SetGT:
3609 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3610 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3611 break;
3612 }
3613 }
3614 }
3615
3616
Chris Lattner3c6a0d42004-05-25 06:32:08 +00003617 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00003618 switch (LHSI->getOpcode()) {
3619 case Instruction::And:
3620 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3621 LHSI->getOperand(0)->hasOneUse()) {
3622 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3623 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3624 // happens a LOT in code produced by the C front-end, for bitfield
3625 // access.
3626 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003627 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3628
3629 // Check to see if there is a noop-cast between the shift and the and.
3630 if (!Shift) {
3631 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3632 if (CI->getOperand(0)->getType()->isIntegral() &&
3633 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3634 CI->getType()->getPrimitiveSizeInBits())
3635 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3636 }
3637
Chris Lattner648e3bc2004-09-23 21:52:49 +00003638 ConstantUInt *ShAmt;
3639 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003640 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3641 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00003642
Chris Lattner648e3bc2004-09-23 21:52:49 +00003643 // We can fold this as long as we can't shift unknown bits
3644 // into the mask. This can only happen with signed shift
3645 // rights, as they sign-extend.
3646 if (ShAmt) {
3647 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003648 Ty->isUnsigned();
Chris Lattner648e3bc2004-09-23 21:52:49 +00003649 if (!CanFold) {
3650 // To test for the bad case of the signed shr, see if any
3651 // of the bits shifted in could be tested after the mask.
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00003652 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3653 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3654
3655 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00003656 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003657 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3658 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00003659 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3660 CanFold = true;
3661 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003662
Chris Lattner648e3bc2004-09-23 21:52:49 +00003663 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00003664 Constant *NewCst;
3665 if (Shift->getOpcode() == Instruction::Shl)
3666 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3667 else
3668 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00003669
Chris Lattner648e3bc2004-09-23 21:52:49 +00003670 // Check to see if we are shifting out any of the bits being
3671 // compared.
3672 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3673 // If we shifted bits out, the fold is not going to work out.
3674 // As a special case, check to see if this means that the
3675 // result is always true or false now.
3676 if (I.getOpcode() == Instruction::SetEQ)
3677 return ReplaceInstUsesWith(I, ConstantBool::False);
3678 if (I.getOpcode() == Instruction::SetNE)
3679 return ReplaceInstUsesWith(I, ConstantBool::True);
3680 } else {
3681 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00003682 Constant *NewAndCST;
3683 if (Shift->getOpcode() == Instruction::Shl)
3684 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3685 else
3686 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3687 LHSI->setOperand(1, NewAndCST);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00003688 if (AndTy == Ty)
3689 LHSI->setOperand(0, Shift->getOperand(0));
3690 else {
3691 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3692 *Shift);
3693 LHSI->setOperand(0, NewCast);
3694 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003695 WorkList.push_back(Shift); // Shift is dead.
3696 AddUsesToWorkList(I);
3697 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00003698 }
3699 }
Chris Lattner457dd822004-06-09 07:59:58 +00003700 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00003701 }
3702 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00003703
Chris Lattner18d19ca2004-09-28 18:22:15 +00003704 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3705 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3706 switch (I.getOpcode()) {
3707 default: break;
3708 case Instruction::SetEQ:
3709 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003710 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3711
3712 // Check that the shift amount is in range. If not, don't perform
3713 // undefined shifts. When the shift is visited it will be
3714 // simplified.
3715 if (ShAmt->getValue() >= TypeBits)
3716 break;
3717
Chris Lattner18d19ca2004-09-28 18:22:15 +00003718 // If we are comparing against bits always shifted out, the
3719 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003720 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00003721 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3722 if (Comp != CI) {// Comparing against a bit that we know is zero.
3723 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3724 Constant *Cst = ConstantBool::get(IsSetNE);
3725 return ReplaceInstUsesWith(I, Cst);
3726 }
3727
3728 if (LHSI->hasOneUse()) {
3729 // Otherwise strength reduce the shift into an and.
Chris Lattner652f3cf2005-01-08 19:42:22 +00003730 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003731 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3732
3733 Constant *Mask;
3734 if (CI->getType()->isUnsigned()) {
3735 Mask = ConstantUInt::get(CI->getType(), Val);
3736 } else if (ShAmtVal != 0) {
3737 Mask = ConstantSInt::get(CI->getType(), Val);
3738 } else {
3739 Mask = ConstantInt::getAllOnesValue(CI->getType());
3740 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003741
Chris Lattner18d19ca2004-09-28 18:22:15 +00003742 Instruction *AndI =
3743 BinaryOperator::createAnd(LHSI->getOperand(0),
3744 Mask, LHSI->getName()+".mask");
3745 Value *And = InsertNewInstBefore(AndI, I);
3746 return new SetCondInst(I.getOpcode(), And,
3747 ConstantExpr::getUShr(CI, ShAmt));
3748 }
3749 }
3750 }
3751 }
3752 break;
3753
Chris Lattner83c4ec02004-09-27 19:29:18 +00003754 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Chris Lattnerf63f6472004-09-27 16:18:50 +00003755 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
Chris Lattnerf63f6472004-09-27 16:18:50 +00003756 switch (I.getOpcode()) {
3757 default: break;
3758 case Instruction::SetEQ:
3759 case Instruction::SetNE: {
Chris Lattnere17a1282005-06-15 20:53:31 +00003760
3761 // Check that the shift amount is in range. If not, don't perform
3762 // undefined shifts. When the shift is visited it will be
3763 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00003764 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Chris Lattnere17a1282005-06-15 20:53:31 +00003765 if (ShAmt->getValue() >= TypeBits)
3766 break;
3767
Chris Lattnerf63f6472004-09-27 16:18:50 +00003768 // If we are comparing against bits always shifted out, the
3769 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00003770 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00003771 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00003772
Chris Lattnerf63f6472004-09-27 16:18:50 +00003773 if (Comp != CI) {// Comparing against a bit that we know is zero.
3774 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3775 Constant *Cst = ConstantBool::get(IsSetNE);
3776 return ReplaceInstUsesWith(I, Cst);
3777 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003778
Chris Lattnerf63f6472004-09-27 16:18:50 +00003779 if (LHSI->hasOneUse() || CI->isNullValue()) {
Chris Lattner652f3cf2005-01-08 19:42:22 +00003780 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00003781
Chris Lattnerf63f6472004-09-27 16:18:50 +00003782 // Otherwise strength reduce the shift into an and.
3783 uint64_t Val = ~0ULL; // All ones.
3784 Val <<= ShAmtVal; // Shift over to the right spot.
3785
3786 Constant *Mask;
3787 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00003788 Val &= ~0ULL >> (64-TypeBits);
Chris Lattnerf63f6472004-09-27 16:18:50 +00003789 Mask = ConstantUInt::get(CI->getType(), Val);
3790 } else {
3791 Mask = ConstantSInt::get(CI->getType(), Val);
3792 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003793
Chris Lattnerf63f6472004-09-27 16:18:50 +00003794 Instruction *AndI =
3795 BinaryOperator::createAnd(LHSI->getOperand(0),
3796 Mask, LHSI->getName()+".mask");
3797 Value *And = InsertNewInstBefore(AndI, I);
3798 return new SetCondInst(I.getOpcode(), And,
3799 ConstantExpr::getShl(CI, ShAmt));
3800 }
3801 break;
3802 }
3803 }
3804 }
3805 break;
Chris Lattner0c967662004-09-24 15:21:34 +00003806
Chris Lattnera96879a2004-09-29 17:40:11 +00003807 case Instruction::Div:
3808 // Fold: (div X, C1) op C2 -> range check
3809 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3810 // Fold this div into the comparison, producing a range check.
3811 // Determine, based on the divide type, what the range is being
3812 // checked. If there is an overflow on the low or high side, remember
3813 // it, otherwise compute the range [low, hi) bounding the new value.
3814 bool LoOverflow = false, HiOverflow = 0;
3815 ConstantInt *LoBound = 0, *HiBound = 0;
3816
3817 ConstantInt *Prod;
3818 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3819
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003820 Instruction::BinaryOps Opcode = I.getOpcode();
3821
Chris Lattnera96879a2004-09-29 17:40:11 +00003822 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3823 } else if (LHSI->getType()->isUnsigned()) { // udiv
3824 LoBound = Prod;
3825 LoOverflow = ProdOV;
3826 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3827 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3828 if (CI->isNullValue()) { // (X / pos) op 0
3829 // Can't overflow.
3830 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3831 HiBound = DivRHS;
3832 } else if (isPositive(CI)) { // (X / pos) op pos
3833 LoBound = Prod;
3834 LoOverflow = ProdOV;
3835 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3836 } else { // (X / pos) op neg
3837 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3838 LoOverflow = AddWithOverflow(LoBound, Prod,
3839 cast<ConstantInt>(DivRHSH));
3840 HiBound = Prod;
3841 HiOverflow = ProdOV;
3842 }
3843 } else { // Divisor is < 0.
3844 if (CI->isNullValue()) { // (X / neg) op 0
3845 LoBound = AddOne(DivRHS);
3846 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00003847 if (HiBound == DivRHS)
3848 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00003849 } else if (isPositive(CI)) { // (X / neg) op pos
3850 HiOverflow = LoOverflow = ProdOV;
3851 if (!LoOverflow)
3852 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3853 HiBound = AddOne(Prod);
3854 } else { // (X / neg) op neg
3855 LoBound = Prod;
3856 LoOverflow = HiOverflow = ProdOV;
3857 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3858 }
Chris Lattner340a05f2004-10-08 19:15:44 +00003859
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003860 // Dividing by a negate swaps the condition.
3861 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00003862 }
3863
3864 if (LoBound) {
3865 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00003866 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00003867 default: assert(0 && "Unhandled setcc opcode!");
3868 case Instruction::SetEQ:
3869 if (LoOverflow && HiOverflow)
3870 return ReplaceInstUsesWith(I, ConstantBool::False);
3871 else if (HiOverflow)
3872 return new SetCondInst(Instruction::SetGE, X, LoBound);
3873 else if (LoOverflow)
3874 return new SetCondInst(Instruction::SetLT, X, HiBound);
3875 else
3876 return InsertRangeTest(X, LoBound, HiBound, true, I);
3877 case Instruction::SetNE:
3878 if (LoOverflow && HiOverflow)
3879 return ReplaceInstUsesWith(I, ConstantBool::True);
3880 else if (HiOverflow)
3881 return new SetCondInst(Instruction::SetLT, X, LoBound);
3882 else if (LoOverflow)
3883 return new SetCondInst(Instruction::SetGE, X, HiBound);
3884 else
3885 return InsertRangeTest(X, LoBound, HiBound, false, I);
3886 case Instruction::SetLT:
3887 if (LoOverflow)
3888 return ReplaceInstUsesWith(I, ConstantBool::False);
3889 return new SetCondInst(Instruction::SetLT, X, LoBound);
3890 case Instruction::SetGT:
3891 if (HiOverflow)
3892 return ReplaceInstUsesWith(I, ConstantBool::False);
3893 return new SetCondInst(Instruction::SetGE, X, HiBound);
3894 }
3895 }
3896 }
3897 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00003898 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003899
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003900 // Simplify seteq and setne instructions...
3901 if (I.getOpcode() == Instruction::SetEQ ||
3902 I.getOpcode() == Instruction::SetNE) {
3903 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3904
Chris Lattner00b1a7e2003-07-23 17:26:36 +00003905 // If the first operand is (and|or|xor) with a constant, and the second
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003906 // operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00003907 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3908 switch (BO->getOpcode()) {
Chris Lattner3571b722004-07-06 07:38:18 +00003909 case Instruction::Rem:
3910 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3911 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3912 BO->hasOneUse() &&
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003913 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3914 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3915 if (isPowerOf2_64(V)) {
3916 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00003917 const Type *UTy = BO->getType()->getUnsignedVersion();
3918 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3919 UTy, "tmp"), I);
3920 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3921 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3922 RHSCst, BO->getName()), I);
3923 return BinaryOperator::create(I.getOpcode(), NewRem,
3924 Constant::getNullValue(UTy));
3925 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003926 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003927 break;
Chris Lattner3571b722004-07-06 07:38:18 +00003928
Chris Lattner934754b2003-08-13 05:33:12 +00003929 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00003930 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3931 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00003932 if (BO->hasOneUse())
3933 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3934 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00003935 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003936 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3937 // efficiently invertible, or if the add has just this one use.
3938 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003939
Chris Lattner934754b2003-08-13 05:33:12 +00003940 if (Value *NegVal = dyn_castNegVal(BOp1))
3941 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3942 else if (Value *NegVal = dyn_castNegVal(BOp0))
3943 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00003944 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00003945 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3946 BO->setName("");
3947 InsertNewInstBefore(Neg, I);
3948 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3949 }
3950 }
3951 break;
3952 case Instruction::Xor:
3953 // For the xor case, we can xor two constants together, eliminating
3954 // the explicit xor.
3955 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3956 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00003957 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00003958
3959 // FALLTHROUGH
3960 case Instruction::Sub:
3961 // Replace (([sub|xor] A, B) != 0) with (A != B)
3962 if (CI->isNullValue())
3963 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3964 BO->getOperand(1));
3965 break;
3966
3967 case Instruction::Or:
3968 // If bits are being or'd in that are not present in the constant we
3969 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00003970 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00003971 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00003972 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003973 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003974 }
Chris Lattner934754b2003-08-13 05:33:12 +00003975 break;
3976
3977 case Instruction::And:
3978 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003979 // If bits are being compared against that are and'd out, then the
3980 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00003981 if (!ConstantExpr::getAnd(CI,
3982 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00003983 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00003984
Chris Lattner457dd822004-06-09 07:59:58 +00003985 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00003986 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00003987 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3988 Instruction::SetNE, Op0,
3989 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00003990
Chris Lattner934754b2003-08-13 05:33:12 +00003991 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3992 // to be a signed value as appropriate.
3993 if (isSignBit(BOC)) {
3994 Value *X = BO->getOperand(0);
3995 // If 'X' is not signed, insert a cast now...
3996 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00003997 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00003998 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00003999 }
4000 return new SetCondInst(isSetNE ? Instruction::SetLT :
4001 Instruction::SetGE, X,
4002 Constant::getNullValue(X->getType()));
4003 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004004
Chris Lattner83c4ec02004-09-27 19:29:18 +00004005 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004006 if (CI->isNullValue() && isHighOnes(BOC)) {
4007 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004008 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004009
4010 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00004011 if (NegX->getType()->isSigned()) {
4012 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4013 X = InsertCastBefore(X, DestTy, I);
4014 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004015 }
4016
4017 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00004018 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004019 }
4020
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004021 }
Chris Lattner934754b2003-08-13 05:33:12 +00004022 default: break;
4023 }
4024 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004025 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00004026 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004027 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4028 Value *CastOp = Cast->getOperand(0);
4029 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004030 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004031 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004032 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004033 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004034 "Source and destination signednesses should differ!");
4035 if (Cast->getType()->isSigned()) {
4036 // If this is a signed comparison, check for comparisons in the
4037 // vicinity of zero.
4038 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4039 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00004040 return BinaryOperator::createSetGT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00004041 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004042 else if (I.getOpcode() == Instruction::SetGT &&
4043 cast<ConstantSInt>(CI)->getValue() == -1)
4044 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00004045 return BinaryOperator::createSetLT(CastOp,
Chris Lattner484d3cf2005-04-24 06:59:08 +00004046 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004047 } else {
4048 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4049 if (I.getOpcode() == Instruction::SetLT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004050 CUI->getValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004051 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00004052 return BinaryOperator::createSetGT(CastOp,
4053 ConstantSInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004054 else if (I.getOpcode() == Instruction::SetGT &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004055 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004056 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00004057 return BinaryOperator::createSetLT(CastOp,
4058 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004059 }
4060 }
4061 }
Chris Lattner40f5d702003-06-04 05:10:11 +00004062 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004063 }
4064
Chris Lattner6970b662005-04-23 15:31:55 +00004065 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4066 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4067 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4068 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00004069 case Instruction::GetElementPtr:
4070 if (RHSC->isNullValue()) {
4071 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4072 bool isAllZeros = true;
4073 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4074 if (!isa<Constant>(LHSI->getOperand(i)) ||
4075 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4076 isAllZeros = false;
4077 break;
4078 }
4079 if (isAllZeros)
4080 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4081 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4082 }
4083 break;
4084
Chris Lattner6970b662005-04-23 15:31:55 +00004085 case Instruction::PHI:
4086 if (Instruction *NV = FoldOpIntoPhi(I))
4087 return NV;
4088 break;
4089 case Instruction::Select:
4090 // If either operand of the select is a constant, we can fold the
4091 // comparison into the select arms, which will cause one to be
4092 // constant folded and the select turned into a bitwise or.
4093 Value *Op1 = 0, *Op2 = 0;
4094 if (LHSI->hasOneUse()) {
4095 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4096 // Fold the known value into the constant operand.
4097 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4098 // Insert a new SetCC of the other select operand.
4099 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4100 LHSI->getOperand(2), RHSC,
4101 I.getName()), I);
4102 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4103 // Fold the known value into the constant operand.
4104 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4105 // Insert a new SetCC of the other select operand.
4106 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4107 LHSI->getOperand(1), RHSC,
4108 I.getName()), I);
4109 }
4110 }
Jeff Cohen9d809302005-04-23 21:38:35 +00004111
Chris Lattner6970b662005-04-23 15:31:55 +00004112 if (Op1)
4113 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4114 break;
4115 }
4116 }
4117
Chris Lattner574da9b2005-01-13 20:14:25 +00004118 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4119 if (User *GEP = dyn_castGetElementPtr(Op0))
4120 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4121 return NI;
4122 if (User *GEP = dyn_castGetElementPtr(Op1))
4123 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4124 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4125 return NI;
4126
Chris Lattnerde90b762003-11-03 04:25:02 +00004127 // Test to see if the operands of the setcc are casted versions of other
4128 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00004129 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4130 Value *CastOp0 = CI->getOperand(0);
4131 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner0cea42a2004-03-13 23:54:27 +00004132 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
Chris Lattnerde90b762003-11-03 04:25:02 +00004133 (I.getOpcode() == Instruction::SetEQ ||
4134 I.getOpcode() == Instruction::SetNE)) {
4135 // We keep moving the cast from the left operand over to the right
4136 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00004137 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00004138
Chris Lattnerde90b762003-11-03 04:25:02 +00004139 // If operand #1 is a cast instruction, see if we can eliminate it as
4140 // well.
Chris Lattner68708052003-11-03 05:17:03 +00004141 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4142 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00004143 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00004144 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00004145
Chris Lattnerde90b762003-11-03 04:25:02 +00004146 // If Op1 is a constant, we can fold the cast into the constant.
4147 if (Op1->getType() != Op0->getType())
4148 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4149 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4150 } else {
4151 // Otherwise, cast the RHS right before the setcc
4152 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4153 InsertNewInstBefore(cast<Instruction>(Op1), I);
4154 }
4155 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4156 }
4157
Chris Lattner68708052003-11-03 05:17:03 +00004158 // Handle the special case of: setcc (cast bool to X), <cst>
4159 // This comes up when you have code like
4160 // int X = A < B;
4161 // if (X) ...
4162 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00004163 // with a constant or another cast from the same type.
4164 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4165 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4166 return R;
Chris Lattner68708052003-11-03 05:17:03 +00004167 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00004168
4169 if (I.getOpcode() == Instruction::SetNE ||
4170 I.getOpcode() == Instruction::SetEQ) {
4171 Value *A, *B;
4172 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4173 (A == Op1 || B == Op1)) {
4174 // (A^B) == A -> B == 0
4175 Value *OtherVal = A == Op1 ? B : A;
4176 return BinaryOperator::create(I.getOpcode(), OtherVal,
4177 Constant::getNullValue(A->getType()));
4178 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4179 (A == Op0 || B == Op0)) {
4180 // A == (A^B) -> B == 0
4181 Value *OtherVal = A == Op0 ? B : A;
4182 return BinaryOperator::create(I.getOpcode(), OtherVal,
4183 Constant::getNullValue(A->getType()));
4184 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4185 // (A-B) == A -> B == 0
4186 return BinaryOperator::create(I.getOpcode(), B,
4187 Constant::getNullValue(B->getType()));
4188 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4189 // A == (A-B) -> B == 0
4190 return BinaryOperator::create(I.getOpcode(), B,
4191 Constant::getNullValue(B->getType()));
4192 }
4193 }
Chris Lattner7e708292002-06-25 16:13:24 +00004194 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004195}
4196
Chris Lattner484d3cf2005-04-24 06:59:08 +00004197// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4198// We only handle extending casts so far.
4199//
4200Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4201 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4202 const Type *SrcTy = LHSCIOp->getType();
4203 const Type *DestTy = SCI.getOperand(0)->getType();
4204 Value *RHSCIOp;
4205
4206 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00004207 return 0;
4208
Chris Lattner484d3cf2005-04-24 06:59:08 +00004209 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4210 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4211 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4212
4213 // Is this a sign or zero extension?
4214 bool isSignSrc = SrcTy->isSigned();
4215 bool isSignDest = DestTy->isSigned();
4216
4217 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4218 // Not an extension from the same type?
4219 RHSCIOp = CI->getOperand(0);
4220 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4221 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4222 // Compute the constant that would happen if we truncated to SrcTy then
4223 // reextended to DestTy.
4224 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4225
4226 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4227 RHSCIOp = Res;
4228 } else {
4229 // If the value cannot be represented in the shorter type, we cannot emit
4230 // a simple comparison.
4231 if (SCI.getOpcode() == Instruction::SetEQ)
4232 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4233 if (SCI.getOpcode() == Instruction::SetNE)
4234 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4235
Chris Lattner484d3cf2005-04-24 06:59:08 +00004236 // Evaluate the comparison for LT.
4237 Value *Result;
4238 if (DestTy->isSigned()) {
4239 // We're performing a signed comparison.
4240 if (isSignSrc) {
4241 // Signed extend and signed comparison.
4242 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4243 Result = ConstantBool::False;
4244 else
4245 Result = ConstantBool::True; // X < (large) --> true
4246 } else {
4247 // Unsigned extend and signed comparison.
4248 if (cast<ConstantSInt>(CI)->getValue() < 0)
4249 Result = ConstantBool::False;
4250 else
4251 Result = ConstantBool::True;
4252 }
4253 } else {
4254 // We're performing an unsigned comparison.
4255 if (!isSignSrc) {
4256 // Unsigned extend & compare -> always true.
4257 Result = ConstantBool::True;
4258 } else {
4259 // We're performing an unsigned comp with a sign extended value.
4260 // This is true if the input is >= 0. [aka >s -1]
4261 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4262 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4263 NegOne, SCI.getName()), SCI);
4264 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00004265 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004266
Jeff Cohen00b168892005-07-27 06:12:32 +00004267 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00004268 if (SCI.getOpcode() == Instruction::SetLT) {
4269 return ReplaceInstUsesWith(SCI, Result);
4270 } else {
4271 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4272 if (Constant *CI = dyn_cast<Constant>(Result))
4273 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4274 else
4275 return BinaryOperator::createNot(Result);
4276 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004277 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00004278 } else {
4279 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00004280 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004281
Chris Lattner8d7089e2005-06-16 03:00:08 +00004282 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00004283 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4284}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004285
Chris Lattnerea340052003-03-10 19:16:08 +00004286Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00004287 assert(I.getOperand(1)->getType() == Type::UByteTy);
4288 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00004289 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004290
4291 // shl X, 0 == X and shr X, 0 == X
4292 // shl 0, X == 0 and shr 0, X == 0
4293 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00004294 Op0 == Constant::getNullValue(Op0->getType()))
4295 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004296
Chris Lattnere87597f2004-10-16 18:11:37 +00004297 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4298 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00004299 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00004300 else // undef << X -> 0 AND undef >>u X -> 0
4301 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4302 }
4303 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00004304 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00004305 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4306 else
4307 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4308 }
4309
Chris Lattnerdf17af12003-08-12 21:53:41 +00004310 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4311 if (!isLeftShift)
4312 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4313 if (CSI->isAllOnesValue())
4314 return ReplaceInstUsesWith(I, CSI);
4315
Chris Lattner2eefe512004-04-09 19:05:30 +00004316 // Try to fold constant and into select arguments.
4317 if (isa<Constant>(Op0))
4318 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004319 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004320 return R;
4321
Chris Lattner120347e2005-05-08 17:34:56 +00004322 // See if we can turn a signed shr into an unsigned shr.
4323 if (!isLeftShift && I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00004324 if (MaskedValueIsZero(Op0,
4325 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattner120347e2005-05-08 17:34:56 +00004326 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4327 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4328 I.getName()), I);
4329 return new CastInst(V, I.getType());
4330 }
4331 }
Jeff Cohen00b168892005-07-27 06:12:32 +00004332
Chris Lattner4d5542c2006-01-06 07:12:35 +00004333 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4334 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4335 return Res;
4336 return 0;
4337}
4338
4339Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4340 ShiftInst &I) {
4341 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner830ed032006-01-06 07:22:22 +00004342 bool isSignedShift = Op0->getType()->isSigned();
4343 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004344
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004345 // See if we can simplify any instructions used by the instruction whose sole
4346 // purpose is to compute bits we don't care about.
4347 uint64_t KnownZero, KnownOne;
4348 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4349 KnownZero, KnownOne))
4350 return &I;
4351
Chris Lattner4d5542c2006-01-06 07:12:35 +00004352 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4353 // of a signed value.
4354 //
4355 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4356 if (Op1->getValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00004357 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00004358 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4359 else {
4360 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4361 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00004362 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004363 }
4364
4365 // ((X*C1) << C2) == (X * (C1 << C2))
4366 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4367 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4368 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4369 return BinaryOperator::createMul(BO->getOperand(0),
4370 ConstantExpr::getShl(BOOp, Op1));
4371
4372 // Try to fold constant and into select arguments.
4373 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4374 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4375 return R;
4376 if (isa<PHINode>(Op0))
4377 if (Instruction *NV = FoldOpIntoPhi(I))
4378 return NV;
4379
4380 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004381 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4382 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4383 Value *V1, *V2;
4384 ConstantInt *CC;
4385 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00004386 default: break;
4387 case Instruction::Add:
4388 case Instruction::And:
4389 case Instruction::Or:
4390 case Instruction::Xor:
4391 // These operators commute.
4392 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004393 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4394 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004395 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004396 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004397 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004398 Op0BO->getName());
4399 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004400 Instruction *X =
4401 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4402 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00004403 InsertNewInstBefore(X, I); // (X + (Y << C))
4404 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00004405 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00004406 return BinaryOperator::createAnd(X, C2);
4407 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004408
Chris Lattner150f12a2005-09-18 06:30:59 +00004409 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4410 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4411 match(Op0BO->getOperand(1),
4412 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004413 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004414 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004415 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004416 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004417 Op0BO->getName());
4418 InsertNewInstBefore(YS, I); // (Y << C)
4419 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00004420 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00004421 V1->getName()+".mask");
4422 InsertNewInstBefore(XM, I); // X & (CC << C)
4423
4424 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4425 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004426
Chris Lattner150f12a2005-09-18 06:30:59 +00004427 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00004428 case Instruction::Sub:
4429 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004430 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4431 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004432 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004433 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004434 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004435 Op0BO->getName());
4436 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004437 Instruction *X =
4438 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4439 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00004440 InsertNewInstBefore(X, I); // (X + (Y << C))
4441 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00004442 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00004443 return BinaryOperator::createAnd(X, C2);
4444 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004445
Chris Lattner150f12a2005-09-18 06:30:59 +00004446 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4447 match(Op0BO->getOperand(0),
4448 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004449 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00004450 cast<BinaryOperator>(Op0BO->getOperand(0))
4451 ->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00004452 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004453 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00004454 Op0BO->getName());
4455 InsertNewInstBefore(YS, I); // (Y << C)
4456 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00004457 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00004458 V1->getName()+".mask");
4459 InsertNewInstBefore(XM, I); // X & (CC << C)
4460
4461 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4462 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004463
Chris Lattner11021cb2005-09-18 05:12:10 +00004464 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004465 }
4466
4467
4468 // If the operand is an bitwise operator with a constant RHS, and the
4469 // shift is the only use, we can pull it out of the shift.
4470 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4471 bool isValid = true; // Valid only for And, Or, Xor
4472 bool highBitSet = false; // Transform if high bit of constant set?
4473
4474 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00004475 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00004476 case Instruction::Add:
4477 isValid = isLeftShift;
4478 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00004479 case Instruction::Or:
4480 case Instruction::Xor:
4481 highBitSet = false;
4482 break;
4483 case Instruction::And:
4484 highBitSet = true;
4485 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004486 }
4487
4488 // If this is a signed shift right, and the high bit is modified
4489 // by the logical operation, do not perform the transformation.
4490 // The highBitSet boolean indicates the value of the high bit of
4491 // the constant which would cause it to be modified for this
4492 // operation.
4493 //
Chris Lattner830ed032006-01-06 07:22:22 +00004494 if (isValid && !isLeftShift && isSignedShift) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004495 uint64_t Val = Op0C->getRawValue();
4496 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4497 }
4498
4499 if (isValid) {
4500 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4501
4502 Instruction *NewShift =
4503 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4504 Op0BO->getName());
4505 Op0BO->setName("");
4506 InsertNewInstBefore(NewShift, I);
4507
4508 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4509 NewRHS);
4510 }
4511 }
4512 }
4513 }
4514
Chris Lattnerad0124c2006-01-06 07:52:12 +00004515 // Find out if this is a shift of a shift by a constant.
4516 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004517 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00004518 ShiftOp = Op0SI;
4519 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4520 // If this is a noop-integer case of a shift instruction, use the shift.
4521 if (CI->getOperand(0)->getType()->isInteger() &&
4522 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4523 CI->getType()->getPrimitiveSizeInBits() &&
4524 isa<ShiftInst>(CI->getOperand(0))) {
4525 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4526 }
4527 }
4528
4529 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4530 // Find the operands and properties of the input shift. Note that the
4531 // signedness of the input shift may differ from the current shift if there
4532 // is a noop cast between the two.
4533 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4534 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattnere8d56c52006-01-07 01:32:28 +00004535 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00004536
4537 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4538
4539 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4540 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4541
4542 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4543 if (isLeftShift == isShiftOfLeftShift) {
4544 // Do not fold these shifts if the first one is signed and the second one
4545 // is unsigned and this is a right shift. Further, don't do any folding
4546 // on them.
4547 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4548 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004549
Chris Lattnerad0124c2006-01-06 07:52:12 +00004550 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4551 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4552 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00004553
Chris Lattnerad0124c2006-01-06 07:52:12 +00004554 Value *Op = ShiftOp->getOperand(0);
4555 if (isShiftOfSignedShift != isSignedShift)
4556 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4557 return new ShiftInst(I.getOpcode(), Op,
4558 ConstantUInt::get(Type::UByteTy, Amt));
4559 }
4560
4561 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4562 // signed types, we can only support the (A >> c1) << c2 configuration,
4563 // because it can not turn an arbitrary bit of A into a sign bit.
4564 if (isUnsignedShift || isLeftShift) {
4565 // Calculate bitmask for what gets shifted off the edge.
4566 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4567 if (isLeftShift)
4568 C = ConstantExpr::getShl(C, ShiftAmt1C);
4569 else
Chris Lattnere8d56c52006-01-07 01:32:28 +00004570 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00004571
4572 Value *Op = ShiftOp->getOperand(0);
4573 if (isShiftOfSignedShift != isSignedShift)
4574 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4575
4576 Instruction *Mask =
4577 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4578 InsertNewInstBefore(Mask, I);
4579
4580 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00004581 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004582 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00004583 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004584 return new ShiftInst(I.getOpcode(), Mask,
4585 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004586 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4587 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4588 // Make sure to emit an unsigned shift right, not a signed one.
4589 Mask = InsertNewInstBefore(new CastInst(Mask,
4590 Mask->getType()->getUnsignedVersion(),
4591 Op->getName()), I);
4592 Mask = new ShiftInst(Instruction::Shr, Mask,
Chris Lattnerad0124c2006-01-06 07:52:12 +00004593 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00004594 InsertNewInstBefore(Mask, I);
4595 return new CastInst(Mask, I.getType());
4596 } else {
4597 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4598 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4599 }
4600 } else {
4601 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4602 Op = InsertNewInstBefore(new CastInst(Mask,
4603 I.getType()->getSignedVersion(),
4604 Mask->getName()), I);
4605 Instruction *Shift =
4606 new ShiftInst(ShiftOp->getOpcode(), Op,
4607 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4608 InsertNewInstBefore(Shift, I);
4609
4610 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4611 C = ConstantExpr::getShl(C, Op1);
4612 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4613 InsertNewInstBefore(Mask, I);
4614 return new CastInst(Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00004615 }
4616 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00004617 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00004618 // this case, C1 == C2 and C1 is 8, 16, or 32.
4619 if (ShiftAmt1 == ShiftAmt2) {
4620 const Type *SExtType = 0;
Chris Lattner94046b42006-04-28 22:21:41 +00004621 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00004622 case 8 : SExtType = Type::SByteTy; break;
4623 case 16: SExtType = Type::ShortTy; break;
4624 case 32: SExtType = Type::IntTy; break;
4625 }
4626
4627 if (SExtType) {
4628 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4629 SExtType, "sext");
4630 InsertNewInstBefore(NewTrunc, I);
4631 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00004632 }
Chris Lattner11021cb2005-09-18 05:12:10 +00004633 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00004634 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00004635 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004636 return 0;
4637}
4638
Chris Lattnera1be5662002-05-02 17:06:02 +00004639
Chris Lattnercfd65102005-10-29 04:36:15 +00004640/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4641/// expression. If so, decompose it, returning some value X, such that Val is
4642/// X*Scale+Offset.
4643///
4644static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4645 unsigned &Offset) {
4646 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4647 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4648 Offset = CI->getValue();
4649 Scale = 1;
4650 return ConstantUInt::get(Type::UIntTy, 0);
4651 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4652 if (I->getNumOperands() == 2) {
4653 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4654 if (I->getOpcode() == Instruction::Shl) {
4655 // This is a value scaled by '1 << the shift amt'.
4656 Scale = 1U << CUI->getValue();
4657 Offset = 0;
4658 return I->getOperand(0);
4659 } else if (I->getOpcode() == Instruction::Mul) {
4660 // This value is scaled by 'CUI'.
4661 Scale = CUI->getValue();
4662 Offset = 0;
4663 return I->getOperand(0);
4664 } else if (I->getOpcode() == Instruction::Add) {
4665 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4666 // divisible by C2.
4667 unsigned SubScale;
4668 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4669 Offset);
4670 Offset += CUI->getValue();
4671 if (SubScale > 1 && (Offset % SubScale == 0)) {
4672 Scale = SubScale;
4673 return SubVal;
4674 }
4675 }
4676 }
4677 }
4678 }
4679
4680 // Otherwise, we can't look past this.
4681 Scale = 1;
4682 Offset = 0;
4683 return Val;
4684}
4685
4686
Chris Lattnerb3f83972005-10-24 06:03:58 +00004687/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4688/// try to eliminate the cast by moving the type information into the alloc.
4689Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4690 AllocationInst &AI) {
4691 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004692 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00004693
Chris Lattnerb53c2382005-10-24 06:22:12 +00004694 // Remove any uses of AI that are dead.
4695 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4696 std::vector<Instruction*> DeadUsers;
4697 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4698 Instruction *User = cast<Instruction>(*UI++);
4699 if (isInstructionTriviallyDead(User)) {
4700 while (UI != E && *UI == User)
4701 ++UI; // If this instruction uses AI more than once, don't break UI.
4702
4703 // Add operands to the worklist.
4704 AddUsesToWorkList(*User);
4705 ++NumDeadInst;
4706 DEBUG(std::cerr << "IC: DCE: " << *User);
4707
4708 User->eraseFromParent();
4709 removeFromWorkList(User);
4710 }
4711 }
4712
Chris Lattnerb3f83972005-10-24 06:03:58 +00004713 // Get the type really allocated and the type casted to.
4714 const Type *AllocElTy = AI.getAllocatedType();
4715 const Type *CastElTy = PTy->getElementType();
4716 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004717
4718 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4719 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4720 if (CastElTyAlign < AllocElTyAlign) return 0;
4721
Chris Lattner39387a52005-10-24 06:35:18 +00004722 // If the allocation has multiple uses, only promote it if we are strictly
4723 // increasing the alignment of the resultant allocation. If we keep it the
4724 // same, we open the door to infinite loops of various kinds.
4725 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4726
Chris Lattnerb3f83972005-10-24 06:03:58 +00004727 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4728 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004729 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00004730
Chris Lattner455fcc82005-10-29 03:19:53 +00004731 // See if we can satisfy the modulus by pulling a scale out of the array
4732 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00004733 unsigned ArraySizeScale, ArrayOffset;
4734 Value *NumElements = // See if the array size is a decomposable linear expr.
4735 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4736
Chris Lattner455fcc82005-10-29 03:19:53 +00004737 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4738 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00004739 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4740 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00004741
Chris Lattner455fcc82005-10-29 03:19:53 +00004742 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4743 Value *Amt = 0;
4744 if (Scale == 1) {
4745 Amt = NumElements;
4746 } else {
4747 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4748 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4749 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4750 else if (Scale != 1) {
4751 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4752 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00004753 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00004754 }
4755
Chris Lattnercfd65102005-10-29 04:36:15 +00004756 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4757 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4758 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4759 Amt = InsertNewInstBefore(Tmp, AI);
4760 }
4761
Chris Lattnerb3f83972005-10-24 06:03:58 +00004762 std::string Name = AI.getName(); AI.setName("");
4763 AllocationInst *New;
4764 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00004765 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004766 else
Nate Begeman14b05292005-11-05 09:21:28 +00004767 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00004768 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00004769
4770 // If the allocation has multiple uses, insert a cast and change all things
4771 // that used it to use the new cast. This will also hack on CI, but it will
4772 // die soon.
4773 if (!AI.hasOneUse()) {
4774 AddUsesToWorkList(AI);
4775 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4776 InsertNewInstBefore(NewCast, AI);
4777 AI.replaceAllUsesWith(NewCast);
4778 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00004779 return ReplaceInstUsesWith(CI, New);
4780}
4781
4782
Chris Lattnera1be5662002-05-02 17:06:02 +00004783// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00004784//
Chris Lattner7e708292002-06-25 16:13:24 +00004785Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00004786 Value *Src = CI.getOperand(0);
4787
Chris Lattnera1be5662002-05-02 17:06:02 +00004788 // If the user is casting a value to the same type, eliminate this cast
4789 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00004790 if (CI.getType() == Src->getType())
4791 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00004792
Chris Lattnere87597f2004-10-16 18:11:37 +00004793 if (isa<UndefValue>(Src)) // cast undef -> undef
4794 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4795
Chris Lattnera1be5662002-05-02 17:06:02 +00004796 // If casting the result of another cast instruction, try to eliminate this
4797 // one!
4798 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00004799 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4800 Value *A = CSrc->getOperand(0);
4801 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4802 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00004803 // This instruction now refers directly to the cast's src operand. This
4804 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00004805 CI.setOperand(0, CSrc->getOperand(0));
4806 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00004807 }
4808
Chris Lattner8fd217c2002-08-02 20:00:25 +00004809 // If this is an A->B->A cast, and we are dealing with integral types, try
4810 // to convert this into a logical 'and' instruction.
4811 //
Misha Brukmanfd939082005-04-21 23:48:37 +00004812 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00004813 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00004814 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00004815 CSrc->getType()->getPrimitiveSizeInBits() <
4816 CI.getType()->getPrimitiveSizeInBits()&&
4817 A->getType()->getPrimitiveSizeInBits() ==
4818 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00004819 assert(CSrc->getType() != Type::ULongTy &&
4820 "Cannot have type bigger than ulong!");
Chris Lattner1a074fc2006-02-07 07:00:41 +00004821 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Chris Lattner6e7ba452005-01-01 16:22:27 +00004822 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4823 AndValue);
4824 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4825 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4826 if (And->getType() != CI.getType()) {
4827 And->setName(CSrc->getName()+".mask");
4828 InsertNewInstBefore(And, CI);
4829 And = new CastInst(And, CI.getType());
4830 }
4831 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00004832 }
4833 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00004834
Chris Lattnera710ddc2004-05-25 04:29:21 +00004835 // If this is a cast to bool, turn it into the appropriate setne instruction.
4836 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00004837 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00004838 Constant::getNullValue(CI.getOperand(0)->getType()));
4839
Chris Lattner6dce1a72006-02-07 06:56:34 +00004840 // See if we can simplify any instructions used by the LHS whose sole
4841 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00004842 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4843 uint64_t KnownZero, KnownOne;
4844 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4845 KnownZero, KnownOne))
4846 return &CI;
4847 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00004848
Chris Lattner797249b2003-06-21 23:12:02 +00004849 // If casting the result of a getelementptr instruction with no offset, turn
4850 // this into a cast of the original pointer!
4851 //
Chris Lattner79d35b32003-06-23 21:59:52 +00004852 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00004853 bool AllZeroOperands = true;
4854 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4855 if (!isa<Constant>(GEP->getOperand(i)) ||
4856 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4857 AllZeroOperands = false;
4858 break;
4859 }
4860 if (AllZeroOperands) {
4861 CI.setOperand(0, GEP->getOperand(0));
4862 return &CI;
4863 }
4864 }
4865
Chris Lattnerbc61e662003-11-02 05:57:39 +00004866 // If we are casting a malloc or alloca to a pointer to a type of the same
4867 // size, rewrite the allocation instruction to allocate the "right" type.
4868 //
4869 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00004870 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4871 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00004872
Chris Lattner6e7ba452005-01-01 16:22:27 +00004873 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4874 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4875 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00004876 if (isa<PHINode>(Src))
4877 if (Instruction *NV = FoldOpIntoPhi(CI))
4878 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00004879
4880 // If the source and destination are pointers, and this cast is equivalent to
4881 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
4882 // This can enhance SROA and other transforms that want type-safe pointers.
4883 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
4884 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
4885 const Type *DstTy = DstPTy->getElementType();
4886 const Type *SrcTy = SrcPTy->getElementType();
4887
4888 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
4889 unsigned NumZeros = 0;
4890 while (SrcTy != DstTy &&
4891 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy)) {
4892 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
4893 ++NumZeros;
4894 }
Chris Lattner4e998b22004-09-29 05:07:12 +00004895
Chris Lattner9fb92132006-04-12 18:09:35 +00004896 // If we found a path from the src to dest, create the getelementptr now.
4897 if (SrcTy == DstTy) {
4898 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
4899 return new GetElementPtrInst(Src, Idxs);
4900 }
4901 }
4902
Chris Lattner24c8e382003-07-24 17:35:25 +00004903 // If the source value is an instruction with only this use, we can attempt to
4904 // propagate the cast into the instruction. Also, only handle integral types
4905 // for now.
4906 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
Chris Lattnerfd059242003-10-15 16:48:29 +00004907 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00004908 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4909 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004910 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4911 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00004912
4913 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4914 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4915
4916 switch (SrcI->getOpcode()) {
4917 case Instruction::Add:
4918 case Instruction::Mul:
4919 case Instruction::And:
4920 case Instruction::Or:
4921 case Instruction::Xor:
4922 // If we are discarding information, or just changing the sign, rewrite.
4923 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4924 // Don't insert two casts if they cannot be eliminated. We allow two
4925 // casts to be inserted if the sizes are the same. This could only be
4926 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00004927 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4928 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00004929 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4930 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4931 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4932 ->getOpcode(), Op0c, Op1c);
4933 }
4934 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00004935
4936 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4937 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4938 Op1 == ConstantBool::True &&
4939 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4940 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4941 return BinaryOperator::createXor(New,
4942 ConstantInt::get(CI.getType(), 1));
4943 }
Chris Lattner24c8e382003-07-24 17:35:25 +00004944 break;
4945 case Instruction::Shl:
4946 // Allow changing the sign of the source operand. Do not allow changing
4947 // the size of the shift, UNLESS the shift amount is a constant. We
4948 // mush not change variable sized shifts to a smaller size, because it
4949 // is undefined to shift more bits out than exist in the value.
4950 if (DestBitSize == SrcBitSize ||
4951 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4952 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4953 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4954 }
4955 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00004956 case Instruction::Shr:
4957 // If this is a signed shr, and if all bits shifted in are about to be
4958 // truncated off, turn it into an unsigned shr to allow greater
4959 // simplifications.
4960 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4961 isa<ConstantInt>(Op1)) {
4962 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4963 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4964 // Convert to unsigned.
4965 Value *N1 = InsertOperandCastBefore(Op0,
4966 Op0->getType()->getUnsignedVersion(), &CI);
4967 // Insert the new shift, which is now unsigned.
4968 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4969 Op1, Src->getName()), CI);
4970 return new CastInst(N1, CI.getType());
4971 }
4972 }
4973 break;
4974
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004975 case Instruction::SetEQ:
Chris Lattner693787a2005-05-04 19:10:26 +00004976 case Instruction::SetNE:
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004977 // We if we are just checking for a seteq of a single bit and casting it
4978 // to an integer. If so, shift the bit to the appropriate place then
4979 // cast to integer to avoid the comparison.
Chris Lattner693787a2005-05-04 19:10:26 +00004980 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3e88a4d2006-02-27 02:38:23 +00004981 uint64_t Op1CV = Op1C->getZExtValue();
4982 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
4983 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4984 // cast (X == 1) to int --> X iff X has only the low bit set.
4985 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
4986 // cast (X != 0) to int --> X iff X has only the low bit set.
4987 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
4988 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
4989 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4990 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4991 // If Op1C some other power of two, convert:
4992 uint64_t KnownZero, KnownOne;
4993 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4994 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4995
4996 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4997 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4998 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4999 // (X&4) == 2 --> false
5000 // (X&4) != 2 --> true
Chris Lattner06e1e252006-02-28 19:47:20 +00005001 Constant *Res = ConstantBool::get(isSetNE);
5002 Res = ConstantExpr::getCast(Res, CI.getType());
5003 return ReplaceInstUsesWith(CI, Res);
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005004 }
5005
5006 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5007 Value *In = Op0;
5008 if (ShiftAmt) {
Chris Lattnerd1523802005-05-06 01:53:19 +00005009 // Perform an unsigned shr by shiftamt. Convert input to
5010 // unsigned if it is signed.
Chris Lattnerd1523802005-05-06 01:53:19 +00005011 if (In->getType()->isSigned())
5012 In = InsertNewInstBefore(new CastInst(In,
5013 In->getType()->getUnsignedVersion(), In->getName()),CI);
5014 // Insert the shift to put the result in the low bit.
5015 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005016 ConstantInt::get(Type::UByteTy, ShiftAmt),
5017 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005018 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005019
5020 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5021 Constant *One = ConstantInt::get(In->getType(), 1);
5022 In = BinaryOperator::createXor(In, One, "tmp");
5023 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005024 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005025
5026 if (CI.getType() == In->getType())
5027 return ReplaceInstUsesWith(CI, In);
5028 else
5029 return new CastInst(In, CI.getType());
Chris Lattnerd1523802005-05-06 01:53:19 +00005030 }
Chris Lattner693787a2005-05-04 19:10:26 +00005031 }
5032 }
5033 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00005034 }
5035 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005036
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005037 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005038}
5039
Chris Lattnere576b912004-04-09 23:46:01 +00005040/// GetSelectFoldableOperands - We want to turn code that looks like this:
5041/// %C = or %A, %B
5042/// %D = select %cond, %C, %A
5043/// into:
5044/// %C = select %cond, %B, 0
5045/// %D = or %A, %C
5046///
5047/// Assuming that the specified instruction is an operand to the select, return
5048/// a bitmask indicating which operands of this instruction are foldable if they
5049/// equal the other incoming value of the select.
5050///
5051static unsigned GetSelectFoldableOperands(Instruction *I) {
5052 switch (I->getOpcode()) {
5053 case Instruction::Add:
5054 case Instruction::Mul:
5055 case Instruction::And:
5056 case Instruction::Or:
5057 case Instruction::Xor:
5058 return 3; // Can fold through either operand.
5059 case Instruction::Sub: // Can only fold on the amount subtracted.
5060 case Instruction::Shl: // Can only fold on the shift amount.
5061 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00005062 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00005063 default:
5064 return 0; // Cannot fold
5065 }
5066}
5067
5068/// GetSelectFoldableConstant - For the same transformation as the previous
5069/// function, return the identity constant that goes into the select.
5070static Constant *GetSelectFoldableConstant(Instruction *I) {
5071 switch (I->getOpcode()) {
5072 default: assert(0 && "This cannot happen!"); abort();
5073 case Instruction::Add:
5074 case Instruction::Sub:
5075 case Instruction::Or:
5076 case Instruction::Xor:
5077 return Constant::getNullValue(I->getType());
5078 case Instruction::Shl:
5079 case Instruction::Shr:
5080 return Constant::getNullValue(Type::UByteTy);
5081 case Instruction::And:
5082 return ConstantInt::getAllOnesValue(I->getType());
5083 case Instruction::Mul:
5084 return ConstantInt::get(I->getType(), 1);
5085 }
5086}
5087
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005088/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5089/// have the same opcode and only one use each. Try to simplify this.
5090Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5091 Instruction *FI) {
5092 if (TI->getNumOperands() == 1) {
5093 // If this is a non-volatile load or a cast from the same type,
5094 // merge.
5095 if (TI->getOpcode() == Instruction::Cast) {
5096 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5097 return 0;
5098 } else {
5099 return 0; // unknown unary op.
5100 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005101
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005102 // Fold this by inserting a select from the input values.
5103 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5104 FI->getOperand(0), SI.getName()+".v");
5105 InsertNewInstBefore(NewSI, SI);
5106 return new CastInst(NewSI, TI->getType());
5107 }
5108
5109 // Only handle binary operators here.
5110 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5111 return 0;
5112
5113 // Figure out if the operations have any operands in common.
5114 Value *MatchOp, *OtherOpT, *OtherOpF;
5115 bool MatchIsOpZero;
5116 if (TI->getOperand(0) == FI->getOperand(0)) {
5117 MatchOp = TI->getOperand(0);
5118 OtherOpT = TI->getOperand(1);
5119 OtherOpF = FI->getOperand(1);
5120 MatchIsOpZero = true;
5121 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5122 MatchOp = TI->getOperand(1);
5123 OtherOpT = TI->getOperand(0);
5124 OtherOpF = FI->getOperand(0);
5125 MatchIsOpZero = false;
5126 } else if (!TI->isCommutative()) {
5127 return 0;
5128 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5129 MatchOp = TI->getOperand(0);
5130 OtherOpT = TI->getOperand(1);
5131 OtherOpF = FI->getOperand(0);
5132 MatchIsOpZero = true;
5133 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5134 MatchOp = TI->getOperand(1);
5135 OtherOpT = TI->getOperand(0);
5136 OtherOpF = FI->getOperand(1);
5137 MatchIsOpZero = true;
5138 } else {
5139 return 0;
5140 }
5141
5142 // If we reach here, they do have operations in common.
5143 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5144 OtherOpF, SI.getName()+".v");
5145 InsertNewInstBefore(NewSI, SI);
5146
5147 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5148 if (MatchIsOpZero)
5149 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5150 else
5151 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5152 } else {
5153 if (MatchIsOpZero)
5154 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5155 else
5156 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5157 }
5158}
5159
Chris Lattner3d69f462004-03-12 05:52:32 +00005160Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005161 Value *CondVal = SI.getCondition();
5162 Value *TrueVal = SI.getTrueValue();
5163 Value *FalseVal = SI.getFalseValue();
5164
5165 // select true, X, Y -> X
5166 // select false, X, Y -> Y
5167 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner3d69f462004-03-12 05:52:32 +00005168 if (C == ConstantBool::True)
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005169 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00005170 else {
5171 assert(C == ConstantBool::False);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005172 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattner3d69f462004-03-12 05:52:32 +00005173 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005174
5175 // select C, X, X -> X
5176 if (TrueVal == FalseVal)
5177 return ReplaceInstUsesWith(SI, TrueVal);
5178
Chris Lattnere87597f2004-10-16 18:11:37 +00005179 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5180 return ReplaceInstUsesWith(SI, FalseVal);
5181 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5182 return ReplaceInstUsesWith(SI, TrueVal);
5183 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5184 if (isa<Constant>(TrueVal))
5185 return ReplaceInstUsesWith(SI, TrueVal);
5186 else
5187 return ReplaceInstUsesWith(SI, FalseVal);
5188 }
5189
Chris Lattner0c199a72004-04-08 04:43:23 +00005190 if (SI.getType() == Type::BoolTy)
5191 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5192 if (C == ConstantBool::True) {
5193 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005194 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005195 } else {
5196 // Change: A = select B, false, C --> A = and !B, C
5197 Value *NotCond =
5198 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5199 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005200 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005201 }
5202 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5203 if (C == ConstantBool::False) {
5204 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005205 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005206 } else {
5207 // Change: A = select B, C, true --> A = or !B, C
5208 Value *NotCond =
5209 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5210 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005211 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005212 }
5213 }
5214
Chris Lattner2eefe512004-04-09 19:05:30 +00005215 // Selecting between two integer constants?
5216 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5217 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5218 // select C, 1, 0 -> cast C to int
5219 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5220 return new CastInst(CondVal, SI.getType());
5221 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5222 // select C, 0, 1 -> cast !C to int
5223 Value *NotCond =
5224 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00005225 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00005226 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00005227 }
Chris Lattner457dd822004-06-09 07:59:58 +00005228
5229 // If one of the constants is zero (we know they can't both be) and we
5230 // have a setcc instruction with zero, and we have an 'and' with the
5231 // non-constant value, eliminate this whole mess. This corresponds to
5232 // cases like this: ((X & 27) ? 27 : 0)
5233 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5234 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5235 if ((IC->getOpcode() == Instruction::SetEQ ||
5236 IC->getOpcode() == Instruction::SetNE) &&
5237 isa<ConstantInt>(IC->getOperand(1)) &&
5238 cast<Constant>(IC->getOperand(1))->isNullValue())
5239 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5240 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00005241 isa<ConstantInt>(ICA->getOperand(1)) &&
5242 (ICA->getOperand(1) == TrueValC ||
5243 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00005244 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5245 // Okay, now we know that everything is set up, we just don't
5246 // know whether we have a setne or seteq and whether the true or
5247 // false val is the zero.
5248 bool ShouldNotVal = !TrueValC->isNullValue();
5249 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5250 Value *V = ICA;
5251 if (ShouldNotVal)
5252 V = InsertNewInstBefore(BinaryOperator::create(
5253 Instruction::Xor, V, ICA->getOperand(1)), SI);
5254 return ReplaceInstUsesWith(SI, V);
5255 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005256 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00005257
5258 // See if we are selecting two values based on a comparison of the two values.
5259 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5260 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5261 // Transform (X == Y) ? X : Y -> Y
5262 if (SCI->getOpcode() == Instruction::SetEQ)
5263 return ReplaceInstUsesWith(SI, FalseVal);
5264 // Transform (X != Y) ? X : Y -> X
5265 if (SCI->getOpcode() == Instruction::SetNE)
5266 return ReplaceInstUsesWith(SI, TrueVal);
5267 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5268
5269 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5270 // Transform (X == Y) ? Y : X -> X
5271 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00005272 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00005273 // Transform (X != Y) ? Y : X -> Y
5274 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00005275 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00005276 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5277 }
5278 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005279
Chris Lattner87875da2005-01-13 22:52:24 +00005280 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5281 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5282 if (TI->hasOneUse() && FI->hasOneUse()) {
5283 bool isInverse = false;
5284 Instruction *AddOp = 0, *SubOp = 0;
5285
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005286 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5287 if (TI->getOpcode() == FI->getOpcode())
5288 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5289 return IV;
5290
5291 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5292 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00005293 if (TI->getOpcode() == Instruction::Sub &&
5294 FI->getOpcode() == Instruction::Add) {
5295 AddOp = FI; SubOp = TI;
5296 } else if (FI->getOpcode() == Instruction::Sub &&
5297 TI->getOpcode() == Instruction::Add) {
5298 AddOp = TI; SubOp = FI;
5299 }
5300
5301 if (AddOp) {
5302 Value *OtherAddOp = 0;
5303 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5304 OtherAddOp = AddOp->getOperand(1);
5305 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5306 OtherAddOp = AddOp->getOperand(0);
5307 }
5308
5309 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00005310 // So at this point we know we have (Y -> OtherAddOp):
5311 // select C, (add X, Y), (sub X, Z)
5312 Value *NegVal; // Compute -Z
5313 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5314 NegVal = ConstantExpr::getNeg(C);
5315 } else {
5316 NegVal = InsertNewInstBefore(
5317 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00005318 }
Chris Lattner97f37a42006-02-24 18:05:58 +00005319
5320 Value *NewTrueOp = OtherAddOp;
5321 Value *NewFalseOp = NegVal;
5322 if (AddOp != TI)
5323 std::swap(NewTrueOp, NewFalseOp);
5324 Instruction *NewSel =
5325 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5326
5327 NewSel = InsertNewInstBefore(NewSel, SI);
5328 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00005329 }
5330 }
5331 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005332
Chris Lattnere576b912004-04-09 23:46:01 +00005333 // See if we can fold the select into one of our operands.
5334 if (SI.getType()->isInteger()) {
5335 // See the comment above GetSelectFoldableOperands for a description of the
5336 // transformation we are doing here.
5337 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5338 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5339 !isa<Constant>(FalseVal))
5340 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5341 unsigned OpToFold = 0;
5342 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5343 OpToFold = 1;
5344 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5345 OpToFold = 2;
5346 }
5347
5348 if (OpToFold) {
5349 Constant *C = GetSelectFoldableConstant(TVI);
5350 std::string Name = TVI->getName(); TVI->setName("");
5351 Instruction *NewSel =
5352 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5353 Name);
5354 InsertNewInstBefore(NewSel, SI);
5355 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5356 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5357 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5358 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5359 else {
5360 assert(0 && "Unknown instruction!!");
5361 }
5362 }
5363 }
Chris Lattnera96879a2004-09-29 17:40:11 +00005364
Chris Lattnere576b912004-04-09 23:46:01 +00005365 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5366 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5367 !isa<Constant>(TrueVal))
5368 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5369 unsigned OpToFold = 0;
5370 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5371 OpToFold = 1;
5372 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5373 OpToFold = 2;
5374 }
5375
5376 if (OpToFold) {
5377 Constant *C = GetSelectFoldableConstant(FVI);
5378 std::string Name = FVI->getName(); FVI->setName("");
5379 Instruction *NewSel =
5380 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5381 Name);
5382 InsertNewInstBefore(NewSel, SI);
5383 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5384 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5385 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5386 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5387 else {
5388 assert(0 && "Unknown instruction!!");
5389 }
5390 }
5391 }
5392 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00005393
5394 if (BinaryOperator::isNot(CondVal)) {
5395 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5396 SI.setOperand(1, FalseVal);
5397 SI.setOperand(2, TrueVal);
5398 return &SI;
5399 }
5400
Chris Lattner3d69f462004-03-12 05:52:32 +00005401 return 0;
5402}
5403
Chris Lattner95a959d2006-03-06 20:18:44 +00005404/// GetKnownAlignment - If the specified pointer has an alignment that we can
5405/// determine, return it, otherwise return 0.
5406static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5407 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5408 unsigned Align = GV->getAlignment();
5409 if (Align == 0 && TD)
5410 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5411 return Align;
5412 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5413 unsigned Align = AI->getAlignment();
5414 if (Align == 0 && TD) {
5415 if (isa<AllocaInst>(AI))
5416 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5417 else if (isa<MallocInst>(AI)) {
5418 // Malloc returns maximally aligned memory.
5419 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5420 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5421 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5422 }
5423 }
5424 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00005425 } else if (isa<CastInst>(V) ||
5426 (isa<ConstantExpr>(V) &&
5427 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5428 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00005429 if (isa<PointerType>(CI->getOperand(0)->getType()))
5430 return GetKnownAlignment(CI->getOperand(0), TD);
5431 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00005432 } else if (isa<GetElementPtrInst>(V) ||
5433 (isa<ConstantExpr>(V) &&
5434 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5435 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00005436 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5437 if (BaseAlignment == 0) return 0;
5438
5439 // If all indexes are zero, it is just the alignment of the base pointer.
5440 bool AllZeroOperands = true;
5441 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5442 if (!isa<Constant>(GEPI->getOperand(i)) ||
5443 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5444 AllZeroOperands = false;
5445 break;
5446 }
5447 if (AllZeroOperands)
5448 return BaseAlignment;
5449
5450 // Otherwise, if the base alignment is >= the alignment we expect for the
5451 // base pointer type, then we know that the resultant pointer is aligned at
5452 // least as much as its type requires.
5453 if (!TD) return 0;
5454
5455 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5456 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00005457 <= BaseAlignment) {
5458 const Type *GEPTy = GEPI->getType();
5459 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5460 }
Chris Lattner95a959d2006-03-06 20:18:44 +00005461 return 0;
5462 }
5463 return 0;
5464}
5465
Chris Lattner3d69f462004-03-12 05:52:32 +00005466
Chris Lattner8b0ea312006-01-13 20:11:04 +00005467/// visitCallInst - CallInst simplification. This mostly only handles folding
5468/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5469/// the heavy lifting.
5470///
Chris Lattner9fe38862003-06-19 17:00:31 +00005471Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00005472 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5473 if (!II) return visitCallSite(&CI);
5474
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005475 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5476 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00005477 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005478 bool Changed = false;
5479
5480 // memmove/cpy/set of zero bytes is a noop.
5481 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5482 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5483
Chris Lattner35b9e482004-10-12 04:52:52 +00005484 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5485 if (CI->getRawValue() == 1) {
5486 // Replace the instruction with just byte operations. We would
5487 // transform other cases to loads/stores, but we don't know if
5488 // alignment is sufficient.
5489 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005490 }
5491
Chris Lattner35b9e482004-10-12 04:52:52 +00005492 // If we have a memmove and the source operation is a constant global,
5493 // then the source and dest pointers can't alias, so we can change this
5494 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00005495 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00005496 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5497 if (GVSrc->isConstant()) {
5498 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00005499 const char *Name;
5500 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5501 Type::UIntTy)
5502 Name = "llvm.memcpy.i32";
5503 else
5504 Name = "llvm.memcpy.i64";
5505 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00005506 CI.getCalledFunction()->getFunctionType());
5507 CI.setOperand(0, MemCpy);
5508 Changed = true;
5509 }
Chris Lattner95a959d2006-03-06 20:18:44 +00005510 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005511
Chris Lattner95a959d2006-03-06 20:18:44 +00005512 // If we can determine a pointer alignment that is bigger than currently
5513 // set, update the alignment.
5514 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5515 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5516 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5517 unsigned Align = std::min(Alignment1, Alignment2);
5518 if (MI->getAlignment()->getRawValue() < Align) {
5519 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5520 Changed = true;
5521 }
5522 } else if (isa<MemSetInst>(MI)) {
5523 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5524 if (MI->getAlignment()->getRawValue() < Alignment) {
5525 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5526 Changed = true;
5527 }
5528 }
5529
Chris Lattner8b0ea312006-01-13 20:11:04 +00005530 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00005531 } else {
5532 switch (II->getIntrinsicID()) {
5533 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00005534 case Intrinsic::ppc_altivec_lvx:
5535 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00005536 case Intrinsic::x86_sse_loadu_ps:
5537 case Intrinsic::x86_sse2_loadu_pd:
5538 case Intrinsic::x86_sse2_loadu_dq:
5539 // Turn PPC lvx -> load if the pointer is known aligned.
5540 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00005541 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00005542 Value *Ptr = InsertCastBefore(II->getOperand(1),
5543 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00005544 return new LoadInst(Ptr);
5545 }
5546 break;
5547 case Intrinsic::ppc_altivec_stvx:
5548 case Intrinsic::ppc_altivec_stvxl:
5549 // Turn stvx -> store if the pointer is known aligned.
5550 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00005551 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5552 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00005553 return new StoreInst(II->getOperand(1), Ptr);
5554 }
5555 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00005556 case Intrinsic::x86_sse_storeu_ps:
5557 case Intrinsic::x86_sse2_storeu_pd:
5558 case Intrinsic::x86_sse2_storeu_dq:
5559 case Intrinsic::x86_sse2_storel_dq:
5560 // Turn X86 storeu -> store if the pointer is known aligned.
5561 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5562 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5563 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5564 return new StoreInst(II->getOperand(2), Ptr);
5565 }
5566 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00005567 case Intrinsic::ppc_altivec_vperm:
5568 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5569 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5570 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5571
5572 // Check that all of the elements are integer constants or undefs.
5573 bool AllEltsOk = true;
5574 for (unsigned i = 0; i != 16; ++i) {
5575 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5576 !isa<UndefValue>(Mask->getOperand(i))) {
5577 AllEltsOk = false;
5578 break;
5579 }
5580 }
5581
5582 if (AllEltsOk) {
5583 // Cast the input vectors to byte vectors.
5584 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5585 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5586 Value *Result = UndefValue::get(Op0->getType());
5587
5588 // Only extract each element once.
5589 Value *ExtractedElts[32];
5590 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5591
5592 for (unsigned i = 0; i != 16; ++i) {
5593 if (isa<UndefValue>(Mask->getOperand(i)))
5594 continue;
5595 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5596 Idx &= 31; // Match the hardware behavior.
5597
5598 if (ExtractedElts[Idx] == 0) {
5599 Instruction *Elt =
5600 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5601 ConstantUInt::get(Type::UIntTy, Idx&15),
5602 "tmp");
5603 InsertNewInstBefore(Elt, CI);
5604 ExtractedElts[Idx] = Elt;
5605 }
5606
5607 // Insert this value into the result vector.
5608 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5609 ConstantUInt::get(Type::UIntTy, i),
5610 "tmp");
5611 InsertNewInstBefore(cast<Instruction>(Result), CI);
5612 }
5613 return new CastInst(Result, CI.getType());
5614 }
5615 }
5616 break;
5617
Chris Lattnera728ddc2006-01-13 21:28:09 +00005618 case Intrinsic::stackrestore: {
5619 // If the save is right next to the restore, remove the restore. This can
5620 // happen when variable allocas are DCE'd.
5621 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5622 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5623 BasicBlock::iterator BI = SS;
5624 if (&*++BI == II)
5625 return EraseInstFromFunction(CI);
5626 }
5627 }
5628
5629 // If the stack restore is in a return/unwind block and if there are no
5630 // allocas or calls between the restore and the return, nuke the restore.
5631 TerminatorInst *TI = II->getParent()->getTerminator();
5632 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5633 BasicBlock::iterator BI = II;
5634 bool CannotRemove = false;
5635 for (++BI; &*BI != TI; ++BI) {
5636 if (isa<AllocaInst>(BI) ||
5637 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5638 CannotRemove = true;
5639 break;
5640 }
5641 }
5642 if (!CannotRemove)
5643 return EraseInstFromFunction(CI);
5644 }
5645 break;
5646 }
5647 }
Chris Lattner35b9e482004-10-12 04:52:52 +00005648 }
5649
Chris Lattner8b0ea312006-01-13 20:11:04 +00005650 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005651}
5652
5653// InvokeInst simplification
5654//
5655Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00005656 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00005657}
5658
Chris Lattnera44d8a22003-10-07 22:32:43 +00005659// visitCallSite - Improvements for call and invoke instructions.
5660//
5661Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00005662 bool Changed = false;
5663
5664 // If the callee is a constexpr cast of a function, attempt to move the cast
5665 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00005666 if (transformConstExprCastCall(CS)) return 0;
5667
Chris Lattner6c266db2003-10-07 22:54:13 +00005668 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00005669
Chris Lattner08b22ec2005-05-13 07:09:09 +00005670 if (Function *CalleeF = dyn_cast<Function>(Callee))
5671 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5672 Instruction *OldCall = CS.getInstruction();
5673 // If the call and callee calling conventions don't match, this call must
5674 // be unreachable, as the call is undefined.
5675 new StoreInst(ConstantBool::True,
5676 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5677 if (!OldCall->use_empty())
5678 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5679 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5680 return EraseInstFromFunction(*OldCall);
5681 return 0;
5682 }
5683
Chris Lattner17be6352004-10-18 02:59:09 +00005684 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5685 // This instruction is not reachable, just remove it. We insert a store to
5686 // undef so that we know that this code is not reachable, despite the fact
5687 // that we can't modify the CFG here.
5688 new StoreInst(ConstantBool::True,
5689 UndefValue::get(PointerType::get(Type::BoolTy)),
5690 CS.getInstruction());
5691
5692 if (!CS.getInstruction()->use_empty())
5693 CS.getInstruction()->
5694 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5695
5696 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5697 // Don't break the CFG, insert a dummy cond branch.
5698 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5699 ConstantBool::True, II);
Chris Lattnere87597f2004-10-16 18:11:37 +00005700 }
Chris Lattner17be6352004-10-18 02:59:09 +00005701 return EraseInstFromFunction(*CS.getInstruction());
5702 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005703
Chris Lattner6c266db2003-10-07 22:54:13 +00005704 const PointerType *PTy = cast<PointerType>(Callee->getType());
5705 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5706 if (FTy->isVarArg()) {
5707 // See if we can optimize any arguments passed through the varargs area of
5708 // the call.
5709 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5710 E = CS.arg_end(); I != E; ++I)
5711 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5712 // If this cast does not effect the value passed through the varargs
5713 // area, we can eliminate the use of the cast.
5714 Value *Op = CI->getOperand(0);
5715 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5716 *I = Op;
5717 Changed = true;
5718 }
5719 }
5720 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005721
Chris Lattner6c266db2003-10-07 22:54:13 +00005722 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00005723}
5724
Chris Lattner9fe38862003-06-19 17:00:31 +00005725// transformConstExprCastCall - If the callee is a constexpr cast of a function,
5726// attempt to move the cast to the arguments of the call/invoke.
5727//
5728bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5729 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5730 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00005731 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00005732 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00005733 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00005734 Instruction *Caller = CS.getInstruction();
5735
5736 // Okay, this is a cast from a function to a different type. Unless doing so
5737 // would cause a type conversion of one of our arguments, change this call to
5738 // be a direct call with arguments casted to the appropriate types.
5739 //
5740 const FunctionType *FT = Callee->getFunctionType();
5741 const Type *OldRetTy = Caller->getType();
5742
Chris Lattnerf78616b2004-01-14 06:06:08 +00005743 // Check to see if we are changing the return type...
5744 if (OldRetTy != FT->getReturnType()) {
5745 if (Callee->isExternal() &&
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00005746 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
5747 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharth7a31b972006-04-20 15:41:37 +00005748 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00005749 && !Caller->use_empty())
Chris Lattnerf78616b2004-01-14 06:06:08 +00005750 return false; // Cannot transform this return value...
5751
5752 // If the callsite is an invoke instruction, and the return value is used by
5753 // a PHI node in a successor, we cannot change the return type of the call
5754 // because there is no place to put the cast instruction (without breaking
5755 // the critical edge). Bail out in this case.
5756 if (!Caller->use_empty())
5757 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5758 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5759 UI != E; ++UI)
5760 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5761 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005762 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00005763 return false;
5764 }
Chris Lattner9fe38862003-06-19 17:00:31 +00005765
5766 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5767 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005768
Chris Lattner9fe38862003-06-19 17:00:31 +00005769 CallSite::arg_iterator AI = CS.arg_begin();
5770 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5771 const Type *ParamTy = FT->getParamType(i);
5772 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
Misha Brukmanfd939082005-04-21 23:48:37 +00005773 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00005774 }
5775
5776 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5777 Callee->isExternal())
5778 return false; // Do not delete arguments unless we have a function body...
5779
5780 // Okay, we decided that this is a safe thing to do: go ahead and start
5781 // inserting cast instructions as necessary...
5782 std::vector<Value*> Args;
5783 Args.reserve(NumActualArgs);
5784
5785 AI = CS.arg_begin();
5786 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5787 const Type *ParamTy = FT->getParamType(i);
5788 if ((*AI)->getType() == ParamTy) {
5789 Args.push_back(*AI);
5790 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00005791 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5792 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00005793 }
5794 }
5795
5796 // If the function takes more arguments than the call was taking, add them
5797 // now...
5798 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5799 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5800
5801 // If we are removing arguments to the function, emit an obnoxious warning...
5802 if (FT->getNumParams() < NumActualArgs)
5803 if (!FT->isVarArg()) {
5804 std::cerr << "WARNING: While resolving call to function '"
5805 << Callee->getName() << "' arguments were dropped!\n";
5806 } else {
5807 // Add all of the arguments in their promoted form to the arg list...
5808 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5809 const Type *PTy = getPromotedType((*AI)->getType());
5810 if (PTy != (*AI)->getType()) {
5811 // Must promote to pass through va_arg area!
5812 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5813 InsertNewInstBefore(Cast, *Caller);
5814 Args.push_back(Cast);
5815 } else {
5816 Args.push_back(*AI);
5817 }
5818 }
5819 }
5820
5821 if (FT->getReturnType() == Type::VoidTy)
5822 Caller->setName(""); // Void type should not have a name...
5823
5824 Instruction *NC;
5825 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00005826 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00005827 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00005828 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005829 } else {
5830 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00005831 if (cast<CallInst>(Caller)->isTailCall())
5832 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00005833 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00005834 }
5835
5836 // Insert a cast of the return type as necessary...
5837 Value *NV = NC;
5838 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5839 if (NV->getType() != Type::VoidTy) {
5840 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00005841
5842 // If this is an invoke instruction, we should insert it after the first
5843 // non-phi, instruction in the normal successor block.
5844 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5845 BasicBlock::iterator I = II->getNormalDest()->begin();
5846 while (isa<PHINode>(I)) ++I;
5847 InsertNewInstBefore(NC, *I);
5848 } else {
5849 // Otherwise, it's a call, just insert cast right after the call instr
5850 InsertNewInstBefore(NC, *Caller);
5851 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00005852 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00005853 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00005854 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00005855 }
5856 }
5857
5858 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5859 Caller->replaceAllUsesWith(NV);
5860 Caller->getParent()->getInstList().erase(Caller);
5861 removeFromWorkList(Caller);
5862 return true;
5863}
5864
5865
Chris Lattnerbac32862004-11-14 19:13:23 +00005866// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5867// operator and they all are only used by the PHI, PHI together their
5868// inputs, and do the operation once, to the result of the PHI.
5869Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5870 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5871
5872 // Scan the instruction, looking for input operations that can be folded away.
5873 // If all input operands to the phi are the same instruction (e.g. a cast from
5874 // the same type or "+42") we can pull the operation through the PHI, reducing
5875 // code size and simplifying code.
5876 Constant *ConstantOp = 0;
5877 const Type *CastSrcTy = 0;
5878 if (isa<CastInst>(FirstInst)) {
5879 CastSrcTy = FirstInst->getOperand(0)->getType();
5880 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5881 // Can fold binop or shift if the RHS is a constant.
5882 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5883 if (ConstantOp == 0) return 0;
5884 } else {
5885 return 0; // Cannot fold this operation.
5886 }
5887
5888 // Check to see if all arguments are the same operation.
5889 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5890 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5891 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5892 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5893 return 0;
5894 if (CastSrcTy) {
5895 if (I->getOperand(0)->getType() != CastSrcTy)
5896 return 0; // Cast operation must match.
5897 } else if (I->getOperand(1) != ConstantOp) {
5898 return 0;
5899 }
5900 }
5901
5902 // Okay, they are all the same operation. Create a new PHI node of the
5903 // correct type, and PHI together all of the LHS's of the instructions.
5904 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5905 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00005906 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00005907
5908 Value *InVal = FirstInst->getOperand(0);
5909 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00005910
5911 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00005912 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5913 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5914 if (NewInVal != InVal)
5915 InVal = 0;
5916 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5917 }
5918
5919 Value *PhiVal;
5920 if (InVal) {
5921 // The new PHI unions all of the same values together. This is really
5922 // common, so we handle it intelligently here for compile-time speed.
5923 PhiVal = InVal;
5924 delete NewPN;
5925 } else {
5926 InsertNewInstBefore(NewPN, PN);
5927 PhiVal = NewPN;
5928 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005929
Chris Lattnerbac32862004-11-14 19:13:23 +00005930 // Insert and return the new operation.
5931 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005932 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00005933 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00005934 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005935 else
5936 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00005937 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00005938}
Chris Lattnera1be5662002-05-02 17:06:02 +00005939
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005940/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5941/// that is dead.
5942static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5943 if (PN->use_empty()) return true;
5944 if (!PN->hasOneUse()) return false;
5945
5946 // Remember this node, and if we find the cycle, return.
5947 if (!PotentiallyDeadPHIs.insert(PN).second)
5948 return true;
5949
5950 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5951 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00005952
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005953 return false;
5954}
5955
Chris Lattner473945d2002-05-06 18:06:38 +00005956// PHINode simplification
5957//
Chris Lattner7e708292002-06-25 16:13:24 +00005958Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Chris Lattner68ee7362005-08-05 01:04:30 +00005959 if (Value *V = PN.hasConstantValue())
5960 return ReplaceInstUsesWith(PN, V);
Chris Lattner7059f2e2004-02-16 05:07:08 +00005961
5962 // If the only user of this instruction is a cast instruction, and all of the
5963 // incoming values are constants, change this PHI to merge together the casted
5964 // constants.
5965 if (PN.hasOneUse())
5966 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5967 if (CI->getType() != PN.getType()) { // noop casts will be folded
5968 bool AllConstant = true;
5969 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5970 if (!isa<Constant>(PN.getIncomingValue(i))) {
5971 AllConstant = false;
5972 break;
5973 }
5974 if (AllConstant) {
5975 // Make a new PHI with all casted values.
5976 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5977 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5978 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5979 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5980 PN.getIncomingBlock(i));
5981 }
5982
5983 // Update the cast instruction.
5984 CI->setOperand(0, New);
5985 WorkList.push_back(CI); // revisit the cast instruction to fold.
5986 WorkList.push_back(New); // Make sure to revisit the new Phi
5987 return &PN; // PN is now dead!
5988 }
5989 }
Chris Lattnerbac32862004-11-14 19:13:23 +00005990
5991 // If all PHI operands are the same operation, pull them through the PHI,
5992 // reducing code size.
5993 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5994 PN.getIncomingValue(0)->hasOneUse())
5995 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5996 return Result;
5997
Chris Lattnera3fd1c52005-01-17 05:10:15 +00005998 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5999 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6000 // PHI)... break the cycle.
6001 if (PN.hasOneUse())
6002 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6003 std::set<PHINode*> PotentiallyDeadPHIs;
6004 PotentiallyDeadPHIs.insert(&PN);
6005 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6006 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6007 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006008
Chris Lattner60921c92003-12-19 05:58:40 +00006009 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00006010}
6011
Chris Lattner28977af2004-04-05 01:30:19 +00006012static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6013 Instruction *InsertPoint,
6014 InstCombiner *IC) {
6015 unsigned PS = IC->getTargetData().getPointerSize();
6016 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00006017 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6018 // We must insert a cast to ensure we sign-extend.
6019 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6020 V->getName()), *InsertPoint);
6021 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6022 *InsertPoint);
6023}
6024
Chris Lattnera1be5662002-05-02 17:06:02 +00006025
Chris Lattner7e708292002-06-25 16:13:24 +00006026Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00006027 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00006028 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00006029 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006030 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00006031 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006032
Chris Lattnere87597f2004-10-16 18:11:37 +00006033 if (isa<UndefValue>(GEP.getOperand(0)))
6034 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6035
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006036 bool HasZeroPointerIndex = false;
6037 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6038 HasZeroPointerIndex = C->isNullValue();
6039
6040 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00006041 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00006042
Chris Lattner28977af2004-04-05 01:30:19 +00006043 // Eliminate unneeded casts for indices.
6044 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006045 gep_type_iterator GTI = gep_type_begin(GEP);
6046 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6047 if (isa<SequentialType>(*GTI)) {
6048 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6049 Value *Src = CI->getOperand(0);
6050 const Type *SrcTy = Src->getType();
6051 const Type *DestTy = CI->getType();
6052 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006053 if (SrcTy->getPrimitiveSizeInBits() ==
6054 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006055 // We can always eliminate a cast from ulong or long to the other.
6056 // We can always eliminate a cast from uint to int or the other on
6057 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00006058 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006059 MadeChange = true;
6060 GEP.setOperand(i, Src);
6061 }
6062 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6063 SrcTy->getPrimitiveSize() == 4) {
6064 // We can always eliminate a cast from int to [u]long. We can
6065 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6066 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00006067 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00006068 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006069 MadeChange = true;
6070 GEP.setOperand(i, Src);
6071 }
Chris Lattner28977af2004-04-05 01:30:19 +00006072 }
6073 }
6074 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006075 // If we are using a wider index than needed for this platform, shrink it
6076 // to what we need. If the incoming value needs a cast instruction,
6077 // insert it. This explicit cast can make subsequent optimizations more
6078 // obvious.
6079 Value *Op = GEP.getOperand(i);
6080 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00006081 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00006082 GEP.setOperand(i, ConstantExpr::getCast(C,
6083 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00006084 MadeChange = true;
6085 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006086 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6087 Op->getName()), GEP);
6088 GEP.setOperand(i, Op);
6089 MadeChange = true;
6090 }
Chris Lattner67769e52004-07-20 01:48:15 +00006091
6092 // If this is a constant idx, make sure to canonicalize it to be a signed
6093 // operand, otherwise CSE and other optimizations are pessimized.
6094 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6095 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6096 CUI->getType()->getSignedVersion()));
6097 MadeChange = true;
6098 }
Chris Lattner28977af2004-04-05 01:30:19 +00006099 }
6100 if (MadeChange) return &GEP;
6101
Chris Lattner90ac28c2002-08-02 19:29:35 +00006102 // Combine Indices - If the source pointer to this getelementptr instruction
6103 // is a getelementptr instruction, combine the indices of the two
6104 // getelementptr instructions into a single instruction.
6105 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00006106 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00006107 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00006108 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00006109
6110 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00006111 // Note that if our source is a gep chain itself that we wait for that
6112 // chain to be resolved before we perform this transformation. This
6113 // avoids us creating a TON of code in some cases.
6114 //
6115 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6116 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6117 return 0; // Wait until our source is folded to completion.
6118
Chris Lattner90ac28c2002-08-02 19:29:35 +00006119 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00006120
6121 // Find out whether the last index in the source GEP is a sequential idx.
6122 bool EndsWithSequential = false;
6123 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6124 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00006125 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00006126
Chris Lattner90ac28c2002-08-02 19:29:35 +00006127 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00006128 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00006129 // Replace: gep (gep %P, long B), long A, ...
6130 // With: T = long A+B; gep %P, T, ...
6131 //
Chris Lattner620ce142004-05-07 22:09:22 +00006132 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00006133 if (SO1 == Constant::getNullValue(SO1->getType())) {
6134 Sum = GO1;
6135 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6136 Sum = SO1;
6137 } else {
6138 // If they aren't the same type, convert both to an integer of the
6139 // target's pointer size.
6140 if (SO1->getType() != GO1->getType()) {
6141 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6142 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6143 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6144 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6145 } else {
6146 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00006147 if (SO1->getType()->getPrimitiveSize() == PS) {
6148 // Convert GO1 to SO1's type.
6149 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6150
6151 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6152 // Convert SO1 to GO1's type.
6153 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6154 } else {
6155 const Type *PT = TD->getIntPtrType();
6156 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6157 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6158 }
6159 }
6160 }
Chris Lattner620ce142004-05-07 22:09:22 +00006161 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6162 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6163 else {
Chris Lattner48595f12004-06-10 02:07:29 +00006164 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6165 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00006166 }
Chris Lattner28977af2004-04-05 01:30:19 +00006167 }
Chris Lattner620ce142004-05-07 22:09:22 +00006168
6169 // Recycle the GEP we already have if possible.
6170 if (SrcGEPOperands.size() == 2) {
6171 GEP.setOperand(0, SrcGEPOperands[0]);
6172 GEP.setOperand(1, Sum);
6173 return &GEP;
6174 } else {
6175 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6176 SrcGEPOperands.end()-1);
6177 Indices.push_back(Sum);
6178 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6179 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006180 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00006181 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006182 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00006183 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00006184 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6185 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00006186 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6187 }
6188
6189 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00006190 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00006191
Chris Lattner620ce142004-05-07 22:09:22 +00006192 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00006193 // GEP of global variable. If all of the indices for this GEP are
6194 // constants, we can promote this to a constexpr instead of an instruction.
6195
6196 // Scan for nonconstants...
6197 std::vector<Constant*> Indices;
6198 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6199 for (; I != E && isa<Constant>(*I); ++I)
6200 Indices.push_back(cast<Constant>(*I));
6201
6202 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00006203 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00006204
6205 // Replace all uses of the GEP with the new constexpr...
6206 return ReplaceInstUsesWith(GEP, CE);
6207 }
Chris Lattnereed48272005-09-13 00:40:14 +00006208 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6209 if (!isa<PointerType>(X->getType())) {
6210 // Not interesting. Source pointer must be a cast from pointer.
6211 } else if (HasZeroPointerIndex) {
6212 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6213 // into : GEP [10 x ubyte]* X, long 0, ...
6214 //
6215 // This occurs when the program declares an array extern like "int X[];"
6216 //
6217 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6218 const PointerType *XTy = cast<PointerType>(X->getType());
6219 if (const ArrayType *XATy =
6220 dyn_cast<ArrayType>(XTy->getElementType()))
6221 if (const ArrayType *CATy =
6222 dyn_cast<ArrayType>(CPTy->getElementType()))
6223 if (CATy->getElementType() == XATy->getElementType()) {
6224 // At this point, we know that the cast source type is a pointer
6225 // to an array of the same type as the destination pointer
6226 // array. Because the array type is never stepped over (there
6227 // is a leading zero) we can fold the cast into this GEP.
6228 GEP.setOperand(0, X);
6229 return &GEP;
6230 }
6231 } else if (GEP.getNumOperands() == 2) {
6232 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00006233 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6234 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00006235 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6236 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6237 if (isa<ArrayType>(SrcElTy) &&
6238 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6239 TD->getTypeSize(ResElTy)) {
6240 Value *V = InsertNewInstBefore(
6241 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6242 GEP.getOperand(1), GEP.getName()), GEP);
6243 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006244 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00006245
6246 // Transform things like:
6247 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6248 // (where tmp = 8*tmp2) into:
6249 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6250
6251 if (isa<ArrayType>(SrcElTy) &&
6252 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6253 uint64_t ArrayEltSize =
6254 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6255
6256 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6257 // allow either a mul, shift, or constant here.
6258 Value *NewIdx = 0;
6259 ConstantInt *Scale = 0;
6260 if (ArrayEltSize == 1) {
6261 NewIdx = GEP.getOperand(1);
6262 Scale = ConstantInt::get(NewIdx->getType(), 1);
6263 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00006264 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006265 Scale = CI;
6266 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6267 if (Inst->getOpcode() == Instruction::Shl &&
6268 isa<ConstantInt>(Inst->getOperand(1))) {
6269 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6270 if (Inst->getType()->isSigned())
6271 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6272 else
6273 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6274 NewIdx = Inst->getOperand(0);
6275 } else if (Inst->getOpcode() == Instruction::Mul &&
6276 isa<ConstantInt>(Inst->getOperand(1))) {
6277 Scale = cast<ConstantInt>(Inst->getOperand(1));
6278 NewIdx = Inst->getOperand(0);
6279 }
6280 }
6281
6282 // If the index will be to exactly the right offset with the scale taken
6283 // out, perform the transformation.
6284 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6285 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6286 Scale = ConstantSInt::get(C->getType(),
Chris Lattner6e2f8432005-09-14 17:32:56 +00006287 (int64_t)C->getRawValue() /
6288 (int64_t)ArrayEltSize);
Chris Lattner7835cdd2005-09-13 18:36:04 +00006289 else
6290 Scale = ConstantUInt::get(Scale->getType(),
6291 Scale->getRawValue() / ArrayEltSize);
6292 if (Scale->getRawValue() != 1) {
6293 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6294 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6295 NewIdx = InsertNewInstBefore(Sc, GEP);
6296 }
6297
6298 // Insert the new GEP instruction.
6299 Instruction *Idx =
6300 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6301 NewIdx, GEP.getName());
6302 Idx = InsertNewInstBefore(Idx, GEP);
6303 return new CastInst(Idx, GEP.getType());
6304 }
6305 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006306 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00006307 }
6308
Chris Lattner8a2a3112001-12-14 16:52:21 +00006309 return 0;
6310}
6311
Chris Lattner0864acf2002-11-04 16:18:53 +00006312Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6313 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6314 if (AI.isArrayAllocation()) // Check C != 1
6315 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6316 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00006317 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00006318
6319 // Create and insert the replacement instruction...
6320 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00006321 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00006322 else {
6323 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00006324 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00006325 }
Chris Lattner7c881df2004-03-19 06:08:10 +00006326
6327 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00006328
Chris Lattner0864acf2002-11-04 16:18:53 +00006329 // Scan to the end of the allocation instructions, to skip over a block of
6330 // allocas if possible...
6331 //
6332 BasicBlock::iterator It = New;
6333 while (isa<AllocationInst>(*It)) ++It;
6334
6335 // Now that I is pointing to the first non-allocation-inst in the block,
6336 // insert our getelementptr instruction...
6337 //
Chris Lattner693787a2005-05-04 19:10:26 +00006338 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6339 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6340 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00006341
6342 // Now make everything use the getelementptr instead of the original
6343 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00006344 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00006345 } else if (isa<UndefValue>(AI.getArraySize())) {
6346 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00006347 }
Chris Lattner7c881df2004-03-19 06:08:10 +00006348
6349 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6350 // Note that we only do this for alloca's, because malloc should allocate and
6351 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00006352 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00006353 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00006354 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6355
Chris Lattner0864acf2002-11-04 16:18:53 +00006356 return 0;
6357}
6358
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006359Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6360 Value *Op = FI.getOperand(0);
6361
6362 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6363 if (CastInst *CI = dyn_cast<CastInst>(Op))
6364 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6365 FI.setOperand(0, CI->getOperand(0));
6366 return &FI;
6367 }
6368
Chris Lattner17be6352004-10-18 02:59:09 +00006369 // free undef -> unreachable.
6370 if (isa<UndefValue>(Op)) {
6371 // Insert a new store to null because we cannot modify the CFG here.
6372 new StoreInst(ConstantBool::True,
6373 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6374 return EraseInstFromFunction(FI);
6375 }
6376
Chris Lattner6160e852004-02-28 04:57:37 +00006377 // If we have 'free null' delete the instruction. This can happen in stl code
6378 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00006379 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006380 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00006381
Chris Lattner67b1e1b2003-12-07 01:24:23 +00006382 return 0;
6383}
6384
6385
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006386/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00006387static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6388 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00006389 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00006390
6391 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00006392 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00006393 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00006394
Chris Lattnera1c35382006-04-02 05:37:12 +00006395 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6396 isa<PackedType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00006397 // If the source is an array, the code below will not succeed. Check to
6398 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6399 // constants.
6400 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6401 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6402 if (ASrcTy->getNumElements() != 0) {
6403 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6404 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6405 SrcTy = cast<PointerType>(CastOp->getType());
6406 SrcPTy = SrcTy->getElementType();
6407 }
6408
Chris Lattnera1c35382006-04-02 05:37:12 +00006409 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6410 isa<PackedType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00006411 // Do not allow turning this into a load of an integer, which is then
6412 // casted to a pointer, this pessimizes pointer analysis a lot.
6413 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006414 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00006415 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00006416
Chris Lattnerf9527852005-01-31 04:50:46 +00006417 // Okay, we are casting from one integer or pointer type to another of
6418 // the same size. Instead of casting the pointer before the load, cast
6419 // the result of the loaded value.
6420 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6421 CI->getName(),
6422 LI.isVolatile()),LI);
6423 // Now cast the result of the load.
6424 return new CastInst(NewLoad, LI.getType());
6425 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00006426 }
6427 }
6428 return 0;
6429}
6430
Chris Lattnerc10aced2004-09-19 18:43:46 +00006431/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00006432/// from this value cannot trap. If it is not obviously safe to load from the
6433/// specified pointer, we do a quick local scan of the basic block containing
6434/// ScanFrom, to determine if the address is already accessed.
6435static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6436 // If it is an alloca or global variable, it is always safe to load from.
6437 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6438
6439 // Otherwise, be a little bit agressive by scanning the local block where we
6440 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006441 // from/to. If so, the previous load or store would have already trapped,
6442 // so there is no harm doing an extra load (also, CSE will later eliminate
6443 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00006444 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6445
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006446 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00006447 --BBI;
6448
6449 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6450 if (LI->getOperand(0) == V) return true;
6451 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6452 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00006453
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00006454 }
Chris Lattner8a375202004-09-19 19:18:10 +00006455 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00006456}
6457
Chris Lattner833b8a42003-06-26 05:06:25 +00006458Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6459 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00006460
Chris Lattner37366c12005-05-01 04:24:53 +00006461 // load (cast X) --> cast (load X) iff safe
6462 if (CastInst *CI = dyn_cast<CastInst>(Op))
6463 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6464 return Res;
6465
6466 // None of the following transforms are legal for volatile loads.
6467 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00006468
Chris Lattner62f254d2005-09-12 22:00:15 +00006469 if (&LI.getParent()->front() != &LI) {
6470 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00006471 // If the instruction immediately before this is a store to the same
6472 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00006473 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6474 if (SI->getOperand(1) == LI.getOperand(0))
6475 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00006476 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6477 if (LIB->getOperand(0) == LI.getOperand(0))
6478 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00006479 }
Chris Lattner37366c12005-05-01 04:24:53 +00006480
6481 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6482 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6483 isa<UndefValue>(GEPI->getOperand(0))) {
6484 // Insert a new store to null instruction before the load to indicate
6485 // that this code is not reachable. We do this instead of inserting
6486 // an unreachable instruction directly because we cannot modify the
6487 // CFG.
6488 new StoreInst(UndefValue::get(LI.getType()),
6489 Constant::getNullValue(Op->getType()), &LI);
6490 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6491 }
6492
Chris Lattnere87597f2004-10-16 18:11:37 +00006493 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00006494 // load null/undef -> undef
6495 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00006496 // Insert a new store to null instruction before the load to indicate that
6497 // this code is not reachable. We do this instead of inserting an
6498 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00006499 new StoreInst(UndefValue::get(LI.getType()),
6500 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00006501 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00006502 }
Chris Lattner833b8a42003-06-26 05:06:25 +00006503
Chris Lattnere87597f2004-10-16 18:11:37 +00006504 // Instcombine load (constant global) into the value loaded.
6505 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6506 if (GV->isConstant() && !GV->isExternal())
6507 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00006508
Chris Lattnere87597f2004-10-16 18:11:37 +00006509 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6510 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6511 if (CE->getOpcode() == Instruction::GetElementPtr) {
6512 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6513 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00006514 if (Constant *V =
6515 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00006516 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00006517 if (CE->getOperand(0)->isNullValue()) {
6518 // Insert a new store to null instruction before the load to indicate
6519 // that this code is not reachable. We do this instead of inserting
6520 // an unreachable instruction directly because we cannot modify the
6521 // CFG.
6522 new StoreInst(UndefValue::get(LI.getType()),
6523 Constant::getNullValue(Op->getType()), &LI);
6524 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6525 }
6526
Chris Lattnere87597f2004-10-16 18:11:37 +00006527 } else if (CE->getOpcode() == Instruction::Cast) {
6528 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6529 return Res;
6530 }
6531 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00006532
Chris Lattner37366c12005-05-01 04:24:53 +00006533 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00006534 // Change select and PHI nodes to select values instead of addresses: this
6535 // helps alias analysis out a lot, allows many others simplifications, and
6536 // exposes redundancy in the code.
6537 //
6538 // Note that we cannot do the transformation unless we know that the
6539 // introduced loads cannot trap! Something like this is valid as long as
6540 // the condition is always false: load (select bool %C, int* null, int* %G),
6541 // but it would not be valid if we transformed it to load from null
6542 // unconditionally.
6543 //
6544 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6545 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00006546 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6547 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00006548 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006549 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00006550 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006551 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00006552 return new SelectInst(SI->getCondition(), V1, V2);
6553 }
6554
Chris Lattner684fe212004-09-23 15:46:00 +00006555 // load (select (cond, null, P)) -> load P
6556 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6557 if (C->isNullValue()) {
6558 LI.setOperand(0, SI->getOperand(2));
6559 return &LI;
6560 }
6561
6562 // load (select (cond, P, null)) -> load P
6563 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6564 if (C->isNullValue()) {
6565 LI.setOperand(0, SI->getOperand(1));
6566 return &LI;
6567 }
6568
Chris Lattnerc10aced2004-09-19 18:43:46 +00006569 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6570 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006571 bool Safe = PN->getParent() == LI.getParent();
6572
6573 // Scan all of the instructions between the PHI and the load to make
6574 // sure there are no instructions that might possibly alter the value
6575 // loaded from the PHI.
6576 if (Safe) {
6577 BasicBlock::iterator I = &LI;
6578 for (--I; !isa<PHINode>(I); --I)
6579 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6580 Safe = false;
6581 break;
6582 }
6583 }
6584
6585 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00006586 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006587 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00006588 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00006589
Chris Lattnerc10aced2004-09-19 18:43:46 +00006590 if (Safe) {
6591 // Create the PHI.
6592 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6593 InsertNewInstBefore(NewPN, *PN);
6594 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6595
6596 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6597 BasicBlock *BB = PN->getIncomingBlock(i);
6598 Value *&TheLoad = LoadMap[BB];
6599 if (TheLoad == 0) {
6600 Value *InVal = PN->getIncomingValue(i);
6601 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6602 InVal->getName()+".val"),
6603 *BB->getTerminator());
6604 }
6605 NewPN->addIncoming(TheLoad, BB);
6606 }
6607 return ReplaceInstUsesWith(LI, NewPN);
6608 }
6609 }
6610 }
Chris Lattner833b8a42003-06-26 05:06:25 +00006611 return 0;
6612}
6613
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006614/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6615/// when possible.
6616static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6617 User *CI = cast<User>(SI.getOperand(1));
6618 Value *CastOp = CI->getOperand(0);
6619
6620 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6621 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6622 const Type *SrcPTy = SrcTy->getElementType();
6623
6624 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6625 // If the source is an array, the code below will not succeed. Check to
6626 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6627 // constants.
6628 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6629 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6630 if (ASrcTy->getNumElements() != 0) {
6631 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6632 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6633 SrcTy = cast<PointerType>(CastOp->getType());
6634 SrcPTy = SrcTy->getElementType();
6635 }
6636
6637 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006638 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006639 IC.getTargetData().getTypeSize(DestPTy)) {
6640
6641 // Okay, we are casting from one integer or pointer type to another of
6642 // the same size. Instead of casting the pointer before the store, cast
6643 // the value to be stored.
6644 Value *NewCast;
6645 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6646 NewCast = ConstantExpr::getCast(C, SrcPTy);
6647 else
6648 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6649 SrcPTy,
6650 SI.getOperand(0)->getName()+".c"), SI);
6651
6652 return new StoreInst(NewCast, CastOp);
6653 }
6654 }
6655 }
6656 return 0;
6657}
6658
Chris Lattner2f503e62005-01-31 05:36:43 +00006659Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6660 Value *Val = SI.getOperand(0);
6661 Value *Ptr = SI.getOperand(1);
6662
6663 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00006664 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00006665 ++NumCombined;
6666 return 0;
6667 }
6668
Chris Lattner9ca96412006-02-08 03:25:32 +00006669 // Do really simple DSE, to catch cases where there are several consequtive
6670 // stores to the same location, separated by a few arithmetic operations. This
6671 // situation often occurs with bitfield accesses.
6672 BasicBlock::iterator BBI = &SI;
6673 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6674 --ScanInsts) {
6675 --BBI;
6676
6677 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6678 // Prev store isn't volatile, and stores to the same location?
6679 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6680 ++NumDeadStore;
6681 ++BBI;
6682 EraseInstFromFunction(*PrevSI);
6683 continue;
6684 }
6685 break;
6686 }
6687
6688 // Don't skip over loads or things that can modify memory.
6689 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6690 break;
6691 }
6692
6693
6694 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00006695
6696 // store X, null -> turns into 'unreachable' in SimplifyCFG
6697 if (isa<ConstantPointerNull>(Ptr)) {
6698 if (!isa<UndefValue>(Val)) {
6699 SI.setOperand(0, UndefValue::get(Val->getType()));
6700 if (Instruction *U = dyn_cast<Instruction>(Val))
6701 WorkList.push_back(U); // Dropped a use.
6702 ++NumCombined;
6703 }
6704 return 0; // Do not modify these!
6705 }
6706
6707 // store undef, Ptr -> noop
6708 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00006709 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00006710 ++NumCombined;
6711 return 0;
6712 }
6713
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00006714 // If the pointer destination is a cast, see if we can fold the cast into the
6715 // source instead.
6716 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6717 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6718 return Res;
6719 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6720 if (CE->getOpcode() == Instruction::Cast)
6721 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6722 return Res;
6723
Chris Lattner408902b2005-09-12 23:23:25 +00006724
6725 // If this store is the last instruction in the basic block, and if the block
6726 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00006727 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00006728 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6729 if (BI->isUnconditional()) {
6730 // Check to see if the successor block has exactly two incoming edges. If
6731 // so, see if the other predecessor contains a store to the same location.
6732 // if so, insert a PHI node (if needed) and move the stores down.
6733 BasicBlock *Dest = BI->getSuccessor(0);
6734
6735 pred_iterator PI = pred_begin(Dest);
6736 BasicBlock *Other = 0;
6737 if (*PI != BI->getParent())
6738 Other = *PI;
6739 ++PI;
6740 if (PI != pred_end(Dest)) {
6741 if (*PI != BI->getParent())
6742 if (Other)
6743 Other = 0;
6744 else
6745 Other = *PI;
6746 if (++PI != pred_end(Dest))
6747 Other = 0;
6748 }
6749 if (Other) { // If only one other pred...
6750 BBI = Other->getTerminator();
6751 // Make sure this other block ends in an unconditional branch and that
6752 // there is an instruction before the branch.
6753 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6754 BBI != Other->begin()) {
6755 --BBI;
6756 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6757
6758 // If this instruction is a store to the same location.
6759 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6760 // Okay, we know we can perform this transformation. Insert a PHI
6761 // node now if we need it.
6762 Value *MergedVal = OtherStore->getOperand(0);
6763 if (MergedVal != SI.getOperand(0)) {
6764 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6765 PN->reserveOperandSpace(2);
6766 PN->addIncoming(SI.getOperand(0), SI.getParent());
6767 PN->addIncoming(OtherStore->getOperand(0), Other);
6768 MergedVal = InsertNewInstBefore(PN, Dest->front());
6769 }
6770
6771 // Advance to a place where it is safe to insert the new store and
6772 // insert it.
6773 BBI = Dest->begin();
6774 while (isa<PHINode>(BBI)) ++BBI;
6775 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6776 OtherStore->isVolatile()), *BBI);
6777
6778 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00006779 EraseInstFromFunction(SI);
6780 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00006781 ++NumCombined;
6782 return 0;
6783 }
6784 }
6785 }
6786 }
6787
Chris Lattner2f503e62005-01-31 05:36:43 +00006788 return 0;
6789}
6790
6791
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006792Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6793 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00006794 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006795 BasicBlock *TrueDest;
6796 BasicBlock *FalseDest;
6797 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6798 !isa<Constant>(X)) {
6799 // Swap Destinations and condition...
6800 BI.setCondition(X);
6801 BI.setSuccessor(0, FalseDest);
6802 BI.setSuccessor(1, TrueDest);
6803 return &BI;
6804 }
6805
6806 // Cannonicalize setne -> seteq
6807 Instruction::BinaryOps Op; Value *Y;
6808 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6809 TrueDest, FalseDest)))
6810 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6811 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6812 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6813 std::string Name = I->getName(); I->setName("");
6814 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6815 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00006816 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006817 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00006818 BI.setSuccessor(0, FalseDest);
6819 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00006820 removeFromWorkList(I);
6821 I->getParent()->getInstList().erase(I);
6822 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00006823 return &BI;
6824 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006825
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00006826 return 0;
6827}
Chris Lattner0864acf2002-11-04 16:18:53 +00006828
Chris Lattner46238a62004-07-03 00:26:11 +00006829Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6830 Value *Cond = SI.getCondition();
6831 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6832 if (I->getOpcode() == Instruction::Add)
6833 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6834 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6835 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00006836 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00006837 AddRHS));
6838 SI.setOperand(0, I->getOperand(0));
6839 WorkList.push_back(I);
6840 return &SI;
6841 }
6842 }
6843 return 0;
6844}
6845
Chris Lattner220b0cf2006-03-05 00:22:33 +00006846/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6847/// is to leave as a vector operation.
6848static bool CheapToScalarize(Value *V, bool isConstant) {
6849 if (isa<ConstantAggregateZero>(V))
6850 return true;
6851 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6852 if (isConstant) return true;
6853 // If all elts are the same, we can extract.
6854 Constant *Op0 = C->getOperand(0);
6855 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6856 if (C->getOperand(i) != Op0)
6857 return false;
6858 return true;
6859 }
6860 Instruction *I = dyn_cast<Instruction>(V);
6861 if (!I) return false;
6862
6863 // Insert element gets simplified to the inserted element or is deleted if
6864 // this is constant idx extract element and its a constant idx insertelt.
6865 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6866 isa<ConstantInt>(I->getOperand(2)))
6867 return true;
6868 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6869 return true;
6870 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6871 if (BO->hasOneUse() &&
6872 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6873 CheapToScalarize(BO->getOperand(1), isConstant)))
6874 return true;
6875
6876 return false;
6877}
6878
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006879/// FindScalarElement - Given a vector and an element number, see if the scalar
6880/// value is already around as a register, for example if it were inserted then
6881/// extracted from the vector.
6882static Value *FindScalarElement(Value *V, unsigned EltNo) {
6883 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
6884 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00006885 unsigned Width = PTy->getNumElements();
6886 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006887 return UndefValue::get(PTy->getElementType());
6888
6889 if (isa<UndefValue>(V))
6890 return UndefValue::get(PTy->getElementType());
6891 else if (isa<ConstantAggregateZero>(V))
6892 return Constant::getNullValue(PTy->getElementType());
6893 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
6894 return CP->getOperand(EltNo);
6895 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
6896 // If this is an insert to a variable element, we don't know what it is.
6897 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
6898 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
6899
6900 // If this is an insert to the element we are looking for, return the
6901 // inserted value.
6902 if (EltNo == IIElt) return III->getOperand(1);
6903
6904 // Otherwise, the insertelement doesn't modify the value, recurse on its
6905 // vector input.
6906 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00006907 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
6908 if (isa<ConstantAggregateZero>(SVI->getOperand(2))) {
6909 return FindScalarElement(SVI->getOperand(0), 0);
6910 } else if (ConstantPacked *CP =
6911 dyn_cast<ConstantPacked>(SVI->getOperand(2))) {
6912 if (isa<UndefValue>(CP->getOperand(EltNo)))
6913 return UndefValue::get(PTy->getElementType());
6914 unsigned InEl = cast<ConstantUInt>(CP->getOperand(EltNo))->getValue();
6915 if (InEl < Width)
6916 return FindScalarElement(SVI->getOperand(0), InEl);
6917 else
6918 return FindScalarElement(SVI->getOperand(1), InEl - Width);
6919 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006920 }
6921
6922 // Otherwise, we don't know.
6923 return 0;
6924}
6925
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006926Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006927
Chris Lattner1f13c882006-03-31 18:25:14 +00006928 // If packed val is undef, replace extract with scalar undef.
6929 if (isa<UndefValue>(EI.getOperand(0)))
6930 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
6931
6932 // If packed val is constant 0, replace extract with scalar 0.
6933 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
6934 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
6935
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006936 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6937 // If packed val is constant with uniform operands, replace EI
6938 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00006939 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006940 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00006941 if (C->getOperand(i) != op0) {
6942 op0 = 0;
6943 break;
6944 }
6945 if (op0)
6946 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006947 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00006948
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006949 // If extracting a specified index from the vector, see if we can recursively
6950 // find a previously computed scalar that was inserted into the vector.
Chris Lattner389a6f52006-04-10 23:06:36 +00006951 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006952 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
6953 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00006954 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00006955
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006956 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6957 if (I->hasOneUse()) {
6958 // Push extractelement into predecessor operation if legal and
6959 // profitable to do so
6960 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00006961 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
6962 if (CheapToScalarize(BO, isConstantElt)) {
6963 ExtractElementInst *newEI0 =
6964 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6965 EI.getName()+".lhs");
6966 ExtractElementInst *newEI1 =
6967 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6968 EI.getName()+".rhs");
6969 InsertNewInstBefore(newEI0, EI);
6970 InsertNewInstBefore(newEI1, EI);
6971 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6972 }
6973 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006974 Value *Ptr = InsertCastBefore(I->getOperand(0),
6975 PointerType::get(EI.getType()), EI);
6976 GetElementPtrInst *GEP =
6977 new GetElementPtrInst(Ptr, EI.getOperand(1),
6978 I->getName() + ".gep");
6979 InsertNewInstBefore(GEP, EI);
6980 return new LoadInst(GEP);
Chris Lattner220b0cf2006-03-05 00:22:33 +00006981 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
6982 // Extracting the inserted element?
6983 if (IE->getOperand(2) == EI.getOperand(1))
6984 return ReplaceInstUsesWith(EI, IE->getOperand(1));
6985 // If the inserted and extracted elements are constants, they must not
Chris Lattnerdf084ff2006-03-30 22:02:40 +00006986 // be the same value, extract from the pre-inserted value instead.
6987 if (isa<Constant>(IE->getOperand(2)) &&
6988 isa<Constant>(EI.getOperand(1))) {
6989 AddUsesToWorkList(EI);
6990 EI.setOperand(0, IE->getOperand(0));
6991 return &EI;
6992 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00006993 }
6994 }
6995 return 0;
6996}
6997
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00006998/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
6999/// elements from either LHS or RHS, return the shuffle mask and true.
7000/// Otherwise, return false.
7001static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7002 std::vector<Constant*> &Mask) {
7003 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7004 "Invalid CollectSingleShuffleElements");
7005 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7006
7007 if (isa<UndefValue>(V)) {
7008 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7009 return true;
7010 } else if (V == LHS) {
7011 for (unsigned i = 0; i != NumElts; ++i)
7012 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7013 return true;
7014 } else if (V == RHS) {
7015 for (unsigned i = 0; i != NumElts; ++i)
7016 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7017 return true;
7018 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7019 // If this is an insert of an extract from some other vector, include it.
7020 Value *VecOp = IEI->getOperand(0);
7021 Value *ScalarOp = IEI->getOperand(1);
7022 Value *IdxOp = IEI->getOperand(2);
7023
Chris Lattnerd929f062006-04-27 21:14:21 +00007024 if (!isa<ConstantInt>(IdxOp))
7025 return false;
7026 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7027
7028 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7029 // Okay, we can handle this if the vector we are insertinting into is
7030 // transitively ok.
7031 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7032 // If so, update the mask to reflect the inserted undef.
7033 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7034 return true;
7035 }
7036 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7037 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007038 EI->getOperand(0)->getType() == V->getType()) {
7039 unsigned ExtractedIdx =
7040 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007041
7042 // This must be extracting from either LHS or RHS.
7043 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7044 // Okay, we can handle this if the vector we are insertinting into is
7045 // transitively ok.
7046 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7047 // If so, update the mask to reflect the inserted value.
7048 if (EI->getOperand(0) == LHS) {
7049 Mask[InsertedIdx & (NumElts-1)] =
7050 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7051 } else {
7052 assert(EI->getOperand(0) == RHS);
7053 Mask[InsertedIdx & (NumElts-1)] =
7054 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7055
7056 }
7057 return true;
7058 }
7059 }
7060 }
7061 }
7062 }
7063 // TODO: Handle shufflevector here!
7064
7065 return false;
7066}
7067
7068/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7069/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7070/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00007071static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007072 Value *&RHS) {
7073 assert(isa<PackedType>(V->getType()) &&
7074 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00007075 "Invalid shuffle!");
7076 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7077
7078 if (isa<UndefValue>(V)) {
7079 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7080 return V;
7081 } else if (isa<ConstantAggregateZero>(V)) {
7082 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7083 return V;
7084 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7085 // If this is an insert of an extract from some other vector, include it.
7086 Value *VecOp = IEI->getOperand(0);
7087 Value *ScalarOp = IEI->getOperand(1);
7088 Value *IdxOp = IEI->getOperand(2);
7089
7090 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7091 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7092 EI->getOperand(0)->getType() == V->getType()) {
7093 unsigned ExtractedIdx =
7094 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7095 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7096
7097 // Either the extracted from or inserted into vector must be RHSVec,
7098 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007099 if (EI->getOperand(0) == RHS || RHS == 0) {
7100 RHS = EI->getOperand(0);
7101 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00007102 Mask[InsertedIdx & (NumElts-1)] =
7103 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7104 return V;
7105 }
7106
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007107 if (VecOp == RHS) {
7108 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00007109 // Everything but the extracted element is replaced with the RHS.
7110 for (unsigned i = 0; i != NumElts; ++i) {
7111 if (i != InsertedIdx)
7112 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7113 }
7114 return V;
7115 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007116
7117 // If this insertelement is a chain that comes from exactly these two
7118 // vectors, return the vector and the effective shuffle.
7119 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7120 return EI->getOperand(0);
7121
Chris Lattnerefb47352006-04-15 01:39:45 +00007122 }
7123 }
7124 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007125 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00007126
7127 // Otherwise, can't do anything fancy. Return an identity vector.
7128 for (unsigned i = 0; i != NumElts; ++i)
7129 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7130 return V;
7131}
7132
7133Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7134 Value *VecOp = IE.getOperand(0);
7135 Value *ScalarOp = IE.getOperand(1);
7136 Value *IdxOp = IE.getOperand(2);
7137
7138 // If the inserted element was extracted from some other vector, and if the
7139 // indexes are constant, try to turn this into a shufflevector operation.
7140 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7141 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7142 EI->getOperand(0)->getType() == IE.getType()) {
7143 unsigned NumVectorElts = IE.getType()->getNumElements();
7144 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7145 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7146
7147 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7148 return ReplaceInstUsesWith(IE, VecOp);
7149
7150 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7151 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7152
7153 // If we are extracting a value from a vector, then inserting it right
7154 // back into the same place, just use the input vector.
7155 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7156 return ReplaceInstUsesWith(IE, VecOp);
7157
7158 // We could theoretically do this for ANY input. However, doing so could
7159 // turn chains of insertelement instructions into a chain of shufflevector
7160 // instructions, and right now we do not merge shufflevectors. As such,
7161 // only do this in a situation where it is clear that there is benefit.
7162 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7163 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7164 // the values of VecOp, except then one read from EIOp0.
7165 // Build a new shuffle mask.
7166 std::vector<Constant*> Mask;
7167 if (isa<UndefValue>(VecOp))
7168 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7169 else {
7170 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7171 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7172 NumVectorElts));
7173 }
7174 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7175 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7176 ConstantPacked::get(Mask));
7177 }
7178
7179 // If this insertelement isn't used by some other insertelement, turn it
7180 // (and any insertelements it points to), into one big shuffle.
7181 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7182 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007183 Value *RHS = 0;
7184 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7185 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7186 // We now have a shuffle of LHS, RHS, Mask.
7187 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00007188 }
7189 }
7190 }
7191
7192 return 0;
7193}
7194
7195
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007196Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7197 Value *LHS = SVI.getOperand(0);
7198 Value *RHS = SVI.getOperand(1);
7199 Constant *Mask = cast<Constant>(SVI.getOperand(2));
7200
7201 bool MadeChange = false;
7202
7203 if (isa<UndefValue>(Mask))
7204 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7205
Chris Lattnerefb47352006-04-15 01:39:45 +00007206 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7207 // the undef, change them to undefs.
7208
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007209 // Canonicalize shuffle(x,x) -> shuffle(x,undef)
7210 if (LHS == RHS) {
7211 if (isa<UndefValue>(LHS)) {
7212 // shuffle(undef,undef,mask) -> undef.
7213 return ReplaceInstUsesWith(SVI, LHS);
7214 }
7215
7216 if (!isa<ConstantAggregateZero>(Mask)) {
7217 // Remap any references to RHS to use LHS.
7218 ConstantPacked *CP = cast<ConstantPacked>(Mask);
7219 std::vector<Constant*> Elts;
7220 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7221 Elts.push_back(CP->getOperand(i));
7222 if (isa<UndefValue>(CP->getOperand(i)))
7223 continue;
7224 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7225 if (MV >= e)
7226 Elts.back() = ConstantUInt::get(Type::UIntTy, MV & (e-1));
7227 }
7228 Mask = ConstantPacked::get(Elts);
7229 }
7230 SVI.setOperand(1, UndefValue::get(RHS->getType()));
7231 SVI.setOperand(2, Mask);
7232 MadeChange = true;
7233 }
7234
Chris Lattner706126d2006-04-16 00:03:56 +00007235 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7236 if (isa<UndefValue>(LHS)) {
7237 // shuffle(undef,x,<0,0,0,0>) -> undef.
7238 if (isa<ConstantAggregateZero>(Mask))
7239 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7240
7241 ConstantPacked *CPM = cast<ConstantPacked>(Mask);
7242 std::vector<Constant*> Elts;
7243 for (unsigned i = 0, e = CPM->getNumOperands(); i != e; ++i) {
7244 if (isa<UndefValue>(CPM->getOperand(i)))
7245 Elts.push_back(CPM->getOperand(i));
7246 else {
7247 unsigned EltNo = cast<ConstantUInt>(CPM->getOperand(i))->getRawValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007248 if (EltNo >= e)
7249 Elts.push_back(ConstantUInt::get(Type::UIntTy, EltNo-e));
Chris Lattner706126d2006-04-16 00:03:56 +00007250 else // Referring to the undef.
7251 Elts.push_back(UndefValue::get(Type::UIntTy));
7252 }
7253 }
7254 return new ShuffleVectorInst(RHS, LHS, ConstantPacked::get(Elts));
7255 }
7256
Chris Lattnera844fc4c2006-04-10 22:45:52 +00007257 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Mask)) {
7258 bool isLHSID = true, isRHSID = true;
7259
7260 // Analyze the shuffle.
7261 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
7262 if (isa<UndefValue>(CP->getOperand(i)))
7263 continue;
7264 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
7265
7266 // Is this an identity shuffle of the LHS value?
7267 isLHSID &= (MV == i);
7268
7269 // Is this an identity shuffle of the RHS value?
7270 isRHSID &= (MV-e == i);
7271 }
7272
7273 // Eliminate identity shuffles.
7274 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7275 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
7276 }
7277
7278 return MadeChange ? &SVI : 0;
7279}
7280
7281
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007282
Chris Lattner62b14df2002-09-02 04:59:56 +00007283void InstCombiner::removeFromWorkList(Instruction *I) {
7284 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7285 WorkList.end());
7286}
7287
Chris Lattnerea1c4542004-12-08 23:43:58 +00007288
7289/// TryToSinkInstruction - Try to move the specified instruction from its
7290/// current block into the beginning of DestBlock, which can only happen if it's
7291/// safe to move the instruction past all of the instructions between it and the
7292/// end of its block.
7293static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7294 assert(I->hasOneUse() && "Invariants didn't hold!");
7295
Chris Lattner108e9022005-10-27 17:13:11 +00007296 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7297 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00007298
Chris Lattnerea1c4542004-12-08 23:43:58 +00007299 // Do not sink alloca instructions out of the entry block.
7300 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7301 return false;
7302
Chris Lattner96a52a62004-12-09 07:14:34 +00007303 // We can only sink load instructions if there is nothing between the load and
7304 // the end of block that could change the value.
7305 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00007306 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7307 Scan != E; ++Scan)
7308 if (Scan->mayWriteToMemory())
7309 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00007310 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00007311
7312 BasicBlock::iterator InsertPos = DestBlock->begin();
7313 while (isa<PHINode>(InsertPos)) ++InsertPos;
7314
Chris Lattner4bc5f802005-08-08 19:11:57 +00007315 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00007316 ++NumSunkInst;
7317 return true;
7318}
7319
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007320
7321/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7322/// all reachable code to the worklist.
7323///
7324/// This has a couple of tricks to make the code faster and more powerful. In
7325/// particular, we constant fold and DCE instructions as we go, to avoid adding
7326/// them to the worklist (this significantly speeds up instcombine on code where
7327/// many instructions are dead or constant). Additionally, if we find a branch
7328/// whose condition is a known constant, we only visit the reachable successors.
7329///
7330static void AddReachableCodeToWorklist(BasicBlock *BB,
7331 std::set<BasicBlock*> &Visited,
7332 std::vector<Instruction*> &WorkList) {
7333 // We have now visited this block! If we've already been here, bail out.
7334 if (!Visited.insert(BB).second) return;
7335
7336 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7337 Instruction *Inst = BBI++;
7338
7339 // DCE instruction if trivially dead.
7340 if (isInstructionTriviallyDead(Inst)) {
7341 ++NumDeadInst;
7342 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7343 Inst->eraseFromParent();
7344 continue;
7345 }
7346
7347 // ConstantProp instruction if trivially constant.
7348 if (Constant *C = ConstantFoldInstruction(Inst)) {
7349 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7350 Inst->replaceAllUsesWith(C);
7351 ++NumConstProp;
7352 Inst->eraseFromParent();
7353 continue;
7354 }
7355
7356 WorkList.push_back(Inst);
7357 }
7358
7359 // Recursively visit successors. If this is a branch or switch on a constant,
7360 // only visit the reachable successor.
7361 TerminatorInst *TI = BB->getTerminator();
7362 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7363 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7364 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
7365 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList);
7366 return;
7367 }
7368 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7369 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7370 // See if this is an explicit destination.
7371 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7372 if (SI->getCaseValue(i) == Cond) {
7373 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList);
7374 return;
7375 }
7376
7377 // Otherwise it is the default destination.
7378 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList);
7379 return;
7380 }
7381 }
7382
7383 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
7384 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList);
7385}
7386
Chris Lattner7e708292002-06-25 16:13:24 +00007387bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007388 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00007389 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00007390
Chris Lattnerb3d59702005-07-07 20:40:38 +00007391 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007392 // Do a depth-first traversal of the function, populate the worklist with
7393 // the reachable instructions. Ignore blocks that are not reachable. Keep
7394 // track of which blocks we visit.
Chris Lattnerb3d59702005-07-07 20:40:38 +00007395 std::set<BasicBlock*> Visited;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007396 AddReachableCodeToWorklist(F.begin(), Visited, WorkList);
Jeff Cohen00b168892005-07-27 06:12:32 +00007397
Chris Lattnerb3d59702005-07-07 20:40:38 +00007398 // Do a quick scan over the function. If we find any blocks that are
7399 // unreachable, remove any instructions inside of them. This prevents
7400 // the instcombine code from having to deal with some bad special cases.
7401 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7402 if (!Visited.count(BB)) {
7403 Instruction *Term = BB->getTerminator();
7404 while (Term != BB->begin()) { // Remove instrs bottom-up
7405 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00007406
Chris Lattnerb3d59702005-07-07 20:40:38 +00007407 DEBUG(std::cerr << "IC: DCE: " << *I);
7408 ++NumDeadInst;
7409
7410 if (!I->use_empty())
7411 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7412 I->eraseFromParent();
7413 }
7414 }
7415 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00007416
7417 while (!WorkList.empty()) {
7418 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7419 WorkList.pop_back();
7420
Misha Brukmana3bbcb52002-10-29 23:06:16 +00007421 // Check to see if we can DCE or ConstantPropagate the instruction...
Chris Lattner62b14df2002-09-02 04:59:56 +00007422 // Check to see if we can DIE the instruction...
7423 if (isInstructionTriviallyDead(I)) {
7424 // Add operands to the worklist...
Chris Lattner4bb7c022003-10-06 17:11:01 +00007425 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007426 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00007427 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00007428
Chris Lattnerad5fec12005-01-28 19:32:01 +00007429 DEBUG(std::cerr << "IC: DCE: " << *I);
7430
7431 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00007432 removeFromWorkList(I);
7433 continue;
7434 }
Chris Lattner62b14df2002-09-02 04:59:56 +00007435
Misha Brukmana3bbcb52002-10-29 23:06:16 +00007436 // Instruction isn't dead, see if we can constant propagate it...
Chris Lattner62b14df2002-09-02 04:59:56 +00007437 if (Constant *C = ConstantFoldInstruction(I)) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00007438 Value* Ptr = I->getOperand(0);
Chris Lattner061718c2004-10-16 19:44:59 +00007439 if (isa<GetElementPtrInst>(I) &&
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00007440 cast<Constant>(Ptr)->isNullValue() &&
7441 !isa<ConstantPointerNull>(C) &&
7442 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
Chris Lattner061718c2004-10-16 19:44:59 +00007443 // If this is a constant expr gep that is effectively computing an
7444 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
7445 bool isFoldableGEP = true;
7446 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
7447 if (!isa<ConstantInt>(I->getOperand(i)))
7448 isFoldableGEP = false;
7449 if (isFoldableGEP) {
Alkis Evlogimenos54a96a22004-12-08 23:10:30 +00007450 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
Chris Lattner061718c2004-10-16 19:44:59 +00007451 std::vector<Value*>(I->op_begin()+1, I->op_end()));
7452 C = ConstantUInt::get(Type::ULongTy, Offset);
Chris Lattner6e758ae2004-10-16 19:46:33 +00007453 C = ConstantExpr::getCast(C, TD->getIntPtrType());
Chris Lattner061718c2004-10-16 19:44:59 +00007454 C = ConstantExpr::getCast(C, I->getType());
7455 }
7456 }
7457
Chris Lattnerad5fec12005-01-28 19:32:01 +00007458 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7459
Chris Lattner62b14df2002-09-02 04:59:56 +00007460 // Add operands to the worklist...
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007461 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00007462 ReplaceInstUsesWith(*I, C);
7463
Chris Lattner62b14df2002-09-02 04:59:56 +00007464 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00007465 I->eraseFromParent();
Chris Lattner60610002003-10-07 15:17:02 +00007466 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007467 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00007468 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00007469
Chris Lattnerea1c4542004-12-08 23:43:58 +00007470 // See if we can trivially sink this instruction to a successor basic block.
7471 if (I->hasOneUse()) {
7472 BasicBlock *BB = I->getParent();
7473 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7474 if (UserParent != BB) {
7475 bool UserIsSuccessor = false;
7476 // See if the user is one of our successors.
7477 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7478 if (*SI == UserParent) {
7479 UserIsSuccessor = true;
7480 break;
7481 }
7482
7483 // If the user is one of our immediate successors, and if that successor
7484 // only has us as a predecessors (we'd have to split the critical edge
7485 // otherwise), we can keep going.
7486 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7487 next(pred_begin(UserParent)) == pred_end(UserParent))
7488 // Okay, the CFG is simple enough, try to sink this instruction.
7489 Changed |= TryToSinkInstruction(I, UserParent);
7490 }
7491 }
7492
Chris Lattner8a2a3112001-12-14 16:52:21 +00007493 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00007494 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00007495 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007496 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00007497 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00007498 DEBUG(std::cerr << "IC: Old = " << *I
7499 << " New = " << *Result);
7500
Chris Lattnerf523d062004-06-09 05:08:07 +00007501 // Everything uses the new instruction now.
7502 I->replaceAllUsesWith(Result);
7503
7504 // Push the new instruction and any users onto the worklist.
7505 WorkList.push_back(Result);
7506 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007507
7508 // Move the name to the new instruction first...
7509 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00007510 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007511
7512 // Insert the new instruction into the basic block...
7513 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00007514 BasicBlock::iterator InsertPos = I;
7515
7516 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7517 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7518 ++InsertPos;
7519
7520 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007521
Chris Lattner00d51312004-05-01 23:27:23 +00007522 // Make sure that we reprocess all operands now that we reduced their
7523 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00007524 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7525 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7526 WorkList.push_back(OpI);
7527
Chris Lattnerf523d062004-06-09 05:08:07 +00007528 // Instructions can end up on the worklist more than once. Make sure
7529 // we do not process an instruction that has been deleted.
7530 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00007531
7532 // Erase the old instruction.
7533 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00007534 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00007535 DEBUG(std::cerr << "IC: MOD = " << *I);
7536
Chris Lattner90ac28c2002-08-02 19:29:35 +00007537 // If the instruction was modified, it's possible that it is now dead.
7538 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00007539 if (isInstructionTriviallyDead(I)) {
7540 // Make sure we process all operands now that we are reducing their
7541 // use counts.
7542 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7543 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7544 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00007545
Chris Lattner00d51312004-05-01 23:27:23 +00007546 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007547 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00007548 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00007549 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00007550 } else {
7551 WorkList.push_back(Result);
7552 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00007553 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00007554 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007555 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007556 }
7557 }
7558
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007559 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00007560}
7561
Brian Gaeke96d4bf72004-07-27 17:43:21 +00007562FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007563 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00007564}
Brian Gaeked0fde302003-11-11 22:41:34 +00007565