blob: bcb4888b6aeb920feb4ba5789f8bdf516a5c4733 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner32ed46b2004-05-04 15:19:33 +000015// %Y = add int %X, 1
16// %Z = add int %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner32ed46b2004-05-04 15:19:33 +000018// %Z = add int %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Chris Lattner2cd91962003-07-23 21:41:57 +000027// 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All SetCC instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000039#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000040#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000041#include "llvm/GlobalVariable.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000042#include "llvm/Target/TargetData.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000045#include "llvm/Support/CallSite.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000046#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000047#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000048#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000049#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000050#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000051#include "llvm/Support/Compiler.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000052#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000054#include <algorithm>
Chris Lattnerdac58ad2006-01-22 23:32:06 +000055#include <iostream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000056using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000057using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000058
Chris Lattnerdd841ae2002-04-18 17:39:14 +000059namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000060 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
Chris Lattner9ca96412006-02-08 03:25:32 +000063 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
Chris Lattnerea1c4542004-12-08 23:43:58 +000064 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000065
Chris Lattnerf4b54612006-06-28 22:08:15 +000066 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000069 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
Chris Lattnerbc61e662003-11-02 05:57:39 +000071 TargetData *TD;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000072
Chris Lattner7bcc0e72004-02-28 05:22:00 +000073 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
75 /// now.
76 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +000077 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +000078 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000079 UI != UE; ++UI)
80 WorkList.push_back(cast<Instruction>(*UI));
81 }
82
Chris Lattner7bcc0e72004-02-28 05:22:00 +000083 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
85 ///
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
90 }
Chris Lattner867b99f2006-10-05 06:55:50 +000091
92 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93 /// dead. Add all of its operands to the worklist, turning them into
94 /// undef's to reduce the number of uses of those instructions.
95 ///
96 /// Return the specified operand before it is turned into an undef.
97 ///
98 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99 Value *R = I.getOperand(op);
100
101 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103 WorkList.push_back(Op);
104 // Set the operand to undef to drop the use.
105 I.setOperand(i, UndefValue::get(Op->getType()));
106 }
107
108 return R;
109 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000110
Chris Lattner62b14df2002-09-02 04:59:56 +0000111 // removeFromWorkList - remove all instances of I from the worklist.
112 void removeFromWorkList(Instruction *I);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000113 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000114 virtual bool runOnFunction(Function &F);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000115
Chris Lattner97e52e42002-04-28 21:27:06 +0000116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000117 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000118 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000119 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000120 }
121
Chris Lattner28977af2004-04-05 01:30:19 +0000122 TargetData &getTargetData() const { return *TD; }
123
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000124 // Visitation implementation - Implement instruction combining for different
125 // instruction types. The semantics are as follows:
126 // Return Value:
127 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000128 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000129 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000130 //
Chris Lattner7e708292002-06-25 16:13:24 +0000131 Instruction *visitAdd(BinaryOperator &I);
132 Instruction *visitSub(BinaryOperator &I);
133 Instruction *visitMul(BinaryOperator &I);
134 Instruction *visitDiv(BinaryOperator &I);
135 Instruction *visitRem(BinaryOperator &I);
136 Instruction *visitAnd(BinaryOperator &I);
137 Instruction *visitOr (BinaryOperator &I);
138 Instruction *visitXor(BinaryOperator &I);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000139 Instruction *visitSetCondInst(SetCondInst &I);
140 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
141
Chris Lattner574da9b2005-01-13 20:14:25 +0000142 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
143 Instruction::BinaryOps Cond, Instruction &I);
Chris Lattnerea340052003-03-10 19:16:08 +0000144 Instruction *visitShiftInst(ShiftInst &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000145 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner4d5542c2006-01-06 07:12:35 +0000146 ShiftInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000147 Instruction *visitCastInst(CastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000148 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
149 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000150 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000151 Instruction *visitCallInst(CallInst &CI);
152 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000153 Instruction *visitPHINode(PHINode &PN);
154 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000155 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000156 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000157 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000158 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000159 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000160 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000161 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000162 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000163 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000164
165 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000166 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000167
Chris Lattner9fe38862003-06-19 17:00:31 +0000168 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000169 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000170 bool transformConstExprCastCall(CallSite CS);
171
Chris Lattner28977af2004-04-05 01:30:19 +0000172 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000173 // InsertNewInstBefore - insert an instruction New before instruction Old
174 // in the program. Add the new instruction to the worklist.
175 //
Chris Lattner955f3312004-09-28 21:48:02 +0000176 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000177 assert(New && New->getParent() == 0 &&
178 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000179 BasicBlock *BB = Old.getParent();
180 BB->getInstList().insert(&Old, New); // Insert inst
181 WorkList.push_back(New); // Add to worklist
Chris Lattner4cb170c2004-02-23 06:38:22 +0000182 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000183 }
184
Chris Lattner0c967662004-09-24 15:21:34 +0000185 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
186 /// This also adds the cast to the worklist. Finally, this returns the
187 /// cast.
188 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
189 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000190
Chris Lattnere2ed0572006-04-06 19:19:17 +0000191 if (Constant *CV = dyn_cast<Constant>(V))
192 return ConstantExpr::getCast(CV, Ty);
193
Chris Lattner0c967662004-09-24 15:21:34 +0000194 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
195 WorkList.push_back(C);
196 return C;
197 }
198
Chris Lattner8b170942002-08-09 23:47:40 +0000199 // ReplaceInstUsesWith - This method is to be used when an instruction is
200 // found to be dead, replacable with another preexisting expression. Here
201 // we add all uses of I to the worklist, replace all uses of I with the new
202 // value, then return I, so that the inst combiner will know that I was
203 // modified.
204 //
205 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000206 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000207 if (&I != V) {
208 I.replaceAllUsesWith(V);
209 return &I;
210 } else {
211 // If we are replacing the instruction with itself, this must be in a
212 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000213 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000214 return &I;
215 }
Chris Lattner8b170942002-08-09 23:47:40 +0000216 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000217
Chris Lattner6dce1a72006-02-07 06:56:34 +0000218 // UpdateValueUsesWith - This method is to be used when an value is
219 // found to be replacable with another preexisting expression or was
220 // updated. Here we add all uses of I to the worklist, replace all uses of
221 // I with the new value (unless the instruction was just updated), then
222 // return true, so that the inst combiner will know that I was modified.
223 //
224 bool UpdateValueUsesWith(Value *Old, Value *New) {
225 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
226 if (Old != New)
227 Old->replaceAllUsesWith(New);
228 if (Instruction *I = dyn_cast<Instruction>(Old))
229 WorkList.push_back(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000230 if (Instruction *I = dyn_cast<Instruction>(New))
231 WorkList.push_back(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000232 return true;
233 }
234
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000235 // EraseInstFromFunction - When dealing with an instruction that has side
236 // effects or produces a void value, we can't rely on DCE to delete the
237 // instruction. Instead, visit methods should return the value returned by
238 // this function.
239 Instruction *EraseInstFromFunction(Instruction &I) {
240 assert(I.use_empty() && "Cannot erase instruction that is used!");
241 AddUsesToWorkList(I);
242 removeFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000243 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000244 return 0; // Don't do anything with FI
245 }
246
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000247 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000248 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
249 /// InsertBefore instruction. This is specialized a bit to avoid inserting
250 /// casts that are known to not do anything...
251 ///
252 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
253 Instruction *InsertBefore);
254
Chris Lattnerc8802d22003-03-11 00:12:48 +0000255 // SimplifyCommutative - This performs a few simplifications for commutative
Chris Lattner4e998b22004-09-29 05:07:12 +0000256 // operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000257 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000258
Chris Lattner255d8912006-02-11 09:31:47 +0000259 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
260 uint64_t &KnownZero, uint64_t &KnownOne,
261 unsigned Depth = 0);
Chris Lattner4e998b22004-09-29 05:07:12 +0000262
Chris Lattner867b99f2006-10-05 06:55:50 +0000263 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
264 uint64_t &UndefElts, unsigned Depth = 0);
265
Chris Lattner4e998b22004-09-29 05:07:12 +0000266 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
267 // PHI node as operand #0, see if we can fold the instruction into the PHI
268 // (which is only possible if all operands to the PHI are constants).
269 Instruction *FoldOpIntoPhi(Instruction &I);
270
Chris Lattnerbac32862004-11-14 19:13:23 +0000271 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
272 // operator and they all are only used by the PHI, PHI together their
273 // inputs, and do the operation once, to the result of the PHI.
274 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
275
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000276 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
277 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000278
279 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
280 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000281 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
282 bool Inside, Instruction &IB);
Chris Lattnerb3f83972005-10-24 06:03:58 +0000283 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000284 Instruction *MatchBSwap(BinaryOperator &I);
285
Chris Lattner70074e02006-05-13 02:06:03 +0000286 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000287 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000288
Chris Lattner7f8897f2006-08-27 22:42:52 +0000289 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000290}
291
Chris Lattner4f98c562003-03-10 21:43:22 +0000292// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000293// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000294static unsigned getComplexity(Value *V) {
295 if (isa<Instruction>(V)) {
296 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000297 return 3;
298 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000299 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000300 if (isa<Argument>(V)) return 3;
301 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000302}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000303
Chris Lattnerc8802d22003-03-11 00:12:48 +0000304// isOnlyUse - Return true if this instruction will be deleted if we stop using
305// it.
306static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000307 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000308}
309
Chris Lattner4cb170c2004-02-23 06:38:22 +0000310// getPromotedType - Return the specified type promoted as it would be to pass
311// though a va_arg area...
312static const Type *getPromotedType(const Type *Ty) {
Chris Lattner5dd04022004-06-17 18:16:02 +0000313 switch (Ty->getTypeID()) {
Chris Lattner4cb170c2004-02-23 06:38:22 +0000314 case Type::SByteTyID:
315 case Type::ShortTyID: return Type::IntTy;
316 case Type::UByteTyID:
317 case Type::UShortTyID: return Type::UIntTy;
318 case Type::FloatTyID: return Type::DoubleTy;
319 default: return Ty;
320 }
321}
322
Chris Lattnereed48272005-09-13 00:40:14 +0000323/// isCast - If the specified operand is a CastInst or a constant expr cast,
324/// return the operand value, otherwise return null.
325static Value *isCast(Value *V) {
326 if (CastInst *I = dyn_cast<CastInst>(V))
327 return I->getOperand(0);
328 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
329 if (CE->getOpcode() == Instruction::Cast)
330 return CE->getOperand(0);
331 return 0;
332}
333
Chris Lattner33a61132006-05-06 09:00:16 +0000334enum CastType {
335 Noop = 0,
336 Truncate = 1,
337 Signext = 2,
338 Zeroext = 3
339};
340
341/// getCastType - In the future, we will split the cast instruction into these
342/// various types. Until then, we have to do the analysis here.
343static CastType getCastType(const Type *Src, const Type *Dest) {
344 assert(Src->isIntegral() && Dest->isIntegral() &&
345 "Only works on integral types!");
346 unsigned SrcSize = Src->getPrimitiveSizeInBits();
347 unsigned DestSize = Dest->getPrimitiveSizeInBits();
348
349 if (SrcSize == DestSize) return Noop;
350 if (SrcSize > DestSize) return Truncate;
351 if (Src->isSigned()) return Signext;
352 return Zeroext;
353}
354
355
356// isEliminableCastOfCast - Return true if it is valid to eliminate the CI
357// instruction.
358//
359static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
360 const Type *DstTy, TargetData *TD) {
361
362 // It is legal to eliminate the instruction if casting A->B->A if the sizes
363 // are identical and the bits don't get reinterpreted (for example
364 // int->float->int would not be allowed).
365 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
366 return true;
367
368 // If we are casting between pointer and integer types, treat pointers as
369 // integers of the appropriate size for the code below.
370 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
371 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
372 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
373
374 // Allow free casting and conversion of sizes as long as the sign doesn't
375 // change...
376 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
377 CastType FirstCast = getCastType(SrcTy, MidTy);
378 CastType SecondCast = getCastType(MidTy, DstTy);
379
380 // Capture the effect of these two casts. If the result is a legal cast,
381 // the CastType is stored here, otherwise a special code is used.
382 static const unsigned CastResult[] = {
383 // First cast is noop
384 0, 1, 2, 3,
385 // First cast is a truncate
386 1, 1, 4, 4, // trunc->extend is not safe to eliminate
387 // First cast is a sign ext
388 2, 5, 2, 4, // signext->zeroext never ok
389 // First cast is a zero ext
390 3, 5, 3, 3,
391 };
392
393 unsigned Result = CastResult[FirstCast*4+SecondCast];
394 switch (Result) {
395 default: assert(0 && "Illegal table value!");
396 case 0:
397 case 1:
398 case 2:
399 case 3:
400 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
401 // truncates, we could eliminate more casts.
402 return (unsigned)getCastType(SrcTy, DstTy) == Result;
403 case 4:
404 return false; // Not possible to eliminate this here.
405 case 5:
406 // Sign or zero extend followed by truncate is always ok if the result
407 // is a truncate or noop.
408 CastType ResultCast = getCastType(SrcTy, DstTy);
409 if (ResultCast == Noop || ResultCast == Truncate)
410 return true;
411 // Otherwise we are still growing the value, we are only safe if the
412 // result will match the sign/zeroextendness of the result.
413 return ResultCast == FirstCast;
414 }
415 }
416
417 // If this is a cast from 'float -> double -> integer', cast from
418 // 'float -> integer' directly, as the value isn't changed by the
419 // float->double conversion.
420 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
421 DstTy->isIntegral() &&
422 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
423 return true;
424
425 // Packed type conversions don't modify bits.
426 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
427 return true;
428
429 return false;
430}
431
432/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
433/// in any code being generated. It does not require codegen if V is simple
434/// enough or if the cast can be folded into other casts.
435static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
436 if (V->getType() == Ty || isa<Constant>(V)) return false;
437
438 // If this is a noop cast, it isn't real codegen.
439 if (V->getType()->isLosslesslyConvertibleTo(Ty))
440 return false;
441
Chris Lattner01575b72006-05-25 23:24:33 +0000442 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000443 if (const CastInst *CI = dyn_cast<CastInst>(V))
444 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
445 TD))
446 return false;
447 return true;
448}
449
450/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
451/// InsertBefore instruction. This is specialized a bit to avoid inserting
452/// casts that are known to not do anything...
453///
454Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
455 Instruction *InsertBefore) {
456 if (V->getType() == DestTy) return V;
457 if (Constant *C = dyn_cast<Constant>(V))
458 return ConstantExpr::getCast(C, DestTy);
459
460 CastInst *CI = new CastInst(V, DestTy, V->getName());
461 InsertNewInstBefore(CI, *InsertBefore);
462 return CI;
463}
464
Chris Lattner4f98c562003-03-10 21:43:22 +0000465// SimplifyCommutative - This performs a few simplifications for commutative
466// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000467//
Chris Lattner4f98c562003-03-10 21:43:22 +0000468// 1. Order operands such that they are listed from right (least complex) to
469// left (most complex). This puts constants before unary operators before
470// binary operators.
471//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000472// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
473// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000474//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000475bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000476 bool Changed = false;
477 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
478 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000479
Chris Lattner4f98c562003-03-10 21:43:22 +0000480 if (!I.isAssociative()) return Changed;
481 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000482 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
483 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
484 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000485 Constant *Folded = ConstantExpr::get(I.getOpcode(),
486 cast<Constant>(I.getOperand(1)),
487 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000488 I.setOperand(0, Op->getOperand(0));
489 I.setOperand(1, Folded);
490 return true;
491 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
492 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
493 isOnlyUse(Op) && isOnlyUse(Op1)) {
494 Constant *C1 = cast<Constant>(Op->getOperand(1));
495 Constant *C2 = cast<Constant>(Op1->getOperand(1));
496
497 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000498 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000499 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
500 Op1->getOperand(0),
501 Op1->getName(), &I);
502 WorkList.push_back(New);
503 I.setOperand(0, New);
504 I.setOperand(1, Folded);
505 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000506 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000507 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000508 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000509}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000510
Chris Lattner8d969642003-03-10 23:06:50 +0000511// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
512// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000513//
Chris Lattner8d969642003-03-10 23:06:50 +0000514static inline Value *dyn_castNegVal(Value *V) {
515 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000516 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000517
Chris Lattner0ce85802004-12-14 20:08:06 +0000518 // Constants can be considered to be negated values if they can be folded.
519 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
520 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000521 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000522}
523
Chris Lattner8d969642003-03-10 23:06:50 +0000524static inline Value *dyn_castNotVal(Value *V) {
525 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000526 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000527
528 // Constants can be considered to be not'ed values...
Chris Lattner3f2ec392003-04-30 22:34:06 +0000529 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
Chris Lattner448c3232004-06-10 02:12:35 +0000530 return ConstantExpr::getNot(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000531 return 0;
532}
533
Chris Lattnerc8802d22003-03-11 00:12:48 +0000534// dyn_castFoldableMul - If this value is a multiply that can be folded into
535// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000536// non-constant operand of the multiply, and set CST to point to the multiplier.
537// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000538//
Chris Lattner50af16a2004-11-13 19:50:12 +0000539static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000540 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000541 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000542 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000543 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000544 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000545 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000546 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000547 // The multiplier is really 1 << CST.
548 Constant *One = ConstantInt::get(V->getType(), 1);
549 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
550 return I->getOperand(0);
551 }
552 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000553 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000554}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000555
Chris Lattner574da9b2005-01-13 20:14:25 +0000556/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
557/// expression, return it.
558static User *dyn_castGetElementPtr(Value *V) {
559 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
560 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
561 if (CE->getOpcode() == Instruction::GetElementPtr)
562 return cast<User>(V);
563 return false;
564}
565
Chris Lattner955f3312004-09-28 21:48:02 +0000566// AddOne, SubOne - Add or subtract a constant one from an integer constant...
Chris Lattnera96879a2004-09-29 17:40:11 +0000567static ConstantInt *AddOne(ConstantInt *C) {
568 return cast<ConstantInt>(ConstantExpr::getAdd(C,
569 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000570}
Chris Lattnera96879a2004-09-29 17:40:11 +0000571static ConstantInt *SubOne(ConstantInt *C) {
572 return cast<ConstantInt>(ConstantExpr::getSub(C,
573 ConstantInt::get(C->getType(), 1)));
Chris Lattner955f3312004-09-28 21:48:02 +0000574}
575
Chris Lattner255d8912006-02-11 09:31:47 +0000576/// GetConstantInType - Return a ConstantInt with the specified type and value.
577///
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000578static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000579 if (Ty->isUnsigned())
580 return ConstantInt::get(Ty, Val);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000581 else if (Ty->getTypeID() == Type::BoolTyID)
582 return ConstantBool::get(Val);
Chris Lattner255d8912006-02-11 09:31:47 +0000583 int64_t SVal = Val;
584 SVal <<= 64-Ty->getPrimitiveSizeInBits();
585 SVal >>= 64-Ty->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +0000586 return ConstantInt::get(Ty, SVal);
Chris Lattner255d8912006-02-11 09:31:47 +0000587}
588
589
Chris Lattner68d5ff22006-02-09 07:38:58 +0000590/// ComputeMaskedBits - Determine which of the bits specified in Mask are
591/// known to be either zero or one and return them in the KnownZero/KnownOne
592/// bitsets. This code only analyzes bits in Mask, in order to short-circuit
593/// processing.
594static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
595 uint64_t &KnownOne, unsigned Depth = 0) {
Chris Lattner5931c542005-09-24 23:43:33 +0000596 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
597 // we cannot optimize based on the assumption that it is zero without changing
Chris Lattner3bedbd92006-02-07 07:27:52 +0000598 // it to be an explicit zero. If we don't change it to zero, other code could
Chris Lattner5931c542005-09-24 23:43:33 +0000599 // optimized based on the contradictory assumption that it is non-zero.
600 // Because instcombine aggressively folds operations with undef args anyway,
601 // this won't lose us code quality.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000602 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
603 // We know all of the bits for a constant!
Chris Lattner255d8912006-02-11 09:31:47 +0000604 KnownOne = CI->getZExtValue() & Mask;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000605 KnownZero = ~KnownOne & Mask;
606 return;
607 }
608
609 KnownZero = KnownOne = 0; // Don't know anything.
Chris Lattner74c51a02006-02-07 08:05:22 +0000610 if (Depth == 6 || Mask == 0)
Chris Lattner68d5ff22006-02-09 07:38:58 +0000611 return; // Limit search depth.
612
613 uint64_t KnownZero2, KnownOne2;
Chris Lattner255d8912006-02-11 09:31:47 +0000614 Instruction *I = dyn_cast<Instruction>(V);
615 if (!I) return;
616
Chris Lattnere3158302006-05-04 17:33:35 +0000617 Mask &= V->getType()->getIntegralTypeMask();
618
Chris Lattner255d8912006-02-11 09:31:47 +0000619 switch (I->getOpcode()) {
620 case Instruction::And:
621 // If either the LHS or the RHS are Zero, the result is zero.
622 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
623 Mask &= ~KnownZero;
624 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
625 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
626 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
627
628 // Output known-1 bits are only known if set in both the LHS & RHS.
629 KnownOne &= KnownOne2;
630 // Output known-0 are known to be clear if zero in either the LHS | RHS.
631 KnownZero |= KnownZero2;
632 return;
633 case Instruction::Or:
634 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
635 Mask &= ~KnownOne;
636 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
637 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
638 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
639
640 // Output known-0 bits are only known if clear in both the LHS & RHS.
641 KnownZero &= KnownZero2;
642 // Output known-1 are known to be set if set in either the LHS | RHS.
643 KnownOne |= KnownOne2;
644 return;
645 case Instruction::Xor: {
646 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
647 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
648 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
649 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
650
651 // Output known-0 bits are known if clear or set in both the LHS & RHS.
652 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
653 // Output known-1 are known to be set if set in only one of the LHS, RHS.
654 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
655 KnownZero = KnownZeroOut;
656 return;
657 }
658 case Instruction::Select:
659 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
660 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
661 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
662 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
663
664 // Only known if known in both the LHS and RHS.
665 KnownOne &= KnownOne2;
666 KnownZero &= KnownZero2;
667 return;
668 case Instruction::Cast: {
669 const Type *SrcTy = I->getOperand(0)->getType();
670 if (!SrcTy->isIntegral()) return;
671
672 // If this is an integer truncate or noop, just look in the input.
673 if (SrcTy->getPrimitiveSizeInBits() >=
674 I->getType()->getPrimitiveSizeInBits()) {
675 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
Chris Lattner68d5ff22006-02-09 07:38:58 +0000676 return;
677 }
Chris Lattner68d5ff22006-02-09 07:38:58 +0000678
Chris Lattner255d8912006-02-11 09:31:47 +0000679 // Sign or Zero extension. Compute the bits in the result that are not
680 // present in the input.
681 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
682 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
Chris Lattner60de63d2005-10-09 06:36:35 +0000683
Chris Lattner255d8912006-02-11 09:31:47 +0000684 // Handle zero extension.
685 if (!SrcTy->isSigned()) {
686 Mask &= SrcTy->getIntegralTypeMask();
687 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
688 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
689 // The top bits are known to be zero.
690 KnownZero |= NewBits;
691 } else {
692 // Sign extension.
693 Mask &= SrcTy->getIntegralTypeMask();
694 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
695 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattner74c51a02006-02-07 08:05:22 +0000696
Chris Lattner255d8912006-02-11 09:31:47 +0000697 // If the sign bit of the input is known set or clear, then we know the
698 // top bits of the result.
699 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
700 if (KnownZero & InSignBit) { // Input sign bit known zero
Chris Lattner68d5ff22006-02-09 07:38:58 +0000701 KnownZero |= NewBits;
Chris Lattner255d8912006-02-11 09:31:47 +0000702 KnownOne &= ~NewBits;
703 } else if (KnownOne & InSignBit) { // Input sign bit known set
704 KnownOne |= NewBits;
705 KnownZero &= ~NewBits;
706 } else { // Input sign bit unknown
707 KnownZero &= ~NewBits;
708 KnownOne &= ~NewBits;
709 }
710 }
711 return;
712 }
713 case Instruction::Shl:
714 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000715 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
716 uint64_t ShiftAmt = SA->getZExtValue();
717 Mask >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000718 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
719 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000720 KnownZero <<= ShiftAmt;
721 KnownOne <<= ShiftAmt;
722 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +0000723 return;
724 }
725 break;
726 case Instruction::Shr:
727 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencerb83eb642006-10-20 07:07:24 +0000728 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Chris Lattner255d8912006-02-11 09:31:47 +0000729 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +0000730 uint64_t ShiftAmt = SA->getZExtValue();
731 uint64_t HighBits = (1ULL << ShiftAmt)-1;
732 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000733
734 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Reid Spencerb83eb642006-10-20 07:07:24 +0000735 Mask <<= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000736 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
737 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000738 KnownZero >>= ShiftAmt;
739 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000740 KnownZero |= HighBits; // high bits known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +0000741 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000742 Mask <<= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000743 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
744 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +0000745 KnownZero >>= ShiftAmt;
746 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +0000747
748 // Handle the sign bits.
749 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencerb83eb642006-10-20 07:07:24 +0000750 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +0000751
752 if (KnownZero & SignBit) { // New bits are known zero.
753 KnownZero |= HighBits;
754 } else if (KnownOne & SignBit) { // New bits are known one.
755 KnownOne |= HighBits;
Chris Lattner68d5ff22006-02-09 07:38:58 +0000756 }
757 }
758 return;
Chris Lattner60de63d2005-10-09 06:36:35 +0000759 }
Chris Lattner255d8912006-02-11 09:31:47 +0000760 break;
Chris Lattner5931c542005-09-24 23:43:33 +0000761 }
Chris Lattner74c51a02006-02-07 08:05:22 +0000762}
763
764/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
765/// this predicate to simplify operations downstream. Mask is known to be zero
766/// for bits that V cannot have.
767static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
Chris Lattner68d5ff22006-02-09 07:38:58 +0000768 uint64_t KnownZero, KnownOne;
769 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
770 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
771 return (KnownZero & Mask) == Mask;
Chris Lattner5931c542005-09-24 23:43:33 +0000772}
773
Chris Lattner255d8912006-02-11 09:31:47 +0000774/// ShrinkDemandedConstant - Check to see if the specified operand of the
775/// specified instruction is a constant integer. If so, check to see if there
776/// are any bits set in the constant that are not demanded. If so, shrink the
777/// constant and return true.
778static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
779 uint64_t Demanded) {
780 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
781 if (!OpC) return false;
782
783 // If there are no bits set that aren't demanded, nothing to do.
784 if ((~Demanded & OpC->getZExtValue()) == 0)
785 return false;
786
787 // This is producing any bits that are not needed, shrink the RHS.
788 uint64_t Val = Demanded & OpC->getZExtValue();
789 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
790 return true;
791}
792
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000793// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
794// set of known zero and one bits, compute the maximum and minimum values that
795// could have the specified known zero and known one bits, returning them in
796// min/max.
797static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
798 uint64_t KnownZero,
799 uint64_t KnownOne,
800 int64_t &Min, int64_t &Max) {
801 uint64_t TypeBits = Ty->getIntegralTypeMask();
802 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
803
804 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
805
806 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
807 // bit if it is unknown.
808 Min = KnownOne;
809 Max = KnownOne|UnknownBits;
810
811 if (SignBit & UnknownBits) { // Sign bit is unknown
812 Min |= SignBit;
813 Max &= ~SignBit;
814 }
815
816 // Sign extend the min/max values.
817 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
818 Min = (Min << ShAmt) >> ShAmt;
819 Max = (Max << ShAmt) >> ShAmt;
820}
821
822// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
823// a set of known zero and one bits, compute the maximum and minimum values that
824// could have the specified known zero and known one bits, returning them in
825// min/max.
826static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
827 uint64_t KnownZero,
828 uint64_t KnownOne,
829 uint64_t &Min,
830 uint64_t &Max) {
831 uint64_t TypeBits = Ty->getIntegralTypeMask();
832 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
833
834 // The minimum value is when the unknown bits are all zeros.
835 Min = KnownOne;
836 // The maximum value is when the unknown bits are all ones.
837 Max = KnownOne|UnknownBits;
838}
Chris Lattner255d8912006-02-11 09:31:47 +0000839
840
841/// SimplifyDemandedBits - Look at V. At this point, we know that only the
842/// DemandedMask bits of the result of V are ever used downstream. If we can
843/// use this information to simplify V, do so and return true. Otherwise,
844/// analyze the expression and return a mask of KnownOne and KnownZero bits for
845/// the expression (used to simplify the caller). The KnownZero/One bits may
846/// only be accurate for those bits in the DemandedMask.
847bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
848 uint64_t &KnownZero, uint64_t &KnownOne,
Chris Lattner6dce1a72006-02-07 06:56:34 +0000849 unsigned Depth) {
Chris Lattner255d8912006-02-11 09:31:47 +0000850 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
851 // We know all of the bits for a constant!
852 KnownOne = CI->getZExtValue() & DemandedMask;
853 KnownZero = ~KnownOne & DemandedMask;
854 return false;
855 }
856
857 KnownZero = KnownOne = 0;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000858 if (!V->hasOneUse()) { // Other users may use these bits.
Chris Lattner255d8912006-02-11 09:31:47 +0000859 if (Depth != 0) { // Not at the root.
860 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
861 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000862 return false;
Chris Lattner255d8912006-02-11 09:31:47 +0000863 }
Chris Lattner6dce1a72006-02-07 06:56:34 +0000864 // If this is the root being simplified, allow it to have multiple uses,
Chris Lattner255d8912006-02-11 09:31:47 +0000865 // just set the DemandedMask to all bits.
866 DemandedMask = V->getType()->getIntegralTypeMask();
867 } else if (DemandedMask == 0) { // Not demanding any bits from V.
Chris Lattner74c51a02006-02-07 08:05:22 +0000868 if (V != UndefValue::get(V->getType()))
869 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
870 return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000871 } else if (Depth == 6) { // Limit search depth.
872 return false;
873 }
874
875 Instruction *I = dyn_cast<Instruction>(V);
876 if (!I) return false; // Only analyze instructions.
877
Chris Lattnere3158302006-05-04 17:33:35 +0000878 DemandedMask &= V->getType()->getIntegralTypeMask();
879
Chris Lattner255d8912006-02-11 09:31:47 +0000880 uint64_t KnownZero2, KnownOne2;
Chris Lattner6dce1a72006-02-07 06:56:34 +0000881 switch (I->getOpcode()) {
882 default: break;
883 case Instruction::And:
Chris Lattner255d8912006-02-11 09:31:47 +0000884 // If either the LHS or the RHS are Zero, the result is zero.
885 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
886 KnownZero, KnownOne, Depth+1))
887 return true;
888 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
889
890 // If something is known zero on the RHS, the bits aren't demanded on the
891 // LHS.
892 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
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 one on one side, return the other.
898 // These bits cannot contribute to the result of the 'and'.
899 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
900 return UpdateValueUsesWith(I, I->getOperand(0));
901 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
902 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000903
904 // If all of the demanded bits in the inputs are known zeros, return zero.
905 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
906 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
907
Chris Lattner255d8912006-02-11 09:31:47 +0000908 // If the RHS is a constant, see if we can simplify it.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000909 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
Chris Lattner255d8912006-02-11 09:31:47 +0000910 return UpdateValueUsesWith(I, I);
911
912 // Output known-1 bits are only known if set in both the LHS & RHS.
913 KnownOne &= KnownOne2;
914 // Output known-0 are known to be clear if zero in either the LHS | RHS.
915 KnownZero |= KnownZero2;
916 break;
917 case Instruction::Or:
918 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
919 KnownZero, KnownOne, Depth+1))
920 return true;
921 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
922 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
923 KnownZero2, KnownOne2, Depth+1))
924 return true;
925 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
926
927 // If all of the demanded bits are known zero on one side, return the other.
928 // These bits cannot contribute to the result of the 'or'.
Jeff Cohenbce48052006-02-18 03:20:33 +0000929 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
Chris Lattner255d8912006-02-11 09:31:47 +0000930 return UpdateValueUsesWith(I, I->getOperand(0));
Jeff Cohenbce48052006-02-18 03:20:33 +0000931 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
Chris Lattner255d8912006-02-11 09:31:47 +0000932 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000933
934 // If all of the potentially set bits on one side are known to be set on
935 // the other side, just use the 'other' side.
936 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
937 (DemandedMask & (~KnownZero)))
938 return UpdateValueUsesWith(I, I->getOperand(0));
Nate Begeman368e18d2006-02-16 21:11:51 +0000939 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
940 (DemandedMask & (~KnownZero2)))
941 return UpdateValueUsesWith(I, I->getOperand(1));
Chris Lattner255d8912006-02-11 09:31:47 +0000942
943 // If the RHS is a constant, see if we can simplify it.
944 if (ShrinkDemandedConstant(I, 1, DemandedMask))
945 return UpdateValueUsesWith(I, I);
946
947 // Output known-0 bits are only known if clear in both the LHS & RHS.
948 KnownZero &= KnownZero2;
949 // Output known-1 are known to be set if set in either the LHS | RHS.
950 KnownOne |= KnownOne2;
951 break;
952 case Instruction::Xor: {
953 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
954 KnownZero, KnownOne, Depth+1))
955 return true;
956 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
957 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
958 KnownZero2, KnownOne2, Depth+1))
959 return true;
960 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
961
962 // If all of the demanded bits are known zero on one side, return the other.
963 // These bits cannot contribute to the result of the 'xor'.
964 if ((DemandedMask & KnownZero) == DemandedMask)
965 return UpdateValueUsesWith(I, I->getOperand(0));
966 if ((DemandedMask & KnownZero2) == DemandedMask)
967 return UpdateValueUsesWith(I, I->getOperand(1));
968
969 // Output known-0 bits are known if clear or set in both the LHS & RHS.
970 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
971 // Output known-1 are known to be set if set in only one of the LHS, RHS.
972 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
973
974 // If all of the unknown bits are known to be zero on one side or the other
975 // (but not both) turn this into an *inclusive* or.
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000976 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner255d8912006-02-11 09:31:47 +0000977 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
978 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
979 Instruction *Or =
980 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
981 I->getName());
982 InsertNewInstBefore(Or, *I);
983 return UpdateValueUsesWith(I, Or);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000984 }
985 }
Chris Lattner255d8912006-02-11 09:31:47 +0000986
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000987 // If all of the demanded bits on one side are known, and all of the set
988 // bits on that side are also known to be set on the other side, turn this
989 // into an AND, as we know the bits will be cleared.
990 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
991 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
992 if ((KnownOne & KnownOne2) == KnownOne) {
993 Constant *AndC = GetConstantInType(I->getType(),
994 ~KnownOne & DemandedMask);
995 Instruction *And =
996 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
997 InsertNewInstBefore(And, *I);
998 return UpdateValueUsesWith(I, And);
999 }
1000 }
1001
Chris Lattner255d8912006-02-11 09:31:47 +00001002 // If the RHS is a constant, see if we can simplify it.
1003 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1004 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1005 return UpdateValueUsesWith(I, I);
1006
1007 KnownZero = KnownZeroOut;
1008 KnownOne = KnownOneOut;
1009 break;
1010 }
1011 case Instruction::Select:
1012 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1013 KnownZero, KnownOne, Depth+1))
1014 return true;
1015 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1016 KnownZero2, KnownOne2, Depth+1))
1017 return true;
1018 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1019 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1020
1021 // If the operands are constants, see if we can simplify them.
1022 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1023 return UpdateValueUsesWith(I, I);
1024 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1025 return UpdateValueUsesWith(I, I);
1026
1027 // Only known if known in both the LHS and RHS.
1028 KnownOne &= KnownOne2;
1029 KnownZero &= KnownZero2;
1030 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001031 case Instruction::Cast: {
1032 const Type *SrcTy = I->getOperand(0)->getType();
Chris Lattner255d8912006-02-11 09:31:47 +00001033 if (!SrcTy->isIntegral()) return false;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001034
Chris Lattner255d8912006-02-11 09:31:47 +00001035 // If this is an integer truncate or noop, just look in the input.
1036 if (SrcTy->getPrimitiveSizeInBits() >=
1037 I->getType()->getPrimitiveSizeInBits()) {
Chris Lattnerf6bd07c2006-09-16 03:14:10 +00001038 // Cast to bool is a comparison against 0, which demands all bits. We
1039 // can't propagate anything useful up.
1040 if (I->getType() == Type::BoolTy)
1041 break;
1042
Chris Lattner255d8912006-02-11 09:31:47 +00001043 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1044 KnownZero, KnownOne, Depth+1))
1045 return true;
1046 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1047 break;
1048 }
1049
1050 // Sign or Zero extension. Compute the bits in the result that are not
1051 // present in the input.
1052 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1053 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1054
1055 // Handle zero extension.
1056 if (!SrcTy->isSigned()) {
1057 DemandedMask &= SrcTy->getIntegralTypeMask();
1058 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1059 KnownZero, KnownOne, Depth+1))
1060 return true;
1061 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1062 // The top bits are known to be zero.
1063 KnownZero |= NewBits;
1064 } else {
1065 // Sign extension.
Chris Lattnerf345fe42006-02-13 22:41:07 +00001066 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1067 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1068
1069 // If any of the sign extended bits are demanded, we know that the sign
1070 // bit is demanded.
1071 if (NewBits & DemandedMask)
1072 InputDemandedBits |= InSignBit;
1073
1074 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
Chris Lattner255d8912006-02-11 09:31:47 +00001075 KnownZero, KnownOne, Depth+1))
1076 return true;
1077 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1078
1079 // If the sign bit of the input is known set or clear, then we know the
1080 // top bits of the result.
Chris Lattner6dce1a72006-02-07 06:56:34 +00001081
Chris Lattner255d8912006-02-11 09:31:47 +00001082 // If the input sign bit is known zero, or if the NewBits are not demanded
1083 // convert this into a zero extension.
1084 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
Chris Lattner6dce1a72006-02-07 06:56:34 +00001085 // Convert to unsigned first.
Chris Lattnerd89d8882006-02-07 19:07:40 +00001086 Instruction *NewVal;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001087 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
Chris Lattnerd89d8882006-02-07 19:07:40 +00001088 I->getOperand(0)->getName());
1089 InsertNewInstBefore(NewVal, *I);
Chris Lattner255d8912006-02-11 09:31:47 +00001090 // Then cast that to the destination type.
Chris Lattnerd89d8882006-02-07 19:07:40 +00001091 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1092 InsertNewInstBefore(NewVal, *I);
Chris Lattner6dce1a72006-02-07 06:56:34 +00001093 return UpdateValueUsesWith(I, NewVal);
Chris Lattner255d8912006-02-11 09:31:47 +00001094 } else if (KnownOne & InSignBit) { // Input sign bit known set
1095 KnownOne |= NewBits;
1096 KnownZero &= ~NewBits;
1097 } else { // Input sign bit unknown
1098 KnownZero &= ~NewBits;
1099 KnownOne &= ~NewBits;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001100 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001101 }
Chris Lattner255d8912006-02-11 09:31:47 +00001102 break;
Chris Lattner6dce1a72006-02-07 06:56:34 +00001103 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001104 case Instruction::Shl:
Reid Spencerb83eb642006-10-20 07:07:24 +00001105 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1106 uint64_t ShiftAmt = SA->getZExtValue();
1107 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
Chris Lattner255d8912006-02-11 09:31:47 +00001108 KnownZero, KnownOne, Depth+1))
1109 return true;
1110 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Reid Spencerb83eb642006-10-20 07:07:24 +00001111 KnownZero <<= ShiftAmt;
1112 KnownOne <<= ShiftAmt;
1113 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
Chris Lattner255d8912006-02-11 09:31:47 +00001114 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001115 break;
1116 case Instruction::Shr:
Chris Lattnerb7363792006-09-18 04:31:40 +00001117 // If this is an arithmetic shift right and only the low-bit is set, we can
1118 // always convert this into a logical shr, even if the shift amount is
1119 // variable. The low bit of the shift cannot be an input sign bit unless
1120 // the shift amount is >= the size of the datatype, which is undefined.
1121 if (DemandedMask == 1 && I->getType()->isSigned()) {
1122 // Convert the input to unsigned.
1123 Instruction *NewVal = new CastInst(I->getOperand(0),
1124 I->getType()->getUnsignedVersion(),
1125 I->getOperand(0)->getName());
1126 InsertNewInstBefore(NewVal, *I);
1127 // Perform the unsigned shift right.
1128 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1129 I->getName());
1130 InsertNewInstBefore(NewVal, *I);
1131 // Then cast that to the destination type.
1132 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1133 InsertNewInstBefore(NewVal, *I);
1134 return UpdateValueUsesWith(I, NewVal);
1135 }
1136
Reid Spencerb83eb642006-10-20 07:07:24 +00001137 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1138 unsigned ShiftAmt = SA->getZExtValue();
Chris Lattner255d8912006-02-11 09:31:47 +00001139
1140 // Compute the new bits that are at the top now.
Reid Spencerb83eb642006-10-20 07:07:24 +00001141 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1142 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
Chris Lattnerc15637b2006-02-13 06:09:08 +00001143 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
Chris Lattner255d8912006-02-11 09:31:47 +00001144 if (I->getType()->isUnsigned()) { // Unsigned shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +00001145 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00001146 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +00001147 KnownZero, KnownOne, Depth+1))
1148 return true;
1149 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +00001150 KnownZero &= TypeMask;
1151 KnownOne &= TypeMask;
Reid Spencerb83eb642006-10-20 07:07:24 +00001152 KnownZero >>= ShiftAmt;
1153 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +00001154 KnownZero |= HighBits; // high bits known zero.
1155 } else { // Signed shift right.
Chris Lattnerc15637b2006-02-13 06:09:08 +00001156 if (SimplifyDemandedBits(I->getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00001157 (DemandedMask << ShiftAmt) & TypeMask,
Chris Lattner255d8912006-02-11 09:31:47 +00001158 KnownZero, KnownOne, Depth+1))
1159 return true;
1160 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Chris Lattnerc15637b2006-02-13 06:09:08 +00001161 KnownZero &= TypeMask;
1162 KnownOne &= TypeMask;
Reid Spencerb83eb642006-10-20 07:07:24 +00001163 KnownZero >>= ShiftAmt;
1164 KnownOne >>= ShiftAmt;
Chris Lattner255d8912006-02-11 09:31:47 +00001165
1166 // Handle the sign bits.
1167 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
Reid Spencerb83eb642006-10-20 07:07:24 +00001168 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
Chris Lattner255d8912006-02-11 09:31:47 +00001169
1170 // If the input sign bit is known to be zero, or if none of the top bits
1171 // are demanded, turn this into an unsigned shift right.
1172 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1173 // Convert the input to unsigned.
1174 Instruction *NewVal;
1175 NewVal = new CastInst(I->getOperand(0),
1176 I->getType()->getUnsignedVersion(),
1177 I->getOperand(0)->getName());
1178 InsertNewInstBefore(NewVal, *I);
1179 // Perform the unsigned shift right.
1180 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1181 InsertNewInstBefore(NewVal, *I);
1182 // Then cast that to the destination type.
1183 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1184 InsertNewInstBefore(NewVal, *I);
1185 return UpdateValueUsesWith(I, NewVal);
1186 } else if (KnownOne & SignBit) { // New bits are known one.
1187 KnownOne |= HighBits;
1188 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001189 }
Chris Lattner255d8912006-02-11 09:31:47 +00001190 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00001191 break;
1192 }
Chris Lattner255d8912006-02-11 09:31:47 +00001193
1194 // If the client is only demanding bits that we know, return the known
1195 // constant.
1196 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1197 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
Chris Lattner6dce1a72006-02-07 06:56:34 +00001198 return false;
1199}
1200
Chris Lattner867b99f2006-10-05 06:55:50 +00001201
1202/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1203/// 64 or fewer elements. DemandedElts contains the set of elements that are
1204/// actually used by the caller. This method analyzes which elements of the
1205/// operand are undef and returns that information in UndefElts.
1206///
1207/// If the information about demanded elements can be used to simplify the
1208/// operation, the operation is simplified, then the resultant value is
1209/// returned. This returns null if no change was made.
1210Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1211 uint64_t &UndefElts,
1212 unsigned Depth) {
1213 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1214 assert(VWidth <= 64 && "Vector too wide to analyze!");
1215 uint64_t EltMask = ~0ULL >> (64-VWidth);
1216 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1217 "Invalid DemandedElts!");
1218
1219 if (isa<UndefValue>(V)) {
1220 // If the entire vector is undefined, just return this info.
1221 UndefElts = EltMask;
1222 return 0;
1223 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1224 UndefElts = EltMask;
1225 return UndefValue::get(V->getType());
1226 }
1227
1228 UndefElts = 0;
1229 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1230 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1231 Constant *Undef = UndefValue::get(EltTy);
1232
1233 std::vector<Constant*> Elts;
1234 for (unsigned i = 0; i != VWidth; ++i)
1235 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1236 Elts.push_back(Undef);
1237 UndefElts |= (1ULL << i);
1238 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1239 Elts.push_back(Undef);
1240 UndefElts |= (1ULL << i);
1241 } else { // Otherwise, defined.
1242 Elts.push_back(CP->getOperand(i));
1243 }
1244
1245 // If we changed the constant, return it.
1246 Constant *NewCP = ConstantPacked::get(Elts);
1247 return NewCP != CP ? NewCP : 0;
1248 } else if (isa<ConstantAggregateZero>(V)) {
1249 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1250 // set to undef.
1251 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1252 Constant *Zero = Constant::getNullValue(EltTy);
1253 Constant *Undef = UndefValue::get(EltTy);
1254 std::vector<Constant*> Elts;
1255 for (unsigned i = 0; i != VWidth; ++i)
1256 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1257 UndefElts = DemandedElts ^ EltMask;
1258 return ConstantPacked::get(Elts);
1259 }
1260
1261 if (!V->hasOneUse()) { // Other users may use these bits.
1262 if (Depth != 0) { // Not at the root.
1263 // TODO: Just compute the UndefElts information recursively.
1264 return false;
1265 }
1266 return false;
1267 } else if (Depth == 10) { // Limit search depth.
1268 return false;
1269 }
1270
1271 Instruction *I = dyn_cast<Instruction>(V);
1272 if (!I) return false; // Only analyze instructions.
1273
1274 bool MadeChange = false;
1275 uint64_t UndefElts2;
1276 Value *TmpV;
1277 switch (I->getOpcode()) {
1278 default: break;
1279
1280 case Instruction::InsertElement: {
1281 // If this is a variable index, we don't know which element it overwrites.
1282 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001283 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001284 if (Idx == 0) {
1285 // Note that we can't propagate undef elt info, because we don't know
1286 // which elt is getting updated.
1287 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1288 UndefElts2, Depth+1);
1289 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1290 break;
1291 }
1292
1293 // If this is inserting an element that isn't demanded, remove this
1294 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001295 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001296 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1297 return AddSoonDeadInstToWorklist(*I, 0);
1298
1299 // Otherwise, the element inserted overwrites whatever was there, so the
1300 // input demanded set is simpler than the output set.
1301 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1302 DemandedElts & ~(1ULL << IdxNo),
1303 UndefElts, Depth+1);
1304 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1305
1306 // The inserted element is defined.
1307 UndefElts |= 1ULL << IdxNo;
1308 break;
1309 }
1310
1311 case Instruction::And:
1312 case Instruction::Or:
1313 case Instruction::Xor:
1314 case Instruction::Add:
1315 case Instruction::Sub:
1316 case Instruction::Mul:
1317 // div/rem demand all inputs, because they don't want divide by zero.
1318 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1319 UndefElts, Depth+1);
1320 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1321 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1322 UndefElts2, Depth+1);
1323 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1324
1325 // Output elements are undefined if both are undefined. Consider things
1326 // like undef&0. The result is known zero, not undef.
1327 UndefElts &= UndefElts2;
1328 break;
1329
1330 case Instruction::Call: {
1331 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1332 if (!II) break;
1333 switch (II->getIntrinsicID()) {
1334 default: break;
1335
1336 // Binary vector operations that work column-wise. A dest element is a
1337 // function of the corresponding input elements from the two inputs.
1338 case Intrinsic::x86_sse_sub_ss:
1339 case Intrinsic::x86_sse_mul_ss:
1340 case Intrinsic::x86_sse_min_ss:
1341 case Intrinsic::x86_sse_max_ss:
1342 case Intrinsic::x86_sse2_sub_sd:
1343 case Intrinsic::x86_sse2_mul_sd:
1344 case Intrinsic::x86_sse2_min_sd:
1345 case Intrinsic::x86_sse2_max_sd:
1346 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1347 UndefElts, Depth+1);
1348 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1349 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1350 UndefElts2, Depth+1);
1351 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1352
1353 // If only the low elt is demanded and this is a scalarizable intrinsic,
1354 // scalarize it now.
1355 if (DemandedElts == 1) {
1356 switch (II->getIntrinsicID()) {
1357 default: break;
1358 case Intrinsic::x86_sse_sub_ss:
1359 case Intrinsic::x86_sse_mul_ss:
1360 case Intrinsic::x86_sse2_sub_sd:
1361 case Intrinsic::x86_sse2_mul_sd:
1362 // TODO: Lower MIN/MAX/ABS/etc
1363 Value *LHS = II->getOperand(1);
1364 Value *RHS = II->getOperand(2);
1365 // Extract the element as scalars.
1366 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1367 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1368
1369 switch (II->getIntrinsicID()) {
1370 default: assert(0 && "Case stmts out of sync!");
1371 case Intrinsic::x86_sse_sub_ss:
1372 case Intrinsic::x86_sse2_sub_sd:
1373 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1374 II->getName()), *II);
1375 break;
1376 case Intrinsic::x86_sse_mul_ss:
1377 case Intrinsic::x86_sse2_mul_sd:
1378 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1379 II->getName()), *II);
1380 break;
1381 }
1382
1383 Instruction *New =
1384 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1385 II->getName());
1386 InsertNewInstBefore(New, *II);
1387 AddSoonDeadInstToWorklist(*II, 0);
1388 return New;
1389 }
1390 }
1391
1392 // Output elements are undefined if both are undefined. Consider things
1393 // like undef&0. The result is known zero, not undef.
1394 UndefElts &= UndefElts2;
1395 break;
1396 }
1397 break;
1398 }
1399 }
1400 return MadeChange ? I : 0;
1401}
1402
Chris Lattner955f3312004-09-28 21:48:02 +00001403// isTrueWhenEqual - Return true if the specified setcondinst instruction is
1404// true when both operands are equal...
1405//
1406static bool isTrueWhenEqual(Instruction &I) {
1407 return I.getOpcode() == Instruction::SetEQ ||
1408 I.getOpcode() == Instruction::SetGE ||
1409 I.getOpcode() == Instruction::SetLE;
1410}
Chris Lattner564a7272003-08-13 19:01:45 +00001411
1412/// AssociativeOpt - Perform an optimization on an associative operator. This
1413/// function is designed to check a chain of associative operators for a
1414/// potential to apply a certain optimization. Since the optimization may be
1415/// applicable if the expression was reassociated, this checks the chain, then
1416/// reassociates the expression as necessary to expose the optimization
1417/// opportunity. This makes use of a special Functor, which must define
1418/// 'shouldApply' and 'apply' methods.
1419///
1420template<typename Functor>
1421Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1422 unsigned Opcode = Root.getOpcode();
1423 Value *LHS = Root.getOperand(0);
1424
1425 // Quick check, see if the immediate LHS matches...
1426 if (F.shouldApply(LHS))
1427 return F.apply(Root);
1428
1429 // Otherwise, if the LHS is not of the same opcode as the root, return.
1430 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001431 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001432 // Should we apply this transform to the RHS?
1433 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1434
1435 // If not to the RHS, check to see if we should apply to the LHS...
1436 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1437 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1438 ShouldApply = true;
1439 }
1440
1441 // If the functor wants to apply the optimization to the RHS of LHSI,
1442 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1443 if (ShouldApply) {
1444 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001445
Chris Lattner564a7272003-08-13 19:01:45 +00001446 // Now all of the instructions are in the current basic block, go ahead
1447 // and perform the reassociation.
1448 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1449
1450 // First move the selected RHS to the LHS of the root...
1451 Root.setOperand(0, LHSI->getOperand(1));
1452
1453 // Make what used to be the LHS of the root be the user of the root...
1454 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001455 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001456 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1457 return 0;
1458 }
Chris Lattner65725312004-04-16 18:08:07 +00001459 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001460 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001461 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1462 BasicBlock::iterator ARI = &Root; ++ARI;
1463 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1464 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001465
1466 // Now propagate the ExtraOperand down the chain of instructions until we
1467 // get to LHSI.
1468 while (TmpLHSI != LHSI) {
1469 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001470 // Move the instruction to immediately before the chain we are
1471 // constructing to avoid breaking dominance properties.
1472 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1473 BB->getInstList().insert(ARI, NextLHSI);
1474 ARI = NextLHSI;
1475
Chris Lattner564a7272003-08-13 19:01:45 +00001476 Value *NextOp = NextLHSI->getOperand(1);
1477 NextLHSI->setOperand(1, ExtraOperand);
1478 TmpLHSI = NextLHSI;
1479 ExtraOperand = NextOp;
1480 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001481
Chris Lattner564a7272003-08-13 19:01:45 +00001482 // Now that the instructions are reassociated, have the functor perform
1483 // the transformation...
1484 return F.apply(Root);
1485 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001486
Chris Lattner564a7272003-08-13 19:01:45 +00001487 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1488 }
1489 return 0;
1490}
1491
1492
1493// AddRHS - Implements: X + X --> X << 1
1494struct AddRHS {
1495 Value *RHS;
1496 AddRHS(Value *rhs) : RHS(rhs) {}
1497 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1498 Instruction *apply(BinaryOperator &Add) const {
1499 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1500 ConstantInt::get(Type::UByteTy, 1));
1501 }
1502};
1503
1504// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1505// iff C1&C2 == 0
1506struct AddMaskingAnd {
1507 Constant *C2;
1508 AddMaskingAnd(Constant *c) : C2(c) {}
1509 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001510 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001511 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001512 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001513 }
1514 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001515 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001516 }
1517};
1518
Chris Lattner6e7ba452005-01-01 16:22:27 +00001519static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001520 InstCombiner *IC) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001521 if (isa<CastInst>(I)) {
1522 if (Constant *SOC = dyn_cast<Constant>(SO))
1523 return ConstantExpr::getCast(SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001524
Chris Lattner6e7ba452005-01-01 16:22:27 +00001525 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1526 SO->getName() + ".cast"), I);
1527 }
1528
Chris Lattner2eefe512004-04-09 19:05:30 +00001529 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001530 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1531 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001532
Chris Lattner2eefe512004-04-09 19:05:30 +00001533 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1534 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001535 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1536 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001537 }
1538
1539 Value *Op0 = SO, *Op1 = ConstOperand;
1540 if (!ConstIsRHS)
1541 std::swap(Op0, Op1);
1542 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001543 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1544 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1545 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1546 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
Chris Lattner326c0f32004-04-10 19:15:56 +00001547 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001548 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001549 abort();
1550 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001551 return IC->InsertNewInstBefore(New, I);
1552}
1553
1554// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1555// constant as the other operand, try to fold the binary operator into the
1556// select arguments. This also works for Cast instructions, which obviously do
1557// not have a second operand.
1558static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1559 InstCombiner *IC) {
1560 // Don't modify shared select instructions
1561 if (!SI->hasOneUse()) return 0;
1562 Value *TV = SI->getOperand(1);
1563 Value *FV = SI->getOperand(2);
1564
1565 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001566 // Bool selects with constant operands can be folded to logical ops.
1567 if (SI->getType() == Type::BoolTy) return 0;
1568
Chris Lattner6e7ba452005-01-01 16:22:27 +00001569 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1570 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1571
1572 return new SelectInst(SI->getCondition(), SelectTrueVal,
1573 SelectFalseVal);
1574 }
1575 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001576}
1577
Chris Lattner4e998b22004-09-29 05:07:12 +00001578
1579/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1580/// node as operand #0, see if we can fold the instruction into the PHI (which
1581/// is only possible if all operands to the PHI are constants).
1582Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1583 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001584 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001585 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001586
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001587 // Check to see if all of the operands of the PHI are constants. If there is
1588 // one non-constant value, remember the BB it is. If there is more than one
1589 // bail out.
1590 BasicBlock *NonConstBB = 0;
1591 for (unsigned i = 0; i != NumPHIValues; ++i)
1592 if (!isa<Constant>(PN->getIncomingValue(i))) {
1593 if (NonConstBB) return 0; // More than one non-const value.
1594 NonConstBB = PN->getIncomingBlock(i);
1595
1596 // If the incoming non-constant value is in I's block, we have an infinite
1597 // loop.
1598 if (NonConstBB == I.getParent())
1599 return 0;
1600 }
1601
1602 // If there is exactly one non-constant value, we can insert a copy of the
1603 // operation in that block. However, if this is a critical edge, we would be
1604 // inserting the computation one some other paths (e.g. inside a loop). Only
1605 // do this if the pred block is unconditionally branching into the phi block.
1606 if (NonConstBB) {
1607 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1608 if (!BI || !BI->isUnconditional()) return 0;
1609 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001610
1611 // Okay, we can do the transformation: create the new PHI node.
1612 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1613 I.setName("");
Chris Lattner55517062005-01-29 00:39:08 +00001614 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001615 InsertNewInstBefore(NewPN, *PN);
1616
1617 // Next, add all of the operands to the PHI.
1618 if (I.getNumOperands() == 2) {
1619 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001620 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001621 Value *InV;
1622 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1623 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1624 } else {
1625 assert(PN->getIncomingBlock(i) == NonConstBB);
1626 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1627 InV = BinaryOperator::create(BO->getOpcode(),
1628 PN->getIncomingValue(i), C, "phitmp",
1629 NonConstBB->getTerminator());
1630 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1631 InV = new ShiftInst(SI->getOpcode(),
1632 PN->getIncomingValue(i), C, "phitmp",
1633 NonConstBB->getTerminator());
1634 else
1635 assert(0 && "Unknown binop!");
1636
1637 WorkList.push_back(cast<Instruction>(InV));
1638 }
1639 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001640 }
1641 } else {
1642 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1643 const Type *RetTy = I.getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001644 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001645 Value *InV;
1646 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1647 InV = ConstantExpr::getCast(InC, RetTy);
1648 } else {
1649 assert(PN->getIncomingBlock(i) == NonConstBB);
1650 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1651 NonConstBB->getTerminator());
1652 WorkList.push_back(cast<Instruction>(InV));
1653 }
1654 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001655 }
1656 }
1657 return ReplaceInstUsesWith(I, NewPN);
1658}
1659
Chris Lattner7e708292002-06-25 16:13:24 +00001660Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00001661 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00001662 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001663
Chris Lattner66331a42004-04-10 22:01:55 +00001664 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00001665 // X + undef -> undef
1666 if (isa<UndefValue>(RHS))
1667 return ReplaceInstUsesWith(I, RHS);
1668
Chris Lattner66331a42004-04-10 22:01:55 +00001669 // X + 0 --> X
Chris Lattner5e678e02005-10-17 17:56:38 +00001670 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1671 if (RHSC->isNullValue())
1672 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00001673 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1674 if (CFP->isExactlyValue(-0.0))
1675 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00001676 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001677
Chris Lattner66331a42004-04-10 22:01:55 +00001678 // X + (signbit) --> X ^ signbit
1679 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattner74c51a02006-02-07 08:05:22 +00001680 uint64_t Val = CI->getZExtValue();
Chris Lattner1a074fc2006-02-07 07:00:41 +00001681 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
Chris Lattner48595f12004-06-10 02:07:29 +00001682 return BinaryOperator::createXor(LHS, RHS);
Chris Lattner66331a42004-04-10 22:01:55 +00001683 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001684
1685 if (isa<PHINode>(LHS))
1686 if (Instruction *NV = FoldOpIntoPhi(I))
1687 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00001688
Chris Lattner4f637d42006-01-06 17:59:59 +00001689 ConstantInt *XorRHS = 0;
1690 Value *XorLHS = 0;
Chris Lattner5931c542005-09-24 23:43:33 +00001691 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1692 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1693 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1694 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1695
1696 uint64_t C0080Val = 1ULL << 31;
1697 int64_t CFF80Val = -C0080Val;
1698 unsigned Size = 32;
1699 do {
1700 if (TySizeBits > Size) {
1701 bool Found = false;
1702 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1703 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1704 if (RHSSExt == CFF80Val) {
1705 if (XorRHS->getZExtValue() == C0080Val)
1706 Found = true;
1707 } else if (RHSZExt == C0080Val) {
1708 if (XorRHS->getSExtValue() == CFF80Val)
1709 Found = true;
1710 }
1711 if (Found) {
1712 // This is a sign extend if the top bits are known zero.
Chris Lattner68d5ff22006-02-09 07:38:58 +00001713 uint64_t Mask = ~0ULL;
Chris Lattner3bedbd92006-02-07 07:27:52 +00001714 Mask <<= 64-(TySizeBits-Size);
Chris Lattner68d5ff22006-02-09 07:38:58 +00001715 Mask &= XorLHS->getType()->getIntegralTypeMask();
Chris Lattner3bedbd92006-02-07 07:27:52 +00001716 if (!MaskedValueIsZero(XorLHS, Mask))
Chris Lattner5931c542005-09-24 23:43:33 +00001717 Size = 0; // Not a sign ext, but can't be any others either.
1718 goto FoundSExt;
1719 }
1720 }
1721 Size >>= 1;
1722 C0080Val >>= Size;
1723 CFF80Val >>= Size;
1724 } while (Size >= 8);
1725
1726FoundSExt:
1727 const Type *MiddleType = 0;
1728 switch (Size) {
1729 default: break;
1730 case 32: MiddleType = Type::IntTy; break;
1731 case 16: MiddleType = Type::ShortTy; break;
1732 case 8: MiddleType = Type::SByteTy; break;
1733 }
1734 if (MiddleType) {
1735 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1736 InsertNewInstBefore(NewTrunc, I);
1737 return new CastInst(NewTrunc, I.getType());
1738 }
1739 }
Chris Lattner66331a42004-04-10 22:01:55 +00001740 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00001741
Chris Lattner564a7272003-08-13 19:01:45 +00001742 // X + X --> X << 1
Robert Bocchino71698282004-07-27 21:02:21 +00001743 if (I.getType()->isInteger()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001744 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00001745
1746 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1747 if (RHSI->getOpcode() == Instruction::Sub)
1748 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1749 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1750 }
1751 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1752 if (LHSI->getOpcode() == Instruction::Sub)
1753 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1754 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1755 }
Robert Bocchino71698282004-07-27 21:02:21 +00001756 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00001757
Chris Lattner5c4afb92002-05-08 22:46:53 +00001758 // -A + B --> B - A
Chris Lattner8d969642003-03-10 23:06:50 +00001759 if (Value *V = dyn_castNegVal(LHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001760 return BinaryOperator::createSub(RHS, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001761
1762 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00001763 if (!isa<Constant>(RHS))
1764 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00001765 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001766
Misha Brukmanfd939082005-04-21 23:48:37 +00001767
Chris Lattner50af16a2004-11-13 19:50:12 +00001768 ConstantInt *C2;
1769 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1770 if (X == RHS) // X*C + X --> X * (C+1)
1771 return BinaryOperator::createMul(RHS, AddOne(C2));
1772
1773 // X*C1 + X*C2 --> X * (C1+C2)
1774 ConstantInt *C1;
1775 if (X == dyn_castFoldableMul(RHS, C1))
1776 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00001777 }
1778
1779 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00001780 if (dyn_castFoldableMul(RHS, C2) == LHS)
1781 return BinaryOperator::createMul(LHS, AddOne(C2));
1782
Chris Lattnerad3448c2003-02-18 19:57:07 +00001783
Chris Lattner564a7272003-08-13 19:01:45 +00001784 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001785 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattner564a7272003-08-13 19:01:45 +00001786 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00001787
Chris Lattner6b032052003-10-02 15:11:26 +00001788 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00001789 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001790 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1791 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1792 return BinaryOperator::createSub(C, X);
Chris Lattner6b032052003-10-02 15:11:26 +00001793 }
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001794
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001795 // (X & FF00) + xx00 -> (X+xx00) & FF00
1796 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1797 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1798 if (Anded == CRHS) {
1799 // See if all bits from the first bit set in the Add RHS up are included
1800 // in the mask. First, get the rightmost bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00001801 uint64_t AddRHSV = CRHS->getZExtValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001802
1803 // Form a mask of all bits from the lowest bit added through the top.
1804 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
Chris Lattner1a074fc2006-02-07 07:00:41 +00001805 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001806
1807 // See if the and mask includes all of these bits.
Reid Spencerb83eb642006-10-20 07:07:24 +00001808 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00001809
Chris Lattnerb99d6b12004-10-08 05:07:56 +00001810 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1811 // Okay, the xform is safe. Insert the new add pronto.
1812 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1813 LHS->getName()), I);
1814 return BinaryOperator::createAnd(NewAdd, C2);
1815 }
1816 }
1817 }
1818
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001819 // Try to fold constant add into select arguments.
1820 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001821 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001822 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00001823 }
1824
Andrew Lenharth16d79552006-09-19 18:24:51 +00001825 // add (cast *A to intptrtype) B -> cast (GEP (cast *A to sbyte*) B) -> intptrtype
1826 {
1827 CastInst* CI = dyn_cast<CastInst>(LHS);
1828 Value* Other = RHS;
1829 if (!CI) {
1830 CI = dyn_cast<CastInst>(RHS);
1831 Other = LHS;
1832 }
Andrew Lenharth45633262006-09-20 15:37:57 +00001833 if (CI && CI->getType()->isSized() &&
1834 (CI->getType()->getPrimitiveSize() ==
1835 TD->getIntPtrType()->getPrimitiveSize())
1836 && isa<PointerType>(CI->getOperand(0)->getType())) {
1837 Value* I2 = InsertCastBefore(CI->getOperand(0),
1838 PointerType::get(Type::SByteTy), I);
1839 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1840 return new CastInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00001841 }
1842 }
1843
Chris Lattner7e708292002-06-25 16:13:24 +00001844 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001845}
1846
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001847// isSignBit - Return true if the value represented by the constant only has the
1848// highest order bit set.
1849static bool isSignBit(ConstantInt *CI) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001850 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00001851 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00001852}
1853
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001854/// RemoveNoopCast - Strip off nonconverting casts from the value.
1855///
1856static Value *RemoveNoopCast(Value *V) {
1857 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1858 const Type *CTy = CI->getType();
1859 const Type *OpTy = CI->getOperand(0)->getType();
1860 if (CTy->isInteger() && OpTy->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00001861 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001862 return RemoveNoopCast(CI->getOperand(0));
1863 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1864 return RemoveNoopCast(CI->getOperand(0));
1865 }
1866 return V;
1867}
1868
Chris Lattner7e708292002-06-25 16:13:24 +00001869Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00001870 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00001871
Chris Lattner233f7dc2002-08-12 21:17:25 +00001872 if (Op0 == Op1) // sub X, X -> 0
1873 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00001874
Chris Lattner233f7dc2002-08-12 21:17:25 +00001875 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00001876 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00001877 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00001878
Chris Lattnere87597f2004-10-16 18:11:37 +00001879 if (isa<UndefValue>(Op0))
1880 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1881 if (isa<UndefValue>(Op1))
1882 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1883
Chris Lattnerd65460f2003-11-05 01:06:05 +00001884 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1885 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00001886 if (C->isAllOnesValue())
1887 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00001888
Chris Lattnerd65460f2003-11-05 01:06:05 +00001889 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001890 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001891 if (match(Op1, m_Not(m_Value(X))))
1892 return BinaryOperator::createAdd(X,
Chris Lattner48595f12004-06-10 02:07:29 +00001893 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
Chris Lattner9c290672004-03-12 23:53:13 +00001894 // -((uint)X >> 31) -> ((int)X >> 31)
1895 // -((int)X >> 31) -> ((uint)X >> 31)
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001896 if (C->isNullValue()) {
1897 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1898 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
Chris Lattner9c290672004-03-12 23:53:13 +00001899 if (SI->getOpcode() == Instruction::Shr)
Reid Spencerb83eb642006-10-20 07:07:24 +00001900 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00001901 const Type *NewTy;
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001902 if (SI->getType()->isSigned())
Chris Lattner5dd04022004-06-17 18:16:02 +00001903 NewTy = SI->getType()->getUnsignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001904 else
Chris Lattner5dd04022004-06-17 18:16:02 +00001905 NewTy = SI->getType()->getSignedVersion();
Chris Lattner9c290672004-03-12 23:53:13 +00001906 // Check to see if we are shifting out everything but the sign bit.
Reid Spencerb83eb642006-10-20 07:07:24 +00001907 if (CU->getZExtValue() ==
1908 SI->getType()->getPrimitiveSizeInBits()-1) {
Chris Lattner9c290672004-03-12 23:53:13 +00001909 // Ok, the transformation is safe. Insert a cast of the incoming
1910 // value, then the new shift, then the new cast.
1911 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1912 SI->getOperand(0)->getName());
1913 Value *InV = InsertNewInstBefore(FirstCast, I);
1914 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1915 CU, SI->getName());
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001916 if (NewShift->getType() == I.getType())
1917 return NewShift;
1918 else {
1919 InV = InsertNewInstBefore(NewShift, I);
1920 return new CastInst(NewShift, I.getType());
1921 }
Chris Lattner9c290672004-03-12 23:53:13 +00001922 }
1923 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00001924 }
Chris Lattner2eefe512004-04-09 19:05:30 +00001925
1926 // Try to fold constant sub into select arguments.
1927 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00001928 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00001929 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00001930
1931 if (isa<PHINode>(Op0))
1932 if (Instruction *NV = FoldOpIntoPhi(I))
1933 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00001934 }
1935
Chris Lattner43d84d62005-04-07 16:15:25 +00001936 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1937 if (Op1I->getOpcode() == Instruction::Add &&
1938 !Op0->getType()->isFloatingPoint()) {
Chris Lattner08954a22005-04-07 16:28:01 +00001939 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001940 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001941 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00001942 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00001943 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1944 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1945 // C1-(X+C2) --> (C1-C2)-X
1946 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1947 Op1I->getOperand(0));
1948 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001949 }
1950
Chris Lattnerfd059242003-10-15 16:48:29 +00001951 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001952 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1953 // is not used by anyone else...
1954 //
Chris Lattner0517e722004-02-02 20:09:56 +00001955 if (Op1I->getOpcode() == Instruction::Sub &&
1956 !Op1I->getType()->isFloatingPoint()) {
Chris Lattnera2881962003-02-18 19:28:33 +00001957 // Swap the two operands of the subexpr...
1958 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1959 Op1I->setOperand(0, IIOp1);
1960 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00001961
Chris Lattnera2881962003-02-18 19:28:33 +00001962 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00001963 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00001964 }
1965
1966 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1967 //
1968 if (Op1I->getOpcode() == Instruction::And &&
1969 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1970 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1971
Chris Lattnerf523d062004-06-09 05:08:07 +00001972 Value *NewNot =
1973 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00001974 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00001975 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00001976
Reid Spencerac5209e2006-10-16 23:08:08 +00001977 // 0 - (X sdiv C) -> (X sdiv -C)
Chris Lattner91ccc152004-10-06 15:08:25 +00001978 if (Op1I->getOpcode() == Instruction::Div)
Reid Spencerb83eb642006-10-20 07:07:24 +00001979 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
1980 if (CSI->getType()->isSigned() && CSI->isNullValue())
Chris Lattner91ccc152004-10-06 15:08:25 +00001981 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Misha Brukmanfd939082005-04-21 23:48:37 +00001982 return BinaryOperator::createDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00001983 ConstantExpr::getNeg(DivRHS));
1984
Chris Lattnerad3448c2003-02-18 19:57:07 +00001985 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00001986 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00001987 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Misha Brukmanfd939082005-04-21 23:48:37 +00001988 Constant *CP1 =
Chris Lattner50af16a2004-11-13 19:50:12 +00001989 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00001990 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00001991 }
Chris Lattner40371712002-05-09 01:29:19 +00001992 }
Chris Lattner43d84d62005-04-07 16:15:25 +00001993 }
Chris Lattnera2881962003-02-18 19:28:33 +00001994
Chris Lattner7edc8c22005-04-07 17:14:51 +00001995 if (!Op0->getType()->isFloatingPoint())
1996 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1997 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00001998 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1999 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2000 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2001 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002002 } else if (Op0I->getOpcode() == Instruction::Sub) {
2003 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2004 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002005 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002006
Chris Lattner50af16a2004-11-13 19:50:12 +00002007 ConstantInt *C1;
2008 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2009 if (X == Op1) { // X*C - X --> X * (C-1)
2010 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2011 return BinaryOperator::createMul(Op1, CP1);
2012 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002013
Chris Lattner50af16a2004-11-13 19:50:12 +00002014 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2015 if (X == dyn_castFoldableMul(Op1, C2))
2016 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2017 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002018 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002019}
2020
Chris Lattner4cb170c2004-02-23 06:38:22 +00002021/// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2022/// really just returns true if the most significant (sign) bit is set.
2023static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2024 if (RHS->getType()->isSigned()) {
2025 // True if source is LHS < 0 or LHS <= -1
2026 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2027 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2028 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00002029 ConstantInt *RHSC = cast<ConstantInt>(RHS);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002030 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2031 // the size of the integer type.
2032 if (Opcode == Instruction::SetGE)
Reid Spencerb83eb642006-10-20 07:07:24 +00002033 return RHSC->getZExtValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00002034 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002035 if (Opcode == Instruction::SetGT)
Reid Spencerb83eb642006-10-20 07:07:24 +00002036 return RHSC->getZExtValue() ==
Chris Lattner484d3cf2005-04-24 06:59:08 +00002037 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002038 }
2039 return false;
2040}
2041
Chris Lattner7e708292002-06-25 16:13:24 +00002042Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002043 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002044 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002045
Chris Lattnere87597f2004-10-16 18:11:37 +00002046 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2048
Chris Lattner233f7dc2002-08-12 21:17:25 +00002049 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002050 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2051 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002052
2053 // ((X << C1)*C2) == (X * (C2 << C1))
2054 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2055 if (SI->getOpcode() == Instruction::Shl)
2056 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002057 return BinaryOperator::createMul(SI->getOperand(0),
2058 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002059
Chris Lattner515c97c2003-09-11 22:24:54 +00002060 if (CI->isNullValue())
2061 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2062 if (CI->equalsInt(1)) // X * 1 == X
2063 return ReplaceInstUsesWith(I, Op0);
2064 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002065 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002066
Reid Spencerb83eb642006-10-20 07:07:24 +00002067 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002068 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2069 uint64_t C = Log2_64(Val);
Chris Lattnera2881962003-02-18 19:28:33 +00002070 return new ShiftInst(Instruction::Shl, Op0,
Reid Spencerb83eb642006-10-20 07:07:24 +00002071 ConstantInt::get(Type::UByteTy, C));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002072 }
Robert Bocchino71698282004-07-27 21:02:21 +00002073 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002074 if (Op1F->isNullValue())
2075 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002076
Chris Lattnera2881962003-02-18 19:28:33 +00002077 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2078 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2079 if (Op1F->getValue() == 1.0)
2080 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2081 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002082
2083 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2084 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2085 isa<ConstantInt>(Op0I->getOperand(1))) {
2086 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2087 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2088 Op1, "tmp");
2089 InsertNewInstBefore(Add, I);
2090 Value *C1C2 = ConstantExpr::getMul(Op1,
2091 cast<Constant>(Op0I->getOperand(1)));
2092 return BinaryOperator::createAdd(Add, C1C2);
2093
2094 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002095
2096 // Try to fold constant mul into select arguments.
2097 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002098 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002099 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002100
2101 if (isa<PHINode>(Op0))
2102 if (Instruction *NV = FoldOpIntoPhi(I))
2103 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002104 }
2105
Chris Lattnera4f445b2003-03-10 23:23:04 +00002106 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2107 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002108 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002109
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002110 // If one of the operands of the multiply is a cast from a boolean value, then
2111 // we know the bool is either zero or one, so this is a 'masking' multiply.
2112 // See if we can simplify things based on how the boolean was originally
2113 // formed.
2114 CastInst *BoolCast = 0;
2115 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2116 if (CI->getOperand(0)->getType() == Type::BoolTy)
2117 BoolCast = CI;
2118 if (!BoolCast)
2119 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2120 if (CI->getOperand(0)->getType() == Type::BoolTy)
2121 BoolCast = CI;
2122 if (BoolCast) {
2123 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2124 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2125 const Type *SCOpTy = SCIOp0->getType();
2126
Chris Lattner4cb170c2004-02-23 06:38:22 +00002127 // If the setcc is true iff the sign bit of X is set, then convert this
2128 // multiply into a shift/and combination.
2129 if (isa<ConstantInt>(SCIOp1) &&
2130 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002131 // Shift the X value right to turn it into "all signbits".
Reid Spencerb83eb642006-10-20 07:07:24 +00002132 Constant *Amt = ConstantInt::get(Type::UByteTy,
Chris Lattner484d3cf2005-04-24 06:59:08 +00002133 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002134 if (SCIOp0->getType()->isUnsigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00002135 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
Chris Lattner4cb170c2004-02-23 06:38:22 +00002136 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
2137 SCIOp0->getName()), I);
2138 }
2139
2140 Value *V =
2141 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
2142 BoolCast->getOperand(0)->getName()+
2143 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002144
2145 // If the multiply type is not the same as the source type, sign extend
2146 // or truncate to the multiply type.
2147 if (I.getType() != V->getType())
Chris Lattner4cb170c2004-02-23 06:38:22 +00002148 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
Misha Brukmanfd939082005-04-21 23:48:37 +00002149
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002150 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002151 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002152 }
2153 }
2154 }
2155
Chris Lattner7e708292002-06-25 16:13:24 +00002156 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002157}
2158
Chris Lattner7e708292002-06-25 16:13:24 +00002159Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002160 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002161
Chris Lattner857e8cd2004-12-12 21:48:58 +00002162 if (isa<UndefValue>(Op0)) // undef / X -> 0
2163 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2164 if (isa<UndefValue>(Op1))
2165 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
2166
2167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner83a2e6e2004-04-26 14:01:59 +00002168 // div X, 1 == X
Chris Lattner233f7dc2002-08-12 21:17:25 +00002169 if (RHS->equalsInt(1))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002170 return ReplaceInstUsesWith(I, Op0);
Chris Lattnera2881962003-02-18 19:28:33 +00002171
Chris Lattner83a2e6e2004-04-26 14:01:59 +00002172 // div X, -1 == -X
2173 if (RHS->isAllOnesValue())
Chris Lattner857e8cd2004-12-12 21:48:58 +00002174 return BinaryOperator::createNeg(Op0);
Chris Lattner83a2e6e2004-04-26 14:01:59 +00002175
Chris Lattner857e8cd2004-12-12 21:48:58 +00002176 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
Chris Lattner18d19ca2004-09-28 18:22:15 +00002177 if (LHS->getOpcode() == Instruction::Div)
2178 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Chris Lattner18d19ca2004-09-28 18:22:15 +00002179 // (X / C1) / C2 -> X / (C1*C2)
2180 return BinaryOperator::createDiv(LHS->getOperand(0),
2181 ConstantExpr::getMul(RHS, LHSRHS));
2182 }
2183
Chris Lattnera2881962003-02-18 19:28:33 +00002184 // Check to see if this is an unsigned division with an exact power of 2,
2185 // if so, convert to a right shift.
Reid Spencerb83eb642006-10-20 07:07:24 +00002186 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2187 if (C->getType()->isUnsigned())
2188 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2189 if (isPowerOf2_64(Val)) {
2190 uint64_t C = Log2_64(Val);
2191 return new ShiftInst(Instruction::Shr, Op0,
2192 ConstantInt::get(Type::UByteTy, C));
2193 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002194
Chris Lattnera052f822004-10-09 02:50:40 +00002195 // -X/C -> X/-C
2196 if (RHS->getType()->isSigned())
Chris Lattner857e8cd2004-12-12 21:48:58 +00002197 if (Value *LHSNeg = dyn_castNegVal(Op0))
Chris Lattnera052f822004-10-09 02:50:40 +00002198 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2199
Chris Lattner857e8cd2004-12-12 21:48:58 +00002200 if (!RHS->isNullValue()) {
2201 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002202 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner857e8cd2004-12-12 21:48:58 +00002203 return R;
2204 if (isa<PHINode>(Op0))
2205 if (Instruction *NV = FoldOpIntoPhi(I))
2206 return NV;
2207 }
Chris Lattnera2881962003-02-18 19:28:33 +00002208 }
2209
Chris Lattner8e49e082006-09-09 20:26:32 +00002210 // Handle div X, Cond?Y:Z
2211 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2212 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2213 // same basic block, then we replace the select with Y, and the condition of
2214 // the select with false (if the cond value is in the same BB). If the
2215 // select has uses other than the div, this allows them to be simplified
2216 // also.
2217 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2218 if (ST->isNullValue()) {
2219 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2220 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner47811b72006-09-28 23:35:22 +00002221 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002222 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2223 I.setOperand(1, SI->getOperand(2));
2224 else
2225 UpdateValueUsesWith(SI, SI->getOperand(2));
2226 return &I;
2227 }
2228 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2229 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2230 if (ST->isNullValue()) {
2231 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2232 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner47811b72006-09-28 23:35:22 +00002233 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002234 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2235 I.setOperand(1, SI->getOperand(1));
2236 else
2237 UpdateValueUsesWith(SI, SI->getOperand(1));
2238 return &I;
2239 }
2240
2241 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2242 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
Reid Spencerb83eb642006-10-20 07:07:24 +00002243 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2244 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2245 if (STO->getType()->isUnsigned() && SFO->getType()->isUnsigned()) {
2246 // STO == 0 and SFO == 0 handled above.
2247 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2248 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2249 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2250 Constant *TC = ConstantInt::get(Type::UByteTy, TSA);
2251 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
2252 TC, SI->getName()+".t");
2253 TSI = InsertNewInstBefore(TSI, I);
Misha Brukmanfd939082005-04-21 23:48:37 +00002254
Reid Spencerb83eb642006-10-20 07:07:24 +00002255 Constant *FC = ConstantInt::get(Type::UByteTy, FSA);
2256 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
2257 FC, SI->getName()+".f");
2258 FSI = InsertNewInstBefore(FSI, I);
2259 return new SelectInst(SI->getOperand(0), TSI, FSI);
2260 }
Chris Lattnerbf70b832005-04-08 04:03:26 +00002261 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002262 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002263
Chris Lattnera2881962003-02-18 19:28:33 +00002264 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002265 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002266 if (LHS->equalsInt(0))
2267 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2268
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002269 if (I.getType()->isSigned()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00002270 // If the sign bits of both operands are zero (i.e. we can prove they are
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002271 // unsigned inputs), turn this into a udiv.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002272 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2273 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002274 const Type *NTy = Op0->getType()->getUnsignedVersion();
2275 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2276 InsertNewInstBefore(LHS, I);
2277 Value *RHS;
2278 if (Constant *R = dyn_cast<Constant>(Op1))
2279 RHS = ConstantExpr::getCast(R, NTy);
2280 else
2281 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2282 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2283 InsertNewInstBefore(Div, I);
2284 return new CastInst(Div, I.getType());
2285 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002286 } else {
2287 // Known to be an unsigned division.
2288 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2289 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2290 if (RHSI->getOpcode() == Instruction::Shl &&
Reid Spencerb83eb642006-10-20 07:07:24 +00002291 isa<ConstantInt>(RHSI->getOperand(0)) &&
2292 RHSI->getOperand(0)->getType()->isUnsigned()) {
2293 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002294 if (isPowerOf2_64(C1)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002295 uint64_t C2 = Log2_64(C1);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002296 Value *Add = RHSI->getOperand(1);
2297 if (C2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002298 Constant *C2V = ConstantInt::get(Add->getType(), C2);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002299 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2300 "tmp"), I);
2301 }
2302 return new ShiftInst(Instruction::Shr, Op0, Add);
2303 }
2304 }
2305 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002306 }
2307
Chris Lattner3f5b8772002-05-06 16:14:14 +00002308 return 0;
2309}
2310
2311
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002312/// GetFactor - If we can prove that the specified value is at least a multiple
2313/// of some factor, return that factor.
2314static Constant *GetFactor(Value *V) {
2315 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2316 return CI;
2317
2318 // Unless we can be tricky, we know this is a multiple of 1.
2319 Constant *Result = ConstantInt::get(V->getType(), 1);
2320
2321 Instruction *I = dyn_cast<Instruction>(V);
2322 if (!I) return Result;
2323
2324 if (I->getOpcode() == Instruction::Mul) {
2325 // Handle multiplies by a constant, etc.
2326 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2327 GetFactor(I->getOperand(1)));
2328 } else if (I->getOpcode() == Instruction::Shl) {
2329 // (X<<C) -> X * (1 << C)
2330 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2331 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2332 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2333 }
2334 } else if (I->getOpcode() == Instruction::And) {
2335 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2336 // X & 0xFFF0 is known to be a multiple of 16.
2337 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2338 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2339 return ConstantExpr::getShl(Result,
Reid Spencerb83eb642006-10-20 07:07:24 +00002340 ConstantInt::get(Type::UByteTy, Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002341 }
2342 } else if (I->getOpcode() == Instruction::Cast) {
2343 Value *Op = I->getOperand(0);
2344 // Only handle int->int casts.
2345 if (!Op->getType()->isInteger()) return Result;
2346 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2347 }
2348 return Result;
2349}
2350
Chris Lattner7e708292002-06-25 16:13:24 +00002351Instruction *InstCombiner::visitRem(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002352 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002353
2354 // 0 % X == 0, we don't need to preserve faults!
2355 if (Constant *LHS = dyn_cast<Constant>(Op0))
2356 if (LHS->isNullValue())
2357 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2358
2359 if (isa<UndefValue>(Op0)) // undef % X -> 0
2360 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2361 if (isa<UndefValue>(Op1))
2362 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2363
Chris Lattner11a49f22005-11-05 07:28:37 +00002364 if (I.getType()->isSigned()) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002365 if (Value *RHSNeg = dyn_castNegVal(Op1))
Reid Spencerb83eb642006-10-20 07:07:24 +00002366 if (!isa<ConstantInt>(RHSNeg) || !RHSNeg->getType()->isSigned() ||
2367 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
Chris Lattner5b73c082004-07-06 07:01:22 +00002368 // X % -Y -> X % Y
2369 AddUsesToWorkList(I);
2370 I.setOperand(1, RHSNeg);
2371 return &I;
2372 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002373
2374 // If the top bits of both operands are zero (i.e. we can prove they are
2375 // unsigned inputs), turn this into a urem.
Chris Lattner3bedbd92006-02-07 07:27:52 +00002376 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2377 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Chris Lattner11a49f22005-11-05 07:28:37 +00002378 const Type *NTy = Op0->getType()->getUnsignedVersion();
2379 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2380 InsertNewInstBefore(LHS, I);
2381 Value *RHS;
2382 if (Constant *R = dyn_cast<Constant>(Op1))
2383 RHS = ConstantExpr::getCast(R, NTy);
2384 else
2385 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2386 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2387 InsertNewInstBefore(Rem, I);
2388 return new CastInst(Rem, I.getType());
2389 }
2390 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002391
Chris Lattner857e8cd2004-12-12 21:48:58 +00002392 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002393 // X % 0 == undef, we don't need to preserve faults!
2394 if (RHS->equalsInt(0))
2395 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2396
Chris Lattnera2881962003-02-18 19:28:33 +00002397 if (RHS->equalsInt(1)) // X % 1 == 0
2398 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2399
2400 // Check to see if this is an unsigned remainder with an exact power of 2,
2401 // if so, convert to a bitwise and.
Reid Spencerb83eb642006-10-20 07:07:24 +00002402 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2403 if (RHS->getType()->isUnsigned())
2404 if (isPowerOf2_64(C->getZExtValue()))
2405 return BinaryOperator::createAnd(Op0, SubOne(C));
Chris Lattner857e8cd2004-12-12 21:48:58 +00002406
Chris Lattner97943922006-02-28 05:49:21 +00002407 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2408 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2409 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2410 return R;
2411 } else if (isa<PHINode>(Op0I)) {
2412 if (Instruction *NV = FoldOpIntoPhi(I))
2413 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002414 }
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002415
2416 // X*C1%C2 --> 0 iff C1%C2 == 0
2417 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2418 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002419 }
Chris Lattnera2881962003-02-18 19:28:33 +00002420 }
2421
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002422 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2423 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2424 if (I.getType()->isUnsigned() &&
2425 RHSI->getOpcode() == Instruction::Shl &&
Reid Spencerb83eb642006-10-20 07:07:24 +00002426 isa<ConstantInt>(RHSI->getOperand(0)) &&
2427 RHSI->getOperand(0)->getType()->isUnsigned()) {
2428 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002429 if (isPowerOf2_64(C1)) {
2430 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2431 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2432 "tmp"), I);
2433 return BinaryOperator::createAnd(Op0, Add);
2434 }
2435 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002436
2437 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2438 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
Chris Lattner8e49e082006-09-09 20:26:32 +00002439 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2440 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2441 // the same basic block, then we replace the select with Y, and the
2442 // condition of the select with false (if the cond value is in the same
2443 // BB). If the select has uses other than the div, this allows them to be
2444 // simplified also.
2445 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2446 if (ST->isNullValue()) {
2447 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2448 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner47811b72006-09-28 23:35:22 +00002449 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002450 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2451 I.setOperand(1, SI->getOperand(2));
2452 else
2453 UpdateValueUsesWith(SI, SI->getOperand(2));
2454 return &I;
2455 }
2456 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2457 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2458 if (ST->isNullValue()) {
2459 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2460 if (CondI && CondI->getParent() == I.getParent())
Chris Lattner47811b72006-09-28 23:35:22 +00002461 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002462 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2463 I.setOperand(1, SI->getOperand(1));
2464 else
2465 UpdateValueUsesWith(SI, SI->getOperand(1));
2466 return &I;
2467 }
2468
2469
Reid Spencerb83eb642006-10-20 07:07:24 +00002470 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2471 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2472 if (STO->getType()->isUnsigned() && SFO->getType()->isUnsigned()) {
2473 // STO == 0 and SFO == 0 handled above.
2474 if (isPowerOf2_64(STO->getZExtValue()) &&
2475 isPowerOf2_64(SFO->getZExtValue())) {
2476 Value *TrueAnd = InsertNewInstBefore(
2477 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"),
2478 I);
2479 Value *FalseAnd = InsertNewInstBefore(
2480 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"),
2481 I);
2482 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2483 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002484 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002485 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002486 }
2487
Chris Lattner3f5b8772002-05-06 16:14:14 +00002488 return 0;
2489}
2490
Chris Lattner8b170942002-08-09 23:47:40 +00002491// isMaxValueMinusOne - return true if this is Max-1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002492static bool isMaxValueMinusOne(const ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002493 if (C->getType()->isUnsigned())
2494 return C->getZExtValue() == C->getType()->getIntegralTypeMask()-1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002495
Chris Lattner8b170942002-08-09 23:47:40 +00002496 // Calculate 0111111111..11111
Chris Lattner484d3cf2005-04-24 06:59:08 +00002497 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002498 int64_t Val = INT64_MAX; // All ones
2499 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
Reid Spencerb83eb642006-10-20 07:07:24 +00002500 return C->getSExtValue() == Val-1;
Chris Lattner8b170942002-08-09 23:47:40 +00002501}
2502
2503// isMinValuePlusOne - return true if this is Min+1
Chris Lattner233f7dc2002-08-12 21:17:25 +00002504static bool isMinValuePlusOne(const ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002505 if (C->getType()->isUnsigned())
2506 return C->getZExtValue() == 1;
Misha Brukmanfd939082005-04-21 23:48:37 +00002507
2508 // Calculate 1111111111000000000000
Chris Lattner484d3cf2005-04-24 06:59:08 +00002509 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattner8b170942002-08-09 23:47:40 +00002510 int64_t Val = -1; // All ones
2511 Val <<= TypeBits-1; // Shift over to the right spot
Reid Spencerb83eb642006-10-20 07:07:24 +00002512 return C->getSExtValue() == Val+1;
Chris Lattner8b170942002-08-09 23:47:40 +00002513}
2514
Chris Lattner457dd822004-06-09 07:59:58 +00002515// isOneBitSet - Return true if there is exactly one bit set in the specified
2516// constant.
2517static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002518 uint64_t V = CI->getZExtValue();
Chris Lattner457dd822004-06-09 07:59:58 +00002519 return V && (V & (V-1)) == 0;
2520}
2521
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002522#if 0 // Currently unused
2523// isLowOnes - Return true if the constant is of the form 0+1+.
2524static bool isLowOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002525 uint64_t V = CI->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002526
2527 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002528 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002529
2530 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2531 return U && V && (U & V) == 0;
2532}
2533#endif
2534
2535// isHighOnes - Return true if the constant is of the form 1+0+.
2536// This is the same as lowones(~X).
2537static bool isHighOnes(const ConstantInt *CI) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002538 uint64_t V = ~CI->getZExtValue();
Chris Lattner2b83af22005-08-07 07:03:10 +00002539 if (~V == 0) return false; // 0's does not match "1+"
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002540
2541 // There won't be bits set in parts that the type doesn't contain.
Reid Spencerb83eb642006-10-20 07:07:24 +00002542 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00002543
2544 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2545 return U && V && (U & V) == 0;
2546}
2547
2548
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002549/// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2550/// are carefully arranged to allow folding of expressions such as:
2551///
2552/// (A < B) | (A > B) --> (A != B)
2553///
2554/// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2555/// represents that the comparison is true if A == B, and bit value '1' is true
2556/// if A < B.
2557///
2558static unsigned getSetCondCode(const SetCondInst *SCI) {
2559 switch (SCI->getOpcode()) {
2560 // False -> 0
2561 case Instruction::SetGT: return 1;
2562 case Instruction::SetEQ: return 2;
2563 case Instruction::SetGE: return 3;
2564 case Instruction::SetLT: return 4;
2565 case Instruction::SetNE: return 5;
2566 case Instruction::SetLE: return 6;
2567 // True -> 7
2568 default:
2569 assert(0 && "Invalid SetCC opcode!");
2570 return 0;
2571 }
2572}
2573
2574/// getSetCCValue - This is the complement of getSetCondCode, which turns an
2575/// opcode and two operands into either a constant true or false, or a brand new
2576/// SetCC instruction.
2577static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2578 switch (Opcode) {
Chris Lattner47811b72006-09-28 23:35:22 +00002579 case 0: return ConstantBool::getFalse();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002580 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2581 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2582 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2583 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2584 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2585 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
Chris Lattner47811b72006-09-28 23:35:22 +00002586 case 7: return ConstantBool::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002587 default: assert(0 && "Illegal SetCCCode!"); return 0;
2588 }
2589}
2590
2591// FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2592struct FoldSetCCLogical {
2593 InstCombiner &IC;
2594 Value *LHS, *RHS;
2595 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2596 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2597 bool shouldApply(Value *V) const {
2598 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2599 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2600 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2601 return false;
2602 }
2603 Instruction *apply(BinaryOperator &Log) const {
2604 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2605 if (SCI->getOperand(0) != LHS) {
2606 assert(SCI->getOperand(1) == LHS);
2607 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2608 }
2609
2610 unsigned LHSCode = getSetCondCode(SCI);
2611 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2612 unsigned Code;
2613 switch (Log.getOpcode()) {
2614 case Instruction::And: Code = LHSCode & RHSCode; break;
2615 case Instruction::Or: Code = LHSCode | RHSCode; break;
2616 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00002617 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00002618 }
2619
2620 Value *RV = getSetCCValue(Code, LHS, RHS);
2621 if (Instruction *I = dyn_cast<Instruction>(RV))
2622 return I;
2623 // Otherwise, it's a constant boolean value...
2624 return IC.ReplaceInstUsesWith(Log, RV);
2625 }
2626};
2627
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002628// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2629// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2630// guaranteed to be either a shift instruction or a binary operator.
2631Instruction *InstCombiner::OptAndOp(Instruction *Op,
2632 ConstantIntegral *OpRHS,
2633 ConstantIntegral *AndRHS,
2634 BinaryOperator &TheAnd) {
2635 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00002636 Constant *Together = 0;
2637 if (!isa<ShiftInst>(Op))
Chris Lattner48595f12004-06-10 02:07:29 +00002638 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00002639
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002640 switch (Op->getOpcode()) {
2641 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002642 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002643 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2644 std::string OpName = Op->getName(); Op->setName("");
Chris Lattner48595f12004-06-10 02:07:29 +00002645 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002646 InsertNewInstBefore(And, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002647 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002648 }
2649 break;
2650 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00002651 if (Together == AndRHS) // (X | C) & C --> C
2652 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002653
Chris Lattner6e7ba452005-01-01 16:22:27 +00002654 if (Op->hasOneUse() && Together != OpRHS) {
2655 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2656 std::string Op0Name = Op->getName(); Op->setName("");
2657 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2658 InsertNewInstBefore(Or, TheAnd);
2659 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002660 }
2661 break;
2662 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00002663 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002664 // Adding a one to a single bit bit-field should be turned into an XOR
2665 // of the bit. First thing to check is to see if this AND is with a
2666 // single bit constant.
Reid Spencerb83eb642006-10-20 07:07:24 +00002667 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002668
2669 // Clear bits that are not part of the constant.
Chris Lattner1a074fc2006-02-07 07:00:41 +00002670 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002671
2672 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00002673 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002674 // Ok, at this point, we know that we are masking the result of the
2675 // ADD down to exactly one bit. If the constant we are adding has
2676 // no bits set below this bit, then we can eliminate the ADD.
Reid Spencerb83eb642006-10-20 07:07:24 +00002677 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00002678
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002679 // Check to see if any bits below the one bit set in AndRHSV are set.
2680 if ((AddRHS & (AndRHSV-1)) == 0) {
2681 // If not, the only thing that can effect the output of the AND is
2682 // the bit specified by AndRHSV. If that bit is set, the effect of
2683 // the XOR is to toggle the bit. If it is clear, then the ADD has
2684 // no effect.
2685 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2686 TheAnd.setOperand(0, X);
2687 return &TheAnd;
2688 } else {
2689 std::string Name = Op->getName(); Op->setName("");
2690 // Pull the XOR out of the AND.
Chris Lattner48595f12004-06-10 02:07:29 +00002691 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002692 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner48595f12004-06-10 02:07:29 +00002693 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002694 }
2695 }
2696 }
2697 }
2698 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00002699
2700 case Instruction::Shl: {
2701 // We know that the AND will not produce any of the bits shifted in, so if
2702 // the anded constant includes them, clear them now!
2703 //
2704 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002705 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2706 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00002707
Chris Lattner0c967662004-09-24 15:21:34 +00002708 if (CI == ShlMask) { // Masking out bits that the shift already masks
2709 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2710 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00002711 TheAnd.setOperand(1, CI);
2712 return &TheAnd;
2713 }
2714 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00002715 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002716 case Instruction::Shr:
2717 // We know that the AND will not produce any of the bits shifted in, so if
2718 // the anded constant includes them, clear them now! This only applies to
2719 // unsigned shifts, because a signed shr may bring in set bits!
2720 //
2721 if (AndRHS->getType()->isUnsigned()) {
2722 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
Chris Lattner0c967662004-09-24 15:21:34 +00002723 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2724 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2725
2726 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2727 return ReplaceInstUsesWith(TheAnd, Op);
2728 } else if (CI != AndRHS) {
2729 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
Chris Lattner62a355c2003-09-19 19:05:02 +00002730 return &TheAnd;
2731 }
Chris Lattner0c967662004-09-24 15:21:34 +00002732 } else { // Signed shr.
2733 // See if this is shifting in some sign extension, then masking it out
2734 // with an and.
2735 if (Op->hasOneUse()) {
2736 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2737 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2738 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
Chris Lattner9b991822004-10-22 04:53:16 +00002739 if (CI == AndRHS) { // Masking out bits shifted in.
Chris Lattner0c967662004-09-24 15:21:34 +00002740 // Make the argument unsigned.
2741 Value *ShVal = Op->getOperand(0);
2742 ShVal = InsertCastBefore(ShVal,
2743 ShVal->getType()->getUnsignedVersion(),
2744 TheAnd);
2745 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2746 OpRHS, Op->getName()),
2747 TheAnd);
Chris Lattnerdc781222004-10-27 05:57:15 +00002748 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2749 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2750 TheAnd.getName()),
2751 TheAnd);
Chris Lattner0c967662004-09-24 15:21:34 +00002752 return new CastInst(ShVal, Op->getType());
2753 }
2754 }
Chris Lattner62a355c2003-09-19 19:05:02 +00002755 }
2756 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002757 }
2758 return 0;
2759}
2760
Chris Lattner8b170942002-08-09 23:47:40 +00002761
Chris Lattnera96879a2004-09-29 17:40:11 +00002762/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2763/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2764/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2765/// insert new instructions.
2766Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2767 bool Inside, Instruction &IB) {
2768 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2769 "Lo is not <= Hi in range emission code!");
2770 if (Inside) {
2771 if (Lo == Hi) // Trivially false.
2772 return new SetCondInst(Instruction::SetNE, V, V);
2773 if (cast<ConstantIntegral>(Lo)->isMinValue())
2774 return new SetCondInst(Instruction::SetLT, V, Hi);
Misha Brukmanfd939082005-04-21 23:48:37 +00002775
Chris Lattnera96879a2004-09-29 17:40:11 +00002776 Constant *AddCST = ConstantExpr::getNeg(Lo);
2777 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2778 InsertNewInstBefore(Add, IB);
2779 // Convert to unsigned for the comparison.
2780 const Type *UnsType = Add->getType()->getUnsignedVersion();
2781 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2782 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2783 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2784 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2785 }
2786
2787 if (Lo == Hi) // Trivially true.
2788 return new SetCondInst(Instruction::SetEQ, V, V);
2789
2790 Hi = SubOne(cast<ConstantInt>(Hi));
Reid Spencerb83eb642006-10-20 07:07:24 +00002791
2792 // V < 0 || V >= Hi ->'V > Hi-1'
2793 if (cast<ConstantIntegral>(Lo)->isMinValue())
Chris Lattnera96879a2004-09-29 17:40:11 +00002794 return new SetCondInst(Instruction::SetGT, V, Hi);
2795
2796 // Emit X-Lo > Hi-Lo-1
2797 Constant *AddCST = ConstantExpr::getNeg(Lo);
2798 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2799 InsertNewInstBefore(Add, IB);
2800 // Convert to unsigned for the comparison.
2801 const Type *UnsType = Add->getType()->getUnsignedVersion();
2802 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2803 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2804 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2805 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2806}
2807
Chris Lattner7203e152005-09-18 07:22:02 +00002808// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2809// any number of 0s on either side. The 1s are allowed to wrap from LSB to
2810// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2811// not, since all 1s are not contiguous.
2812static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002813 uint64_t V = Val->getZExtValue();
Chris Lattner7203e152005-09-18 07:22:02 +00002814 if (!isShiftedMask_64(V)) return false;
2815
2816 // look for the first zero bit after the run of ones
2817 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2818 // look for the first non-zero bit
2819 ME = 64-CountLeadingZeros_64(V);
2820 return true;
2821}
2822
2823
2824
2825/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2826/// where isSub determines whether the operator is a sub. If we can fold one of
2827/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00002828///
2829/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2830/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2831/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2832///
2833/// return (A +/- B).
2834///
2835Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2836 ConstantIntegral *Mask, bool isSub,
2837 Instruction &I) {
2838 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2839 if (!LHSI || LHSI->getNumOperands() != 2 ||
2840 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2841
2842 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2843
2844 switch (LHSI->getOpcode()) {
2845 default: return 0;
2846 case Instruction::And:
Chris Lattner7203e152005-09-18 07:22:02 +00002847 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2848 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Reid Spencerb83eb642006-10-20 07:07:24 +00002849 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
Chris Lattner7203e152005-09-18 07:22:02 +00002850 break;
2851
2852 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2853 // part, we don't need any explicit masks to take them out of A. If that
2854 // is all N is, ignore it.
2855 unsigned MB, ME;
2856 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Chris Lattner3bedbd92006-02-07 07:27:52 +00002857 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2858 Mask >>= 64-MB+1;
2859 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00002860 break;
2861 }
2862 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00002863 return 0;
2864 case Instruction::Or:
2865 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00002866 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Reid Spencerb83eb642006-10-20 07:07:24 +00002867 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
Chris Lattner7203e152005-09-18 07:22:02 +00002868 ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00002869 break;
2870 return 0;
2871 }
2872
2873 Instruction *New;
2874 if (isSub)
2875 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2876 else
2877 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2878 return InsertNewInstBefore(New, I);
2879}
2880
Chris Lattner7e708292002-06-25 16:13:24 +00002881Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002882 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002883 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002884
Chris Lattnere87597f2004-10-16 18:11:37 +00002885 if (isa<UndefValue>(Op1)) // X & undef -> 0
2886 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2887
Chris Lattner6e7ba452005-01-01 16:22:27 +00002888 // and X, X = X
2889 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00002890 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002891
Chris Lattnerf8c36f52006-02-12 08:02:11 +00002892 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00002893 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00002894 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00002895 if (!isa<PackedType>(I.getType()) &&
2896 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattner255d8912006-02-11 09:31:47 +00002897 KnownZero, KnownOne))
Chris Lattner9ca96412006-02-08 03:25:32 +00002898 return &I;
2899
Chris Lattner6e7ba452005-01-01 16:22:27 +00002900 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner7560c3a2006-02-08 07:34:50 +00002901 uint64_t AndRHSMask = AndRHS->getZExtValue();
2902 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
Chris Lattner7560c3a2006-02-08 07:34:50 +00002903 uint64_t NotAndRHS = AndRHSMask^TypeMask;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002904
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002905 // Optimize a variety of ((val OP C1) & C2) combinations...
2906 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2907 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002908 Value *Op0LHS = Op0I->getOperand(0);
2909 Value *Op0RHS = Op0I->getOperand(1);
2910 switch (Op0I->getOpcode()) {
2911 case Instruction::Xor:
2912 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00002913 // If the mask is only needed on one incoming arm, push it up.
2914 if (Op0I->hasOneUse()) {
2915 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2916 // Not masking anything out for the LHS, move to RHS.
2917 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2918 Op0RHS->getName()+".masked");
2919 InsertNewInstBefore(NewRHS, I);
2920 return BinaryOperator::create(
2921 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002922 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00002923 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00002924 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2925 // Not masking anything out for the RHS, move to LHS.
2926 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2927 Op0LHS->getName()+".masked");
2928 InsertNewInstBefore(NewLHS, I);
2929 return BinaryOperator::create(
2930 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2931 }
2932 }
2933
Chris Lattner6e7ba452005-01-01 16:22:27 +00002934 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00002935 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00002936 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2937 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2938 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2939 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2940 return BinaryOperator::createAnd(V, AndRHS);
2941 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2942 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00002943 break;
2944
2945 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00002946 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2947 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2948 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2949 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2950 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00002951 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002952 }
2953
Chris Lattner58403262003-07-23 19:25:52 +00002954 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002955 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00002956 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00002957 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2958 const Type *SrcTy = CI->getOperand(0)->getType();
2959
Chris Lattner2b83af22005-08-07 07:03:10 +00002960 // If this is an integer truncation or change from signed-to-unsigned, and
2961 // if the source is an and/or with immediate, transform it. This
2962 // frequently occurs for bitfield accesses.
2963 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2964 if (SrcTy->getPrimitiveSizeInBits() >=
2965 I.getType()->getPrimitiveSizeInBits() &&
2966 CastOp->getNumOperands() == 2)
Chris Lattner7560c3a2006-02-08 07:34:50 +00002967 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
Chris Lattner2b83af22005-08-07 07:03:10 +00002968 if (CastOp->getOpcode() == Instruction::And) {
2969 // Change: and (cast (and X, C1) to T), C2
2970 // into : and (cast X to T), trunc(C1)&C2
2971 // This will folds the two ands together, which may allow other
2972 // simplifications.
2973 Instruction *NewCast =
2974 new CastInst(CastOp->getOperand(0), I.getType(),
2975 CastOp->getName()+".shrunk");
2976 NewCast = InsertNewInstBefore(NewCast, I);
2977
2978 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2979 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2980 return BinaryOperator::createAnd(NewCast, C3);
2981 } else if (CastOp->getOpcode() == Instruction::Or) {
2982 // Change: and (cast (or X, C1) to T), C2
2983 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2984 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2985 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2986 return ReplaceInstUsesWith(I, AndRHS);
2987 }
2988 }
Chris Lattner06782f82003-07-23 19:36:21 +00002989 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002990
2991 // Try to fold constant and into select arguments.
2992 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002993 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002994 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002995 if (isa<PHINode>(Op0))
2996 if (Instruction *NV = FoldOpIntoPhi(I))
2997 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00002998 }
2999
Chris Lattner8d969642003-03-10 23:06:50 +00003000 Value *Op0NotVal = dyn_castNotVal(Op0);
3001 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003002
Chris Lattner5b62aa72004-06-18 06:07:51 +00003003 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3005
Misha Brukmancb6267b2004-07-30 12:50:08 +00003006 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003007 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003008 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3009 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003010 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003011 return BinaryOperator::createNot(Or);
3012 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003013
3014 {
3015 Value *A = 0, *B = 0;
3016 ConstantInt *C1 = 0, *C2 = 0;
3017 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3018 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3019 return ReplaceInstUsesWith(I, Op1);
3020 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3021 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3022 return ReplaceInstUsesWith(I, Op0);
Chris Lattner64daab52006-04-01 08:03:55 +00003023
3024 if (Op0->hasOneUse() &&
3025 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3026 if (A == Op1) { // (A^B)&A -> A&(A^B)
3027 I.swapOperands(); // Simplify below
3028 std::swap(Op0, Op1);
3029 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3030 cast<BinaryOperator>(Op0)->swapOperands();
3031 I.swapOperands(); // Simplify below
3032 std::swap(Op0, Op1);
3033 }
3034 }
3035 if (Op1->hasOneUse() &&
3036 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3037 if (B == Op0) { // B&(A^B) -> B&(B^A)
3038 cast<BinaryOperator>(Op1)->swapOperands();
3039 std::swap(A, B);
3040 }
3041 if (A == Op0) { // A&(A^B) -> A & ~B
3042 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3043 InsertNewInstBefore(NotB, I);
3044 return BinaryOperator::createAnd(A, NotB);
3045 }
3046 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003047 }
3048
Chris Lattnera2881962003-02-18 19:28:33 +00003049
Chris Lattner955f3312004-09-28 21:48:02 +00003050 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3051 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003052 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3053 return R;
3054
Chris Lattner955f3312004-09-28 21:48:02 +00003055 Value *LHSVal, *RHSVal;
3056 ConstantInt *LHSCst, *RHSCst;
3057 Instruction::BinaryOps LHSCC, RHSCC;
3058 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3059 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3060 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3061 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00003062 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattner955f3312004-09-28 21:48:02 +00003063 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3064 // Ensure that the larger constant is on the RHS.
3065 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3066 SetCondInst *LHS = cast<SetCondInst>(Op0);
3067 if (cast<ConstantBool>(Cmp)->getValue()) {
3068 std::swap(LHS, RHS);
3069 std::swap(LHSCst, RHSCst);
3070 std::swap(LHSCC, RHSCC);
3071 }
3072
3073 // At this point, we know we have have two setcc instructions
3074 // comparing a value against two constants and and'ing the result
3075 // together. Because of the above check, we know that we only have
3076 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3077 // FoldSetCCLogical check above), that the two constants are not
3078 // equal.
3079 assert(LHSCst != RHSCst && "Compares not folded above?");
3080
3081 switch (LHSCC) {
3082 default: assert(0 && "Unknown integer condition code!");
3083 case Instruction::SetEQ:
3084 switch (RHSCC) {
3085 default: assert(0 && "Unknown integer condition code!");
3086 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3087 case Instruction::SetGT: // (X == 13 & X > 15) -> false
Chris Lattner47811b72006-09-28 23:35:22 +00003088 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner955f3312004-09-28 21:48:02 +00003089 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3090 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3091 return ReplaceInstUsesWith(I, LHS);
3092 }
3093 case Instruction::SetNE:
3094 switch (RHSCC) {
3095 default: assert(0 && "Unknown integer condition code!");
3096 case Instruction::SetLT:
3097 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3098 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3099 break; // (X != 13 & X < 15) -> no change
3100 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3101 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3102 return ReplaceInstUsesWith(I, RHS);
3103 case Instruction::SetNE:
3104 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3105 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3106 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3107 LHSVal->getName()+".off");
3108 InsertNewInstBefore(Add, I);
3109 const Type *UnsType = Add->getType()->getUnsignedVersion();
3110 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3111 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3112 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3113 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3114 }
3115 break; // (X != 13 & X != 15) -> no change
3116 }
3117 break;
3118 case Instruction::SetLT:
3119 switch (RHSCC) {
3120 default: assert(0 && "Unknown integer condition code!");
3121 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3122 case Instruction::SetGT: // (X < 13 & X > 15) -> false
Chris Lattner47811b72006-09-28 23:35:22 +00003123 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner955f3312004-09-28 21:48:02 +00003124 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3125 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3126 return ReplaceInstUsesWith(I, LHS);
3127 }
3128 case Instruction::SetGT:
3129 switch (RHSCC) {
3130 default: assert(0 && "Unknown integer condition code!");
3131 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3132 return ReplaceInstUsesWith(I, LHS);
3133 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3134 return ReplaceInstUsesWith(I, RHS);
3135 case Instruction::SetNE:
3136 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3137 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3138 break; // (X > 13 & X != 15) -> no change
Chris Lattnera96879a2004-09-29 17:40:11 +00003139 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3140 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
Chris Lattner955f3312004-09-28 21:48:02 +00003141 }
3142 }
3143 }
3144 }
3145
Chris Lattner6fc205f2006-05-05 06:39:07 +00003146 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3147 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003148 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003149 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003150 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003151 // Only do this if the casts both really cause code to be generated.
3152 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3153 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003154 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3155 Op1C->getOperand(0),
3156 I.getName());
3157 InsertNewInstBefore(NewOp, I);
3158 return new CastInst(NewOp, I.getType());
3159 }
3160 }
3161
Chris Lattner7e708292002-06-25 16:13:24 +00003162 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003163}
3164
Chris Lattnerafe91a52006-06-15 19:07:26 +00003165/// CollectBSwapParts - Look to see if the specified value defines a single byte
3166/// in the result. If it does, and if the specified byte hasn't been filled in
3167/// yet, fill it in and return false.
3168static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3169 Instruction *I = dyn_cast<Instruction>(V);
3170 if (I == 0) return true;
3171
3172 // If this is an or instruction, it is an inner node of the bswap.
3173 if (I->getOpcode() == Instruction::Or)
3174 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3175 CollectBSwapParts(I->getOperand(1), ByteValues);
3176
3177 // If this is a shift by a constant int, and it is "24", then its operand
3178 // defines a byte. We only handle unsigned types here.
3179 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3180 // Not shifting the entire input by N-1 bytes?
Reid Spencerb83eb642006-10-20 07:07:24 +00003181 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003182 8*(ByteValues.size()-1))
3183 return true;
3184
3185 unsigned DestNo;
3186 if (I->getOpcode() == Instruction::Shl) {
3187 // X << 24 defines the top byte with the lowest of the input bytes.
3188 DestNo = ByteValues.size()-1;
3189 } else {
3190 // X >>u 24 defines the low byte with the highest of the input bytes.
3191 DestNo = 0;
3192 }
3193
3194 // If the destination byte value is already defined, the values are or'd
3195 // together, which isn't a bswap (unless it's an or of the same bits).
3196 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3197 return true;
3198 ByteValues[DestNo] = I->getOperand(0);
3199 return false;
3200 }
3201
3202 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3203 // don't have this.
3204 Value *Shift = 0, *ShiftLHS = 0;
3205 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3206 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3207 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3208 return true;
3209 Instruction *SI = cast<Instruction>(Shift);
3210
3211 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Reid Spencerb83eb642006-10-20 07:07:24 +00003212 if (ShiftAmt->getZExtValue() & 7 ||
3213 ShiftAmt->getZExtValue() > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003214 return true;
3215
3216 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3217 unsigned DestByte;
3218 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Reid Spencerb83eb642006-10-20 07:07:24 +00003219 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003220 break;
3221 // Unknown mask for bswap.
3222 if (DestByte == ByteValues.size()) return true;
3223
Reid Spencerb83eb642006-10-20 07:07:24 +00003224 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003225 unsigned SrcByte;
3226 if (SI->getOpcode() == Instruction::Shl)
3227 SrcByte = DestByte - ShiftBytes;
3228 else
3229 SrcByte = DestByte + ShiftBytes;
3230
3231 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3232 if (SrcByte != ByteValues.size()-DestByte-1)
3233 return true;
3234
3235 // If the destination byte value is already defined, the values are or'd
3236 // together, which isn't a bswap (unless it's an or of the same bits).
3237 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3238 return true;
3239 ByteValues[DestByte] = SI->getOperand(0);
3240 return false;
3241}
3242
3243/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3244/// If so, insert the new bswap intrinsic and return it.
3245Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3246 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3247 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3248 return 0;
3249
3250 /// ByteValues - For each byte of the result, we keep track of which value
3251 /// defines each byte.
3252 std::vector<Value*> ByteValues;
3253 ByteValues.resize(I.getType()->getPrimitiveSize());
3254
3255 // Try to find all the pieces corresponding to the bswap.
3256 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3257 CollectBSwapParts(I.getOperand(1), ByteValues))
3258 return 0;
3259
3260 // Check to see if all of the bytes come from the same value.
3261 Value *V = ByteValues[0];
3262 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3263
3264 // Check to make sure that all of the bytes come from the same value.
3265 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3266 if (ByteValues[i] != V)
3267 return 0;
3268
3269 // If they do then *success* we can turn this into a bswap. Figure out what
3270 // bswap to make it into.
3271 Module *M = I.getParent()->getParent()->getParent();
Chris Lattnered36b2f2006-07-11 18:31:26 +00003272 const char *FnName = 0;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003273 if (I.getType() == Type::UShortTy)
3274 FnName = "llvm.bswap.i16";
3275 else if (I.getType() == Type::UIntTy)
3276 FnName = "llvm.bswap.i32";
3277 else if (I.getType() == Type::ULongTy)
3278 FnName = "llvm.bswap.i64";
3279 else
3280 assert(0 && "Unknown integer type!");
3281 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3282
3283 return new CallInst(F, V);
3284}
3285
3286
Chris Lattner7e708292002-06-25 16:13:24 +00003287Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003288 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003289 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003290
Chris Lattnere87597f2004-10-16 18:11:37 +00003291 if (isa<UndefValue>(Op1))
3292 return ReplaceInstUsesWith(I, // X | undef -> -1
3293 ConstantIntegral::getAllOnesValue(I.getType()));
3294
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003295 // or X, X = X
3296 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003297 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003298
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003299 // See if we can simplify any instructions used by the instruction whose sole
3300 // purpose is to compute bits we don't care about.
3301 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003302 if (!isa<PackedType>(I.getType()) &&
3303 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003304 KnownZero, KnownOne))
3305 return &I;
3306
Chris Lattner3f5b8772002-05-06 16:14:14 +00003307 // or X, -1 == -1
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003308 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003309 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003310 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3311 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003312 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3313 Op0->setName("");
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003314 InsertNewInstBefore(Or, I);
3315 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3316 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003317
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003318 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3319 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3320 std::string Op0Name = Op0->getName(); Op0->setName("");
3321 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3322 InsertNewInstBefore(Or, I);
3323 return BinaryOperator::createXor(Or,
3324 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003325 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003326
3327 // Try to fold constant and into select arguments.
3328 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003329 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003330 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003331 if (isa<PHINode>(Op0))
3332 if (Instruction *NV = FoldOpIntoPhi(I))
3333 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003334 }
3335
Chris Lattner4f637d42006-01-06 17:59:59 +00003336 Value *A = 0, *B = 0;
3337 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003338
3339 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3340 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3341 return ReplaceInstUsesWith(I, Op1);
3342 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3343 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3344 return ReplaceInstUsesWith(I, Op0);
3345
Chris Lattner6423d4c2006-07-10 20:25:24 +00003346 // (A | B) | C and A | (B | C) -> bswap if possible.
3347 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003348 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00003349 match(Op1, m_Or(m_Value(), m_Value())) ||
3350 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3351 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003352 if (Instruction *BSwap = MatchBSwap(I))
3353 return BSwap;
3354 }
3355
Chris Lattner6e4c6492005-05-09 04:58:36 +00003356 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3357 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003358 MaskedValueIsZero(Op1, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003359 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3360 Op0->setName("");
3361 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3362 }
3363
3364 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3365 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattner3bedbd92006-02-07 07:27:52 +00003366 MaskedValueIsZero(Op0, C1->getZExtValue())) {
Chris Lattner6e4c6492005-05-09 04:58:36 +00003367 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3368 Op0->setName("");
3369 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3370 }
3371
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003372 // (A & C1)|(B & C2)
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003373 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003374 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3375
3376 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3377 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3378
3379
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003380 // If we have: ((V + N) & C1) | (V & C2)
3381 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3382 // replace with V+N.
3383 if (C1 == ConstantExpr::getNot(C2)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003384 Value *V1 = 0, *V2 = 0;
Reid Spencerb83eb642006-10-20 07:07:24 +00003385 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003386 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3387 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003388 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003389 return ReplaceInstUsesWith(I, A);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003390 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003391 return ReplaceInstUsesWith(I, A);
3392 }
3393 // Or commutes, try both ways.
Reid Spencerb83eb642006-10-20 07:07:24 +00003394 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003395 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3396 // Add commutes, try both ways.
Chris Lattner3bedbd92006-02-07 07:27:52 +00003397 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003398 return ReplaceInstUsesWith(I, B);
Chris Lattner3bedbd92006-02-07 07:27:52 +00003399 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00003400 return ReplaceInstUsesWith(I, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003401 }
3402 }
3403 }
Chris Lattner67ca7682003-08-12 19:11:07 +00003404
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003405 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3406 if (A == Op1) // ~A | A == -1
Misha Brukmanfd939082005-04-21 23:48:37 +00003407 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003408 ConstantIntegral::getAllOnesValue(I.getType()));
3409 } else {
3410 A = 0;
3411 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003412 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003413 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3414 if (Op0 == B)
Misha Brukmanfd939082005-04-21 23:48:37 +00003415 return ReplaceInstUsesWith(I,
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003416 ConstantIntegral::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00003417
Misha Brukmancb6267b2004-07-30 12:50:08 +00003418 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003419 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3420 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3421 I.getName()+".demorgan"), I);
3422 return BinaryOperator::createNot(And);
3423 }
Chris Lattnera27231a2003-03-10 23:13:59 +00003424 }
Chris Lattnera2881962003-02-18 19:28:33 +00003425
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003426 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003427 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003428 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3429 return R;
3430
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003431 Value *LHSVal, *RHSVal;
3432 ConstantInt *LHSCst, *RHSCst;
3433 Instruction::BinaryOps LHSCC, RHSCC;
3434 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3435 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3436 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3437 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
Misha Brukmanfd939082005-04-21 23:48:37 +00003438 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003439 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3440 // Ensure that the larger constant is on the RHS.
3441 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3442 SetCondInst *LHS = cast<SetCondInst>(Op0);
3443 if (cast<ConstantBool>(Cmp)->getValue()) {
3444 std::swap(LHS, RHS);
3445 std::swap(LHSCst, RHSCst);
3446 std::swap(LHSCC, RHSCC);
3447 }
3448
3449 // At this point, we know we have have two setcc instructions
3450 // comparing a value against two constants and or'ing the result
3451 // together. Because of the above check, we know that we only have
3452 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3453 // FoldSetCCLogical check above), that the two constants are not
3454 // equal.
3455 assert(LHSCst != RHSCst && "Compares not folded above?");
3456
3457 switch (LHSCC) {
3458 default: assert(0 && "Unknown integer condition code!");
3459 case Instruction::SetEQ:
3460 switch (RHSCC) {
3461 default: assert(0 && "Unknown integer condition code!");
3462 case Instruction::SetEQ:
3463 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3464 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3465 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3466 LHSVal->getName()+".off");
3467 InsertNewInstBefore(Add, I);
3468 const Type *UnsType = Add->getType()->getUnsignedVersion();
3469 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3470 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3471 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3472 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3473 }
3474 break; // (X == 13 | X == 15) -> no change
3475
Chris Lattner240d6f42005-04-19 06:04:18 +00003476 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3477 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003478 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3479 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3480 return ReplaceInstUsesWith(I, RHS);
3481 }
3482 break;
3483 case Instruction::SetNE:
3484 switch (RHSCC) {
3485 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003486 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3487 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3488 return ReplaceInstUsesWith(I, LHS);
3489 case Instruction::SetNE: // (X != 13 | X != 15) -> true
Chris Lattnere88b7532005-06-17 03:59:17 +00003490 case Instruction::SetLT: // (X != 13 | X < 15) -> true
Chris Lattner47811b72006-09-28 23:35:22 +00003491 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003492 }
3493 break;
3494 case Instruction::SetLT:
3495 switch (RHSCC) {
3496 default: assert(0 && "Unknown integer condition code!");
3497 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3498 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00003499 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3500 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003501 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3502 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3503 return ReplaceInstUsesWith(I, RHS);
3504 }
3505 break;
3506 case Instruction::SetGT:
3507 switch (RHSCC) {
3508 default: assert(0 && "Unknown integer condition code!");
3509 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3510 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3511 return ReplaceInstUsesWith(I, LHS);
3512 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3513 case Instruction::SetLT: // (X > 13 | X < 15) -> true
Chris Lattner47811b72006-09-28 23:35:22 +00003514 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00003515 }
3516 }
3517 }
3518 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003519
3520 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3521 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003522 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003523 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003524 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003525 // Only do this if the casts both really cause code to be generated.
3526 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3527 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003528 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3529 Op1C->getOperand(0),
3530 I.getName());
3531 InsertNewInstBefore(NewOp, I);
3532 return new CastInst(NewOp, I.getType());
3533 }
3534 }
3535
Chris Lattnere9bed7d2005-09-18 03:42:07 +00003536
Chris Lattner7e708292002-06-25 16:13:24 +00003537 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003538}
3539
Chris Lattnerc317d392004-02-16 01:20:27 +00003540// XorSelf - Implements: X ^ X --> 0
3541struct XorSelf {
3542 Value *RHS;
3543 XorSelf(Value *rhs) : RHS(rhs) {}
3544 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3545 Instruction *apply(BinaryOperator &Xor) const {
3546 return &Xor;
3547 }
3548};
Chris Lattner3f5b8772002-05-06 16:14:14 +00003549
3550
Chris Lattner7e708292002-06-25 16:13:24 +00003551Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003552 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003553 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003554
Chris Lattnere87597f2004-10-16 18:11:37 +00003555 if (isa<UndefValue>(Op1))
3556 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3557
Chris Lattnerc317d392004-02-16 01:20:27 +00003558 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3559 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3560 assert(Result == &I && "AssociativeOpt didn't work?");
Chris Lattner233f7dc2002-08-12 21:17:25 +00003561 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00003562 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003563
3564 // See if we can simplify any instructions used by the instruction whose sole
3565 // purpose is to compute bits we don't care about.
3566 uint64_t KnownZero, KnownOne;
Chris Lattner98509ef2006-03-25 21:58:26 +00003567 if (!isa<PackedType>(I.getType()) &&
3568 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003569 KnownZero, KnownOne))
3570 return &I;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003571
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003572 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003573 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner05bd1b22002-08-20 18:24:26 +00003574 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003575 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
Chris Lattner47811b72006-09-28 23:35:22 +00003576 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
Chris Lattner05bd1b22002-08-20 18:24:26 +00003577 return new SetCondInst(SCI->getInverseCondition(),
3578 SCI->getOperand(0), SCI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00003579
Chris Lattnerd65460f2003-11-05 01:06:05 +00003580 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00003581 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3582 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00003583 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3584 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003585 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00003586 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003587 }
Chris Lattner5b62aa72004-06-18 06:07:51 +00003588
3589 // ~(~X & Y) --> (X | ~Y)
3590 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3591 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3592 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3593 Instruction *NotY =
Misha Brukmanfd939082005-04-21 23:48:37 +00003594 BinaryOperator::createNot(Op0I->getOperand(1),
Chris Lattner5b62aa72004-06-18 06:07:51 +00003595 Op0I->getOperand(1)->getName()+".not");
3596 InsertNewInstBefore(NotY, I);
3597 return BinaryOperator::createOr(Op0NotVal, NotY);
3598 }
3599 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003600
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003601 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003602 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00003603 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00003604 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00003605 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3606 return BinaryOperator::createSub(
3607 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00003608 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00003609 Op0I->getOperand(0));
Chris Lattner7c4049c2004-01-12 19:35:11 +00003610 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00003611 } else if (Op0I->getOpcode() == Instruction::Or) {
3612 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3613 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3614 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3615 // Anything in both C1 and C2 is known to be zero, remove it from
3616 // NewRHS.
3617 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3618 NewRHS = ConstantExpr::getAnd(NewRHS,
3619 ConstantExpr::getNot(CommonBits));
3620 WorkList.push_back(Op0I);
3621 I.setOperand(0, Op0I->getOperand(0));
3622 I.setOperand(1, NewRHS);
3623 return &I;
3624 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00003625 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00003626 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003627
3628 // Try to fold constant and into select arguments.
3629 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003630 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003631 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003632 if (isa<PHINode>(Op0))
3633 if (Instruction *NV = FoldOpIntoPhi(I))
3634 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003635 }
3636
Chris Lattner8d969642003-03-10 23:06:50 +00003637 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003638 if (X == Op1)
3639 return ReplaceInstUsesWith(I,
3640 ConstantIntegral::getAllOnesValue(I.getType()));
3641
Chris Lattner8d969642003-03-10 23:06:50 +00003642 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00003643 if (X == Op0)
3644 return ReplaceInstUsesWith(I,
3645 ConstantIntegral::getAllOnesValue(I.getType()));
3646
Chris Lattner64daab52006-04-01 08:03:55 +00003647 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
Chris Lattner26ca7e12004-02-16 03:54:20 +00003648 if (Op1I->getOpcode() == Instruction::Or) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003649 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003650 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00003651 I.swapOperands();
3652 std::swap(Op0, Op1);
3653 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003654 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00003655 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00003656 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003657 } else if (Op1I->getOpcode() == Instruction::Xor) {
3658 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3659 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3660 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3661 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003662 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3663 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3664 Op1I->swapOperands();
3665 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3666 I.swapOperands(); // Simplified below.
3667 std::swap(Op0, Op1);
3668 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003669 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003670
Chris Lattner64daab52006-04-01 08:03:55 +00003671 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
Chris Lattnerfd059242003-10-15 16:48:29 +00003672 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
Chris Lattnercb40a372003-03-10 18:24:17 +00003673 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00003674 Op0I->swapOperands();
Chris Lattner4f98c562003-03-10 21:43:22 +00003675 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
Chris Lattner64daab52006-04-01 08:03:55 +00003676 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3677 InsertNewInstBefore(NotB, I);
Chris Lattner48595f12004-06-10 02:07:29 +00003678 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00003679 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00003680 } else if (Op0I->getOpcode() == Instruction::Xor) {
3681 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3682 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3683 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3684 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner64daab52006-04-01 08:03:55 +00003685 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3686 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3687 Op0I->swapOperands();
Chris Lattnerae1ab392006-04-01 22:05:01 +00003688 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3689 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner64daab52006-04-01 08:03:55 +00003690 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3691 InsertNewInstBefore(N, I);
3692 return BinaryOperator::createAnd(N, Op1);
3693 }
Chris Lattnercb40a372003-03-10 18:24:17 +00003694 }
3695
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003696 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3697 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3698 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3699 return R;
3700
Chris Lattner6fc205f2006-05-05 06:39:07 +00003701 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3702 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner581a7ad2006-05-05 20:51:30 +00003703 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner6fc205f2006-05-05 06:39:07 +00003704 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Chris Lattner581a7ad2006-05-05 20:51:30 +00003705 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
Chris Lattner33a61132006-05-06 09:00:16 +00003706 // Only do this if the casts both really cause code to be generated.
3707 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3708 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00003709 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3710 Op1C->getOperand(0),
3711 I.getName());
3712 InsertNewInstBefore(NewOp, I);
3713 return new CastInst(NewOp, I.getType());
3714 }
3715 }
3716
Chris Lattner7e708292002-06-25 16:13:24 +00003717 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003718}
3719
Chris Lattnera96879a2004-09-29 17:40:11 +00003720/// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3721/// overflowed for this type.
3722static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3723 ConstantInt *In2) {
3724 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3725 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3726}
3727
3728static bool isPositive(ConstantInt *C) {
Reid Spencerb83eb642006-10-20 07:07:24 +00003729 return C->getSExtValue() >= 0;
Chris Lattnera96879a2004-09-29 17:40:11 +00003730}
3731
3732/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3733/// overflowed for this type.
3734static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3735 ConstantInt *In2) {
3736 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3737
3738 if (In1->getType()->isUnsigned())
Reid Spencerb83eb642006-10-20 07:07:24 +00003739 return cast<ConstantInt>(Result)->getZExtValue() <
3740 cast<ConstantInt>(In1)->getZExtValue();
Chris Lattnera96879a2004-09-29 17:40:11 +00003741 if (isPositive(In1) != isPositive(In2))
3742 return false;
3743 if (isPositive(In1))
Reid Spencerb83eb642006-10-20 07:07:24 +00003744 return cast<ConstantInt>(Result)->getSExtValue() <
3745 cast<ConstantInt>(In1)->getSExtValue();
3746 return cast<ConstantInt>(Result)->getSExtValue() >
3747 cast<ConstantInt>(In1)->getSExtValue();
Chris Lattnera96879a2004-09-29 17:40:11 +00003748}
3749
Chris Lattner574da9b2005-01-13 20:14:25 +00003750/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3751/// code necessary to compute the offset from the base pointer (without adding
3752/// in the base pointer). Return the result as a signed integer of intptr size.
3753static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3754 TargetData &TD = IC.getTargetData();
3755 gep_type_iterator GTI = gep_type_begin(GEP);
3756 const Type *UIntPtrTy = TD.getIntPtrType();
3757 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3758 Value *Result = Constant::getNullValue(SIntPtrTy);
3759
3760 // Build a mask for high order bits.
Chris Lattner1a074fc2006-02-07 07:00:41 +00003761 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
Chris Lattner574da9b2005-01-13 20:14:25 +00003762
Chris Lattner574da9b2005-01-13 20:14:25 +00003763 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3764 Value *Op = GEP->getOperand(i);
Chris Lattner0b84c802005-01-13 23:26:48 +00003765 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
Reid Spencerb83eb642006-10-20 07:07:24 +00003766 Constant *Scale = ConstantExpr::getCast(ConstantInt::get(UIntPtrTy, Size),
Chris Lattner574da9b2005-01-13 20:14:25 +00003767 SIntPtrTy);
3768 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3769 if (!OpC->isNullValue()) {
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003770 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00003771 Scale = ConstantExpr::getMul(OpC, Scale);
3772 if (Constant *RC = dyn_cast<Constant>(Result))
3773 Result = ConstantExpr::getAdd(RC, Scale);
3774 else {
3775 // Emit an add instruction.
3776 Result = IC.InsertNewInstBefore(
3777 BinaryOperator::createAdd(Result, Scale,
3778 GEP->getName()+".offs"), I);
3779 }
3780 }
3781 } else {
Chris Lattner6f7f02f2005-01-14 17:17:59 +00003782 // Convert to correct type.
3783 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3784 Op->getName()+".c"), I);
3785 if (Size != 1)
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003786 // We'll let instcombine(mul) convert this to a shl if possible.
3787 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3788 GEP->getName()+".idx"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00003789
3790 // Emit an add instruction.
Chris Lattner5bdf04c2005-01-13 20:40:58 +00003791 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
Chris Lattner574da9b2005-01-13 20:14:25 +00003792 GEP->getName()+".offs"), I);
3793 }
3794 }
3795 return Result;
3796}
3797
3798/// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3799/// else. At this point we know that the GEP is on the LHS of the comparison.
3800Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3801 Instruction::BinaryOps Cond,
3802 Instruction &I) {
3803 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00003804
3805 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3806 if (isa<PointerType>(CI->getOperand(0)->getType()))
3807 RHS = CI->getOperand(0);
3808
Chris Lattner574da9b2005-01-13 20:14:25 +00003809 Value *PtrBase = GEPLHS->getOperand(0);
3810 if (PtrBase == RHS) {
3811 // As an optimization, we don't actually have to compute the actual value of
3812 // OFFSET if this is a seteq or setne comparison, just return whether each
3813 // index is zero or not.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003814 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3815 Instruction *InVal = 0;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003816 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3817 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnere9d782b2005-01-13 22:25:21 +00003818 bool EmitIt = true;
3819 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3820 if (isa<UndefValue>(C)) // undef index -> undef.
3821 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3822 if (C->isNullValue())
3823 EmitIt = false;
Chris Lattnerad5fec12005-01-28 19:32:01 +00003824 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3825 EmitIt = false; // This is indexing into a zero sized array?
Misha Brukmanfd939082005-04-21 23:48:37 +00003826 } else if (isa<ConstantInt>(C))
Chris Lattnere9d782b2005-01-13 22:25:21 +00003827 return ReplaceInstUsesWith(I, // No comparison is needed here.
3828 ConstantBool::get(Cond == Instruction::SetNE));
3829 }
3830
3831 if (EmitIt) {
Misha Brukmanfd939082005-04-21 23:48:37 +00003832 Instruction *Comp =
Chris Lattnere9d782b2005-01-13 22:25:21 +00003833 new SetCondInst(Cond, GEPLHS->getOperand(i),
3834 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3835 if (InVal == 0)
3836 InVal = Comp;
3837 else {
3838 InVal = InsertNewInstBefore(InVal, I);
3839 InsertNewInstBefore(Comp, I);
3840 if (Cond == Instruction::SetNE) // True if any are unequal
3841 InVal = BinaryOperator::createOr(InVal, Comp);
3842 else // True if all are equal
3843 InVal = BinaryOperator::createAnd(InVal, Comp);
3844 }
3845 }
3846 }
3847
3848 if (InVal)
3849 return InVal;
3850 else
3851 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3852 ConstantBool::get(Cond == Instruction::SetEQ));
3853 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003854
3855 // Only lower this if the setcc is the only user of the GEP or if we expect
3856 // the result to fold to a constant!
3857 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3858 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3859 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3860 return new SetCondInst(Cond, Offset,
3861 Constant::getNullValue(Offset->getType()));
3862 }
3863 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00003864 // If the base pointers are different, but the indices are the same, just
3865 // compare the base pointer.
3866 if (PtrBase != GEPRHS->getOperand(0)) {
3867 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00003868 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00003869 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00003870 if (IndicesTheSame)
3871 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3872 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3873 IndicesTheSame = false;
3874 break;
3875 }
3876
3877 // If all indices are the same, just compare the base pointers.
3878 if (IndicesTheSame)
3879 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3880 GEPRHS->getOperand(0));
3881
3882 // Otherwise, the base pointers are different and the indices are
3883 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00003884 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00003885 }
Chris Lattner574da9b2005-01-13 20:14:25 +00003886
Chris Lattnere9d782b2005-01-13 22:25:21 +00003887 // If one of the GEPs has all zero indices, recurse.
3888 bool AllZeros = true;
3889 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3890 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3891 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3892 AllZeros = false;
3893 break;
3894 }
3895 if (AllZeros)
3896 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3897 SetCondInst::getSwappedCondition(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003898
3899 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00003900 AllZeros = true;
3901 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3902 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3903 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3904 AllZeros = false;
3905 break;
3906 }
3907 if (AllZeros)
3908 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3909
Chris Lattner4401c9c2005-01-14 00:20:05 +00003910 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3911 // If the GEPs only differ by one index, compare it.
3912 unsigned NumDifferences = 0; // Keep track of # differences.
3913 unsigned DiffOperand = 0; // The operand that differs.
3914 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3915 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00003916 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3917 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003918 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00003919 NumDifferences = 2;
3920 break;
3921 } else {
3922 if (NumDifferences++) break;
3923 DiffOperand = i;
3924 }
3925 }
3926
3927 if (NumDifferences == 0) // SAME GEP?
3928 return ReplaceInstUsesWith(I, // No comparison is needed here.
3929 ConstantBool::get(Cond == Instruction::SetEQ));
3930 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00003931 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3932 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Chris Lattner7911f032005-07-18 23:07:33 +00003933
3934 // Convert the operands to signed values to make sure to perform a
3935 // signed comparison.
3936 const Type *NewTy = LHSV->getType()->getSignedVersion();
3937 if (LHSV->getType() != NewTy)
3938 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3939 LHSV->getName()), I);
3940 if (RHSV->getType() != NewTy)
3941 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3942 RHSV->getName()), I);
3943 return new SetCondInst(Cond, LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00003944 }
3945 }
3946
Chris Lattner574da9b2005-01-13 20:14:25 +00003947 // Only lower this if the setcc is the only user of the GEP or if we expect
3948 // the result to fold to a constant!
3949 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3950 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3951 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3952 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3953 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3954 return new SetCondInst(Cond, L, R);
3955 }
3956 }
3957 return 0;
3958}
3959
3960
Chris Lattner484d3cf2005-04-24 06:59:08 +00003961Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003962 bool Changed = SimplifyCommutative(I);
Chris Lattner8b170942002-08-09 23:47:40 +00003963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3964 const Type *Ty = Op0->getType();
Chris Lattner3f5b8772002-05-06 16:14:14 +00003965
3966 // setcc X, X
Chris Lattner8b170942002-08-09 23:47:40 +00003967 if (Op0 == Op1)
3968 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
Chris Lattner53a5b572002-05-09 20:11:54 +00003969
Chris Lattnere87597f2004-10-16 18:11:37 +00003970 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3971 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3972
Chris Lattner711b3402004-11-14 07:33:16 +00003973 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3974 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00003975 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3976 isa<ConstantPointerNull>(Op0)) &&
3977 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00003978 isa<ConstantPointerNull>(Op1)))
Chris Lattner8b170942002-08-09 23:47:40 +00003979 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3980
3981 // setcc's with boolean values can always be turned into bitwise operations
3982 if (Ty == Type::BoolTy) {
Chris Lattner5dbef222004-08-11 00:50:51 +00003983 switch (I.getOpcode()) {
3984 default: assert(0 && "Invalid setcc instruction!");
3985 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00003986 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00003987 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00003988 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00003989 }
Chris Lattner5dbef222004-08-11 00:50:51 +00003990 case Instruction::SetNE:
3991 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00003992
Chris Lattner5dbef222004-08-11 00:50:51 +00003993 case Instruction::SetGT:
3994 std::swap(Op0, Op1); // Change setgt -> setlt
3995 // FALL THROUGH
3996 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3997 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3998 InsertNewInstBefore(Not, I);
3999 return BinaryOperator::createAnd(Not, Op1);
4000 }
4001 case Instruction::SetGE:
Chris Lattner8b170942002-08-09 23:47:40 +00004002 std::swap(Op0, Op1); // Change setge -> setle
Chris Lattner5dbef222004-08-11 00:50:51 +00004003 // FALL THROUGH
4004 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
4005 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4006 InsertNewInstBefore(Not, I);
4007 return BinaryOperator::createOr(Not, Op1);
4008 }
4009 }
Chris Lattner8b170942002-08-09 23:47:40 +00004010 }
4011
Chris Lattner2be51ae2004-06-09 04:24:29 +00004012 // See if we are doing a comparison between a constant and an instruction that
4013 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004014 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnera96879a2004-09-29 17:40:11 +00004015 // Check to see if we are comparing against the minimum or maximum value...
4016 if (CI->isMinValue()) {
4017 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
Chris Lattner47811b72006-09-28 23:35:22 +00004018 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004019 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
Chris Lattner47811b72006-09-28 23:35:22 +00004020 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004021 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4022 return BinaryOperator::createSetEQ(Op0, Op1);
4023 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4024 return BinaryOperator::createSetNE(Op0, Op1);
4025
4026 } else if (CI->isMaxValue()) {
4027 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
Chris Lattner47811b72006-09-28 23:35:22 +00004028 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004029 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
Chris Lattner47811b72006-09-28 23:35:22 +00004030 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004031 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4032 return BinaryOperator::createSetEQ(Op0, Op1);
4033 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4034 return BinaryOperator::createSetNE(Op0, Op1);
4035
4036 // Comparing against a value really close to min or max?
4037 } else if (isMinValuePlusOne(CI)) {
4038 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4039 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4040 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4041 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4042
4043 } else if (isMaxValueMinusOne(CI)) {
4044 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4045 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4046 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4047 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4048 }
4049
4050 // If we still have a setle or setge instruction, turn it into the
4051 // appropriate setlt or setgt instruction. Since the border cases have
4052 // already been handled above, this requires little checking.
4053 //
4054 if (I.getOpcode() == Instruction::SetLE)
4055 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4056 if (I.getOpcode() == Instruction::SetGE)
4057 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4058
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004059
4060 // See if we can fold the comparison based on bits known to be zero or one
4061 // in the input.
4062 uint64_t KnownZero, KnownOne;
4063 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4064 KnownZero, KnownOne, 0))
4065 return &I;
4066
4067 // Given the known and unknown bits, compute a range that the LHS could be
4068 // in.
4069 if (KnownOne | KnownZero) {
4070 if (Ty->isUnsigned()) { // Unsigned comparison.
4071 uint64_t Min, Max;
4072 uint64_t RHSVal = CI->getZExtValue();
4073 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4074 Min, Max);
4075 switch (I.getOpcode()) { // LE/GE have been folded already.
4076 default: assert(0 && "Unknown setcc opcode!");
4077 case Instruction::SetEQ:
4078 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004079 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004080 break;
4081 case Instruction::SetNE:
4082 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004083 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004084 break;
4085 case Instruction::SetLT:
Chris Lattner47811b72006-09-28 23:35:22 +00004086 if (Max < RHSVal)
4087 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4088 if (Min > RHSVal)
4089 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004090 break;
4091 case Instruction::SetGT:
Chris Lattner47811b72006-09-28 23:35:22 +00004092 if (Min > RHSVal)
4093 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4094 if (Max < RHSVal)
4095 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004096 break;
4097 }
4098 } else { // Signed comparison.
4099 int64_t Min, Max;
4100 int64_t RHSVal = CI->getSExtValue();
4101 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4102 Min, Max);
4103 switch (I.getOpcode()) { // LE/GE have been folded already.
4104 default: assert(0 && "Unknown setcc opcode!");
4105 case Instruction::SetEQ:
4106 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004107 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004108 break;
4109 case Instruction::SetNE:
4110 if (Max < RHSVal || Min > RHSVal)
Chris Lattner47811b72006-09-28 23:35:22 +00004111 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004112 break;
4113 case Instruction::SetLT:
Chris Lattner47811b72006-09-28 23:35:22 +00004114 if (Max < RHSVal)
4115 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4116 if (Min > RHSVal)
4117 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004118 break;
4119 case Instruction::SetGT:
Chris Lattner47811b72006-09-28 23:35:22 +00004120 if (Min > RHSVal)
4121 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4122 if (Max < RHSVal)
4123 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004124 break;
4125 }
4126 }
4127 }
4128
4129
Chris Lattner3c6a0d42004-05-25 06:32:08 +00004130 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner648e3bc2004-09-23 21:52:49 +00004131 switch (LHSI->getOpcode()) {
4132 case Instruction::And:
4133 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4134 LHSI->getOperand(0)->hasOneUse()) {
Chris Lattnere695a3b2006-09-18 05:27:43 +00004135 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4136
4137 // If an operand is an AND of a truncating cast, we can widen the
4138 // and/compare to be the input width without changing the value
4139 // produced, eliminating a cast.
4140 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4141 // We can do this transformation if either the AND constant does not
4142 // have its sign bit set or if it is an equality comparison.
4143 // Extending a relational comparison when we're checking the sign
4144 // bit would not work.
4145 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4146 (I.isEquality() ||
4147 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4148 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4149 ConstantInt *NewCST;
4150 ConstantInt *NewCI;
4151 if (Cast->getOperand(0)->getType()->isSigned()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004152 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004153 AndCST->getZExtValue());
Reid Spencerb83eb642006-10-20 07:07:24 +00004154 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004155 CI->getZExtValue());
4156 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00004157 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004158 AndCST->getZExtValue());
Reid Spencerb83eb642006-10-20 07:07:24 +00004159 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
Chris Lattnere695a3b2006-09-18 05:27:43 +00004160 CI->getZExtValue());
4161 }
4162 Instruction *NewAnd =
4163 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4164 LHSI->getName());
4165 InsertNewInstBefore(NewAnd, I);
4166 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4167 }
4168 }
4169
Chris Lattner648e3bc2004-09-23 21:52:49 +00004170 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4171 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4172 // happens a LOT in code produced by the C front-end, for bitfield
4173 // access.
4174 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004175
4176 // Check to see if there is a noop-cast between the shift and the and.
4177 if (!Shift) {
4178 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4179 if (CI->getOperand(0)->getType()->isIntegral() &&
4180 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4181 CI->getType()->getPrimitiveSizeInBits())
4182 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4183 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00004184
Reid Spencerb83eb642006-10-20 07:07:24 +00004185 ConstantInt *ShAmt;
4186 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004187 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4188 const Type *AndTy = AndCST->getType(); // Type of the and.
Misha Brukmanfd939082005-04-21 23:48:37 +00004189
Chris Lattner648e3bc2004-09-23 21:52:49 +00004190 // We can fold this as long as we can't shift unknown bits
4191 // into the mask. This can only happen with signed shift
4192 // rights, as they sign-extend.
4193 if (ShAmt) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004194 bool CanFold = Shift->isLogicalShift();
Chris Lattner648e3bc2004-09-23 21:52:49 +00004195 if (!CanFold) {
4196 // To test for the bad case of the signed shr, see if any
4197 // of the bits shifted in could be tested after the mask.
Reid Spencerb83eb642006-10-20 07:07:24 +00004198 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
Chris Lattnerd7e31cf2005-06-17 01:29:28 +00004199 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4200
Reid Spencerb83eb642006-10-20 07:07:24 +00004201 Constant *OShAmt = ConstantInt::get(Type::UByteTy, ShAmtVal);
Misha Brukmanfd939082005-04-21 23:48:37 +00004202 Constant *ShVal =
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004203 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4204 OShAmt);
Chris Lattner648e3bc2004-09-23 21:52:49 +00004205 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4206 CanFold = true;
4207 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004208
Chris Lattner648e3bc2004-09-23 21:52:49 +00004209 if (CanFold) {
Chris Lattner0cba71b2004-09-28 17:54:07 +00004210 Constant *NewCst;
4211 if (Shift->getOpcode() == Instruction::Shl)
4212 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4213 else
4214 NewCst = ConstantExpr::getShl(CI, ShAmt);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004215
Chris Lattner648e3bc2004-09-23 21:52:49 +00004216 // Check to see if we are shifting out any of the bits being
4217 // compared.
4218 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4219 // If we shifted bits out, the fold is not going to work out.
4220 // As a special case, check to see if this means that the
4221 // result is always true or false now.
4222 if (I.getOpcode() == Instruction::SetEQ)
Chris Lattner47811b72006-09-28 23:35:22 +00004223 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattner648e3bc2004-09-23 21:52:49 +00004224 if (I.getOpcode() == Instruction::SetNE)
Chris Lattner47811b72006-09-28 23:35:22 +00004225 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattner648e3bc2004-09-23 21:52:49 +00004226 } else {
4227 I.setOperand(1, NewCst);
Chris Lattner0cba71b2004-09-28 17:54:07 +00004228 Constant *NewAndCST;
4229 if (Shift->getOpcode() == Instruction::Shl)
4230 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4231 else
4232 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4233 LHSI->setOperand(1, NewAndCST);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00004234 if (AndTy == Ty)
4235 LHSI->setOperand(0, Shift->getOperand(0));
4236 else {
4237 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4238 *Shift);
4239 LHSI->setOperand(0, NewCast);
4240 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00004241 WorkList.push_back(Shift); // Shift is dead.
4242 AddUsesToWorkList(I);
4243 return &I;
Chris Lattner5eb91942004-07-21 19:50:44 +00004244 }
4245 }
Chris Lattner457dd822004-06-09 07:59:58 +00004246 }
Chris Lattner65b72ba2006-09-18 04:22:48 +00004247
4248 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4249 // preferable because it allows the C<<Y expression to be hoisted out
4250 // of a loop if Y is invariant and X is not.
4251 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
Chris Lattner6d7ca922006-09-18 18:27:05 +00004252 I.isEquality() && !Shift->isArithmeticShift() &&
4253 isa<Instruction>(Shift->getOperand(0))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004254 // Compute C << Y.
4255 Value *NS;
4256 if (Shift->getOpcode() == Instruction::Shr) {
4257 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4258 "tmp");
4259 } else {
4260 // Make sure we insert a logical shift.
Chris Lattnere695a3b2006-09-18 05:27:43 +00004261 Constant *NewAndCST = AndCST;
Chris Lattner65b72ba2006-09-18 04:22:48 +00004262 if (AndCST->getType()->isSigned())
Chris Lattnere695a3b2006-09-18 05:27:43 +00004263 NewAndCST = ConstantExpr::getCast(AndCST,
Chris Lattner65b72ba2006-09-18 04:22:48 +00004264 AndCST->getType()->getUnsignedVersion());
Chris Lattnere695a3b2006-09-18 05:27:43 +00004265 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4266 Shift->getOperand(1), "tmp");
Chris Lattner65b72ba2006-09-18 04:22:48 +00004267 }
4268 InsertNewInstBefore(cast<Instruction>(NS), I);
4269
4270 // If C's sign doesn't agree with the and, insert a cast now.
4271 if (NS->getType() != LHSI->getType())
4272 NS = InsertCastBefore(NS, LHSI->getType(), I);
4273
4274 Value *ShiftOp = Shift->getOperand(0);
4275 if (ShiftOp->getType() != LHSI->getType())
4276 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4277
4278 // Compute X & (C << Y).
4279 Instruction *NewAnd =
4280 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4281 InsertNewInstBefore(NewAnd, I);
4282
4283 I.setOperand(0, NewAnd);
4284 return &I;
4285 }
Chris Lattner648e3bc2004-09-23 21:52:49 +00004286 }
4287 break;
Chris Lattner83c4ec02004-09-27 19:29:18 +00004288
Chris Lattner18d19ca2004-09-28 18:22:15 +00004289 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
Reid Spencerb83eb642006-10-20 07:07:24 +00004290 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004291 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004292 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4293
4294 // Check that the shift amount is in range. If not, don't perform
4295 // undefined shifts. When the shift is visited it will be
4296 // simplified.
Reid Spencerb83eb642006-10-20 07:07:24 +00004297 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004298 break;
4299
Chris Lattner18d19ca2004-09-28 18:22:15 +00004300 // If we are comparing against bits always shifted out, the
4301 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00004302 Constant *Comp =
Chris Lattner18d19ca2004-09-28 18:22:15 +00004303 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4304 if (Comp != CI) {// Comparing against a bit that we know is zero.
4305 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4306 Constant *Cst = ConstantBool::get(IsSetNE);
4307 return ReplaceInstUsesWith(I, Cst);
4308 }
4309
4310 if (LHSI->hasOneUse()) {
4311 // Otherwise strength reduce the shift into an and.
Reid Spencerb83eb642006-10-20 07:07:24 +00004312 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004313 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4314
4315 Constant *Mask;
4316 if (CI->getType()->isUnsigned()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004317 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004318 } else if (ShAmtVal != 0) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004319 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattner18d19ca2004-09-28 18:22:15 +00004320 } else {
4321 Mask = ConstantInt::getAllOnesValue(CI->getType());
4322 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004323
Chris Lattner18d19ca2004-09-28 18:22:15 +00004324 Instruction *AndI =
4325 BinaryOperator::createAnd(LHSI->getOperand(0),
4326 Mask, LHSI->getName()+".mask");
4327 Value *And = InsertNewInstBefore(AndI, I);
4328 return new SetCondInst(I.getOpcode(), And,
4329 ConstantExpr::getUShr(CI, ShAmt));
4330 }
4331 }
Chris Lattner18d19ca2004-09-28 18:22:15 +00004332 }
4333 break;
4334
Chris Lattner83c4ec02004-09-27 19:29:18 +00004335 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
Reid Spencerb83eb642006-10-20 07:07:24 +00004336 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
Chris Lattner65b72ba2006-09-18 04:22:48 +00004337 if (I.isEquality()) {
Chris Lattnere17a1282005-06-15 20:53:31 +00004338 // Check that the shift amount is in range. If not, don't perform
4339 // undefined shifts. When the shift is visited it will be
4340 // simplified.
Chris Lattneraa457ac2005-06-16 01:52:07 +00004341 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00004342 if (ShAmt->getZExtValue() >= TypeBits)
Chris Lattnere17a1282005-06-15 20:53:31 +00004343 break;
4344
Chris Lattnerf63f6472004-09-27 16:18:50 +00004345 // If we are comparing against bits always shifted out, the
4346 // comparison cannot succeed.
Misha Brukmanfd939082005-04-21 23:48:37 +00004347 Constant *Comp =
Chris Lattnerf63f6472004-09-27 16:18:50 +00004348 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
Misha Brukmanfd939082005-04-21 23:48:37 +00004349
Chris Lattnerf63f6472004-09-27 16:18:50 +00004350 if (Comp != CI) {// Comparing against a bit that we know is zero.
4351 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4352 Constant *Cst = ConstantBool::get(IsSetNE);
4353 return ReplaceInstUsesWith(I, Cst);
4354 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004355
Chris Lattnerf63f6472004-09-27 16:18:50 +00004356 if (LHSI->hasOneUse() || CI->isNullValue()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004357 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
Chris Lattner18d19ca2004-09-28 18:22:15 +00004358
Chris Lattnerf63f6472004-09-27 16:18:50 +00004359 // Otherwise strength reduce the shift into an and.
4360 uint64_t Val = ~0ULL; // All ones.
4361 Val <<= ShAmtVal; // Shift over to the right spot.
4362
4363 Constant *Mask;
4364 if (CI->getType()->isUnsigned()) {
Chris Lattnerf52d6812005-04-24 17:46:05 +00004365 Val &= ~0ULL >> (64-TypeBits);
Reid Spencerb83eb642006-10-20 07:07:24 +00004366 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattnerf63f6472004-09-27 16:18:50 +00004367 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00004368 Mask = ConstantInt::get(CI->getType(), Val);
Chris Lattnerf63f6472004-09-27 16:18:50 +00004369 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004370
Chris Lattnerf63f6472004-09-27 16:18:50 +00004371 Instruction *AndI =
4372 BinaryOperator::createAnd(LHSI->getOperand(0),
4373 Mask, LHSI->getName()+".mask");
4374 Value *And = InsertNewInstBefore(AndI, I);
4375 return new SetCondInst(I.getOpcode(), And,
4376 ConstantExpr::getShl(CI, ShAmt));
4377 }
Chris Lattnerf63f6472004-09-27 16:18:50 +00004378 }
4379 }
4380 break;
Chris Lattner0c967662004-09-24 15:21:34 +00004381
Chris Lattnera96879a2004-09-29 17:40:11 +00004382 case Instruction::Div:
4383 // Fold: (div X, C1) op C2 -> range check
4384 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4385 // Fold this div into the comparison, producing a range check.
4386 // Determine, based on the divide type, what the range is being
4387 // checked. If there is an overflow on the low or high side, remember
4388 // it, otherwise compute the range [low, hi) bounding the new value.
4389 bool LoOverflow = false, HiOverflow = 0;
4390 ConstantInt *LoBound = 0, *HiBound = 0;
4391
4392 ConstantInt *Prod;
4393 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4394
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004395 Instruction::BinaryOps Opcode = I.getOpcode();
4396
Chris Lattnera96879a2004-09-29 17:40:11 +00004397 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4398 } else if (LHSI->getType()->isUnsigned()) { // udiv
4399 LoBound = Prod;
4400 LoOverflow = ProdOV;
4401 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4402 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4403 if (CI->isNullValue()) { // (X / pos) op 0
4404 // Can't overflow.
4405 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4406 HiBound = DivRHS;
4407 } else if (isPositive(CI)) { // (X / pos) op pos
4408 LoBound = Prod;
4409 LoOverflow = ProdOV;
4410 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4411 } else { // (X / pos) op neg
4412 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4413 LoOverflow = AddWithOverflow(LoBound, Prod,
4414 cast<ConstantInt>(DivRHSH));
4415 HiBound = Prod;
4416 HiOverflow = ProdOV;
4417 }
4418 } else { // Divisor is < 0.
4419 if (CI->isNullValue()) { // (X / neg) op 0
4420 LoBound = AddOne(DivRHS);
4421 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner56625032005-06-17 02:05:55 +00004422 if (HiBound == DivRHS)
4423 LoBound = 0; // - INTMIN = INTMIN
Chris Lattnera96879a2004-09-29 17:40:11 +00004424 } else if (isPositive(CI)) { // (X / neg) op pos
4425 HiOverflow = LoOverflow = ProdOV;
4426 if (!LoOverflow)
4427 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4428 HiBound = AddOne(Prod);
4429 } else { // (X / neg) op neg
4430 LoBound = Prod;
4431 LoOverflow = HiOverflow = ProdOV;
4432 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4433 }
Chris Lattner340a05f2004-10-08 19:15:44 +00004434
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004435 // Dividing by a negate swaps the condition.
4436 Opcode = SetCondInst::getSwappedCondition(Opcode);
Chris Lattnera96879a2004-09-29 17:40:11 +00004437 }
4438
4439 if (LoBound) {
4440 Value *X = LHSI->getOperand(0);
Chris Lattner6a9fdfa2004-10-11 19:40:04 +00004441 switch (Opcode) {
Chris Lattnera96879a2004-09-29 17:40:11 +00004442 default: assert(0 && "Unhandled setcc opcode!");
4443 case Instruction::SetEQ:
4444 if (LoOverflow && HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004445 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004446 else if (HiOverflow)
4447 return new SetCondInst(Instruction::SetGE, X, LoBound);
4448 else if (LoOverflow)
4449 return new SetCondInst(Instruction::SetLT, X, HiBound);
4450 else
4451 return InsertRangeTest(X, LoBound, HiBound, true, I);
4452 case Instruction::SetNE:
4453 if (LoOverflow && HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004454 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004455 else if (HiOverflow)
4456 return new SetCondInst(Instruction::SetLT, X, LoBound);
4457 else if (LoOverflow)
4458 return new SetCondInst(Instruction::SetGE, X, HiBound);
4459 else
4460 return InsertRangeTest(X, LoBound, HiBound, false, I);
4461 case Instruction::SetLT:
4462 if (LoOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004463 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004464 return new SetCondInst(Instruction::SetLT, X, LoBound);
4465 case Instruction::SetGT:
4466 if (HiOverflow)
Chris Lattner47811b72006-09-28 23:35:22 +00004467 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
Chris Lattnera96879a2004-09-29 17:40:11 +00004468 return new SetCondInst(Instruction::SetGE, X, HiBound);
4469 }
4470 }
4471 }
4472 break;
Chris Lattner648e3bc2004-09-23 21:52:49 +00004473 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004474
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004475 // Simplify seteq and setne instructions...
Chris Lattner65b72ba2006-09-18 04:22:48 +00004476 if (I.isEquality()) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004477 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4478
Reid Spencerb83eb642006-10-20 07:07:24 +00004479 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4480 // the second operand is a constant, simplify a bit.
Chris Lattner934754b2003-08-13 05:33:12 +00004481 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4482 switch (BO->getOpcode()) {
Reid Spencerb83eb642006-10-20 07:07:24 +00004483#if 0
4484 case Instruction::SRem:
4485 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4486 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4487 BO->hasOneUse()) {
4488 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4489 if (V > 1 && isPowerOf2_64(V)) {
4490 Value *NewRem = InsertNewInstBefore(
4491 BinaryOperator::createURem(BO->getOperand(0),
4492 BO->getOperand(1),
4493 BO->getName()), I);
4494 return BinaryOperator::create(
4495 I.getOpcode(), NewRem,
4496 Constant::getNullValue(NewRem->getType()));
4497 }
4498 }
4499 break;
4500#endif
4501
Chris Lattner3571b722004-07-06 07:38:18 +00004502 case Instruction::Rem:
4503 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
Reid Spencerb83eb642006-10-20 07:07:24 +00004504 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4505 BO->hasOneUse() && BO->getOperand(1)->getType()->isSigned()) {
4506 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4507 if (V > 1 && isPowerOf2_64(V)) {
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004508 unsigned L2 = Log2_64(V);
Chris Lattner3571b722004-07-06 07:38:18 +00004509 const Type *UTy = BO->getType()->getUnsignedVersion();
4510 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4511 UTy, "tmp"), I);
Reid Spencerb83eb642006-10-20 07:07:24 +00004512 Constant *RHSCst = ConstantInt::get(UTy, 1ULL << L2);
Chris Lattner3571b722004-07-06 07:38:18 +00004513 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4514 RHSCst, BO->getName()), I);
4515 return BinaryOperator::create(I.getOpcode(), NewRem,
4516 Constant::getNullValue(UTy));
4517 }
Chris Lattnerbcd7db52005-08-02 19:16:58 +00004518 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004519 break;
Chris Lattner934754b2003-08-13 05:33:12 +00004520 case Instruction::Add:
Chris Lattner15d58b62004-06-27 22:51:36 +00004521 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4522 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattner3d834bf2004-09-21 21:35:23 +00004523 if (BO->hasOneUse())
4524 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4525 ConstantExpr::getSub(CI, BOp1C));
Chris Lattner15d58b62004-06-27 22:51:36 +00004526 } else if (CI->isNullValue()) {
Chris Lattner934754b2003-08-13 05:33:12 +00004527 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4528 // efficiently invertible, or if the add has just this one use.
4529 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004530
Chris Lattner934754b2003-08-13 05:33:12 +00004531 if (Value *NegVal = dyn_castNegVal(BOp1))
4532 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4533 else if (Value *NegVal = dyn_castNegVal(BOp0))
4534 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
Chris Lattnerfd059242003-10-15 16:48:29 +00004535 else if (BO->hasOneUse()) {
Chris Lattner934754b2003-08-13 05:33:12 +00004536 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4537 BO->setName("");
4538 InsertNewInstBefore(Neg, I);
4539 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4540 }
4541 }
4542 break;
4543 case Instruction::Xor:
4544 // For the xor case, we can xor two constants together, eliminating
4545 // the explicit xor.
4546 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4547 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
Chris Lattner48595f12004-06-10 02:07:29 +00004548 ConstantExpr::getXor(CI, BOC));
Chris Lattner934754b2003-08-13 05:33:12 +00004549
4550 // FALLTHROUGH
4551 case Instruction::Sub:
4552 // Replace (([sub|xor] A, B) != 0) with (A != B)
4553 if (CI->isNullValue())
4554 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4555 BO->getOperand(1));
4556 break;
4557
4558 case Instruction::Or:
4559 // If bits are being or'd in that are not present in the constant we
4560 // are comparing against, then the comparison could never succeed!
Chris Lattner7c4049c2004-01-12 19:35:11 +00004561 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Chris Lattner448c3232004-06-10 02:12:35 +00004562 Constant *NotCI = ConstantExpr::getNot(CI);
Chris Lattner48595f12004-06-10 02:07:29 +00004563 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004564 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner7c4049c2004-01-12 19:35:11 +00004565 }
Chris Lattner934754b2003-08-13 05:33:12 +00004566 break;
4567
4568 case Instruction::And:
4569 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004570 // If bits are being compared against that are and'd out, then the
4571 // comparison can never succeed!
Chris Lattner448c3232004-06-10 02:12:35 +00004572 if (!ConstantExpr::getAnd(CI,
4573 ConstantExpr::getNot(BOC))->isNullValue())
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004574 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
Chris Lattner934754b2003-08-13 05:33:12 +00004575
Chris Lattner457dd822004-06-09 07:59:58 +00004576 // If we have ((X & C) == C), turn it into ((X & C) != 0).
Chris Lattner3285a6f2004-06-10 02:33:20 +00004577 if (CI == BOC && isOneBitSet(CI))
Chris Lattner457dd822004-06-09 07:59:58 +00004578 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4579 Instruction::SetNE, Op0,
4580 Constant::getNullValue(CI->getType()));
Chris Lattner457dd822004-06-09 07:59:58 +00004581
Chris Lattner934754b2003-08-13 05:33:12 +00004582 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4583 // to be a signed value as appropriate.
4584 if (isSignBit(BOC)) {
4585 Value *X = BO->getOperand(0);
4586 // If 'X' is not signed, insert a cast now...
4587 if (!BOC->getType()->isSigned()) {
Chris Lattner5dd04022004-06-17 18:16:02 +00004588 const Type *DestTy = BOC->getType()->getSignedVersion();
Chris Lattner83c4ec02004-09-27 19:29:18 +00004589 X = InsertCastBefore(X, DestTy, I);
Chris Lattner934754b2003-08-13 05:33:12 +00004590 }
4591 return new SetCondInst(isSetNE ? Instruction::SetLT :
4592 Instruction::SetGE, X,
4593 Constant::getNullValue(X->getType()));
4594 }
Misha Brukmanfd939082005-04-21 23:48:37 +00004595
Chris Lattner83c4ec02004-09-27 19:29:18 +00004596 // ((X & ~7) == 0) --> X < 8
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004597 if (CI->isNullValue() && isHighOnes(BOC)) {
4598 Value *X = BO->getOperand(0);
Chris Lattner83c4ec02004-09-27 19:29:18 +00004599 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004600
4601 // If 'X' is signed, insert a cast now.
Chris Lattner83c4ec02004-09-27 19:29:18 +00004602 if (NegX->getType()->isSigned()) {
4603 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4604 X = InsertCastBefore(X, DestTy, I);
4605 NegX = ConstantExpr::getCast(NegX, DestTy);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004606 }
4607
4608 return new SetCondInst(isSetNE ? Instruction::SetGE :
Chris Lattner83c4ec02004-09-27 19:29:18 +00004609 Instruction::SetLT, X, NegX);
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00004610 }
4611
Chris Lattnerbc5d4142003-07-23 17:02:11 +00004612 }
Chris Lattner934754b2003-08-13 05:33:12 +00004613 default: break;
4614 }
4615 }
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004616 } else { // Not a SetEQ/SetNE
Misha Brukmanfd939082005-04-21 23:48:37 +00004617 // If the LHS is a cast from an integral value of the same size,
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004618 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4619 Value *CastOp = Cast->getOperand(0);
4620 const Type *SrcTy = CastOp->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004621 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004622 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
Chris Lattner484d3cf2005-04-24 06:59:08 +00004623 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
Misha Brukmanfd939082005-04-21 23:48:37 +00004624 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004625 "Source and destination signednesses should differ!");
4626 if (Cast->getType()->isSigned()) {
4627 // If this is a signed comparison, check for comparisons in the
4628 // vicinity of zero.
4629 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4630 // X < 0 => x > 127
Chris Lattner48595f12004-06-10 02:07:29 +00004631 return BinaryOperator::createSetGT(CastOp,
Reid Spencerb83eb642006-10-20 07:07:24 +00004632 ConstantInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004633 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00004634 cast<ConstantInt>(CI)->getSExtValue() == -1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004635 // X > -1 => x < 128
Chris Lattner48595f12004-06-10 02:07:29 +00004636 return BinaryOperator::createSetLT(CastOp,
Reid Spencerb83eb642006-10-20 07:07:24 +00004637 ConstantInt::get(SrcTy, 1ULL << (SrcTySize-1)));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004638 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00004639 ConstantInt *CUI = cast<ConstantInt>(CI);
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004640 if (I.getOpcode() == Instruction::SetLT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00004641 CUI->getZExtValue() == 1ULL << (SrcTySize-1))
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004642 // X < 128 => X > -1
Chris Lattner48595f12004-06-10 02:07:29 +00004643 return BinaryOperator::createSetGT(CastOp,
Reid Spencerb83eb642006-10-20 07:07:24 +00004644 ConstantInt::get(SrcTy, -1));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004645 else if (I.getOpcode() == Instruction::SetGT &&
Reid Spencerb83eb642006-10-20 07:07:24 +00004646 CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004647 // X > 127 => X < 0
Chris Lattner48595f12004-06-10 02:07:29 +00004648 return BinaryOperator::createSetLT(CastOp,
4649 Constant::getNullValue(SrcTy));
Chris Lattnerc5943fb2004-02-23 07:16:20 +00004650 }
4651 }
4652 }
Chris Lattner40f5d702003-06-04 05:10:11 +00004653 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004654 }
4655
Chris Lattner6970b662005-04-23 15:31:55 +00004656 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4657 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4658 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4659 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00004660 case Instruction::GetElementPtr:
4661 if (RHSC->isNullValue()) {
4662 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4663 bool isAllZeros = true;
4664 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4665 if (!isa<Constant>(LHSI->getOperand(i)) ||
4666 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4667 isAllZeros = false;
4668 break;
4669 }
4670 if (isAllZeros)
4671 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4672 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4673 }
4674 break;
4675
Chris Lattner6970b662005-04-23 15:31:55 +00004676 case Instruction::PHI:
4677 if (Instruction *NV = FoldOpIntoPhi(I))
4678 return NV;
4679 break;
4680 case Instruction::Select:
4681 // If either operand of the select is a constant, we can fold the
4682 // comparison into the select arms, which will cause one to be
4683 // constant folded and the select turned into a bitwise or.
4684 Value *Op1 = 0, *Op2 = 0;
4685 if (LHSI->hasOneUse()) {
4686 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4687 // Fold the known value into the constant operand.
4688 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4689 // Insert a new SetCC of the other select operand.
4690 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4691 LHSI->getOperand(2), RHSC,
4692 I.getName()), I);
4693 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4694 // Fold the known value into the constant operand.
4695 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4696 // Insert a new SetCC of the other select operand.
4697 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4698 LHSI->getOperand(1), RHSC,
4699 I.getName()), I);
4700 }
4701 }
Jeff Cohen9d809302005-04-23 21:38:35 +00004702
Chris Lattner6970b662005-04-23 15:31:55 +00004703 if (Op1)
4704 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4705 break;
4706 }
4707 }
4708
Chris Lattner574da9b2005-01-13 20:14:25 +00004709 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4710 if (User *GEP = dyn_castGetElementPtr(Op0))
4711 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4712 return NI;
4713 if (User *GEP = dyn_castGetElementPtr(Op1))
4714 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4715 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4716 return NI;
4717
Chris Lattnerde90b762003-11-03 04:25:02 +00004718 // Test to see if the operands of the setcc are casted versions of other
4719 // values. If the cast can be stripped off both arguments, we do so now.
Chris Lattner68708052003-11-03 05:17:03 +00004720 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4721 Value *CastOp0 = CI->getOperand(0);
4722 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
Chris Lattner65b72ba2006-09-18 04:22:48 +00004723 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00004724 // We keep moving the cast from the left operand over to the right
4725 // operand, where it can often be eliminated completely.
Chris Lattner68708052003-11-03 05:17:03 +00004726 Op0 = CastOp0;
Misha Brukmanfd939082005-04-21 23:48:37 +00004727
Chris Lattnerde90b762003-11-03 04:25:02 +00004728 // If operand #1 is a cast instruction, see if we can eliminate it as
4729 // well.
Chris Lattner68708052003-11-03 05:17:03 +00004730 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4731 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
Chris Lattnerde90b762003-11-03 04:25:02 +00004732 Op0->getType()))
Chris Lattner68708052003-11-03 05:17:03 +00004733 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00004734
Chris Lattnerde90b762003-11-03 04:25:02 +00004735 // If Op1 is a constant, we can fold the cast into the constant.
4736 if (Op1->getType() != Op0->getType())
4737 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4738 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4739 } else {
4740 // Otherwise, cast the RHS right before the setcc
4741 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4742 InsertNewInstBefore(cast<Instruction>(Op1), I);
4743 }
4744 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4745 }
4746
Chris Lattner68708052003-11-03 05:17:03 +00004747 // Handle the special case of: setcc (cast bool to X), <cst>
4748 // This comes up when you have code like
4749 // int X = A < B;
4750 // if (X) ...
4751 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00004752 // with a constant or another cast from the same type.
4753 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4754 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4755 return R;
Chris Lattner68708052003-11-03 05:17:03 +00004756 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00004757
Chris Lattner65b72ba2006-09-18 04:22:48 +00004758 if (I.isEquality()) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00004759 Value *A, *B;
4760 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4761 (A == Op1 || B == Op1)) {
4762 // (A^B) == A -> B == 0
4763 Value *OtherVal = A == Op1 ? B : A;
4764 return BinaryOperator::create(I.getOpcode(), OtherVal,
4765 Constant::getNullValue(A->getType()));
4766 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4767 (A == Op0 || B == Op0)) {
4768 // A == (A^B) -> B == 0
4769 Value *OtherVal = A == Op0 ? B : A;
4770 return BinaryOperator::create(I.getOpcode(), OtherVal,
4771 Constant::getNullValue(A->getType()));
4772 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4773 // (A-B) == A -> B == 0
4774 return BinaryOperator::create(I.getOpcode(), B,
4775 Constant::getNullValue(B->getType()));
4776 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4777 // A == (A-B) -> B == 0
4778 return BinaryOperator::create(I.getOpcode(), B,
4779 Constant::getNullValue(B->getType()));
4780 }
4781 }
Chris Lattner7e708292002-06-25 16:13:24 +00004782 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004783}
4784
Chris Lattner484d3cf2005-04-24 06:59:08 +00004785// visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4786// We only handle extending casts so far.
4787//
4788Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4789 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4790 const Type *SrcTy = LHSCIOp->getType();
4791 const Type *DestTy = SCI.getOperand(0)->getType();
4792 Value *RHSCIOp;
4793
4794 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
Chris Lattnerb352fa52005-01-17 03:20:02 +00004795 return 0;
4796
Chris Lattner484d3cf2005-04-24 06:59:08 +00004797 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4798 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4799 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4800
4801 // Is this a sign or zero extension?
4802 bool isSignSrc = SrcTy->isSigned();
4803 bool isSignDest = DestTy->isSigned();
4804
4805 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4806 // Not an extension from the same type?
4807 RHSCIOp = CI->getOperand(0);
4808 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4809 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4810 // Compute the constant that would happen if we truncated to SrcTy then
4811 // reextended to DestTy.
4812 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4813
4814 if (ConstantExpr::getCast(Res, DestTy) == CI) {
Devang Patel6ce890b2006-10-19 18:54:08 +00004815 // Make sure that src sign and dest sign match. For example,
4816 //
4817 // %A = cast short %X to uint
4818 // %B = setgt uint %A, 1330
4819 //
Devang Pateldf308fa2006-10-19 19:21:36 +00004820 // It is incorrect to transform this into
Devang Patel6ce890b2006-10-19 18:54:08 +00004821 //
4822 // %B = setgt short %X, 1330
4823 //
4824 // because %A may have negative value.
Devang Patel002e4992006-10-19 20:59:13 +00004825 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
4826 // OR operation is EQ/NE.
4827 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy || SCI.isEquality())
Devang Patel6ce890b2006-10-19 18:54:08 +00004828 RHSCIOp = Res;
4829 else
4830 return 0;
Chris Lattner484d3cf2005-04-24 06:59:08 +00004831 } else {
4832 // If the value cannot be represented in the shorter type, we cannot emit
4833 // a simple comparison.
4834 if (SCI.getOpcode() == Instruction::SetEQ)
Chris Lattner47811b72006-09-28 23:35:22 +00004835 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
Chris Lattner484d3cf2005-04-24 06:59:08 +00004836 if (SCI.getOpcode() == Instruction::SetNE)
Chris Lattner47811b72006-09-28 23:35:22 +00004837 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
Chris Lattner484d3cf2005-04-24 06:59:08 +00004838
Chris Lattner484d3cf2005-04-24 06:59:08 +00004839 // Evaluate the comparison for LT.
4840 Value *Result;
4841 if (DestTy->isSigned()) {
4842 // We're performing a signed comparison.
4843 if (isSignSrc) {
4844 // Signed extend and signed comparison.
Reid Spencerb83eb642006-10-20 07:07:24 +00004845 if (cast<ConstantInt>(CI)->getSExtValue() < 0)// X < (small) --> false
Chris Lattner47811b72006-09-28 23:35:22 +00004846 Result = ConstantBool::getFalse();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004847 else
Reid Spencerb83eb642006-10-20 07:07:24 +00004848 Result = ConstantBool::getTrue(); // X < (large) --> true
Chris Lattner484d3cf2005-04-24 06:59:08 +00004849 } else {
4850 // Unsigned extend and signed comparison.
Reid Spencerb83eb642006-10-20 07:07:24 +00004851 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
Chris Lattner47811b72006-09-28 23:35:22 +00004852 Result = ConstantBool::getFalse();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004853 else
Chris Lattner47811b72006-09-28 23:35:22 +00004854 Result = ConstantBool::getTrue();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004855 }
4856 } else {
4857 // We're performing an unsigned comparison.
4858 if (!isSignSrc) {
4859 // Unsigned extend & compare -> always true.
Chris Lattner47811b72006-09-28 23:35:22 +00004860 Result = ConstantBool::getTrue();
Chris Lattner484d3cf2005-04-24 06:59:08 +00004861 } else {
4862 // We're performing an unsigned comp with a sign extended value.
4863 // This is true if the input is >= 0. [aka >s -1]
4864 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4865 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4866 NegOne, SCI.getName()), SCI);
4867 }
Reid Spencer6731d5c2004-11-28 21:31:15 +00004868 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004869
Jeff Cohen00b168892005-07-27 06:12:32 +00004870 // Finally, return the value computed.
Chris Lattner484d3cf2005-04-24 06:59:08 +00004871 if (SCI.getOpcode() == Instruction::SetLT) {
4872 return ReplaceInstUsesWith(SCI, Result);
4873 } else {
4874 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4875 if (Constant *CI = dyn_cast<Constant>(Result))
4876 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4877 else
4878 return BinaryOperator::createNot(Result);
4879 }
Chris Lattnerb352fa52005-01-17 03:20:02 +00004880 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00004881 } else {
4882 return 0;
Reid Spencer6731d5c2004-11-28 21:31:15 +00004883 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004884
Chris Lattner8d7089e2005-06-16 03:00:08 +00004885 // Okay, just insert a compare of the reduced operands now!
Chris Lattner484d3cf2005-04-24 06:59:08 +00004886 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4887}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004888
Chris Lattnerea340052003-03-10 19:16:08 +00004889Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00004890 assert(I.getOperand(1)->getType() == Type::UByteTy);
4891 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdf17af12003-08-12 21:53:41 +00004892 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004893
4894 // shl X, 0 == X and shr X, 0 == X
4895 // shl 0, X == 0 and shr 0, X == 0
4896 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00004897 Op0 == Constant::getNullValue(Op0->getType()))
4898 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004899
Chris Lattnere87597f2004-10-16 18:11:37 +00004900 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4901 if (!isLeftShift && I.getType()->isSigned())
Chris Lattner79a564c2004-10-16 23:28:04 +00004902 return ReplaceInstUsesWith(I, Op0);
Chris Lattnere87597f2004-10-16 18:11:37 +00004903 else // undef << X -> 0 AND undef >>u X -> 0
4904 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4905 }
4906 if (isa<UndefValue>(Op1)) {
Chris Lattnerf9944f12005-07-20 18:49:28 +00004907 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00004908 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4909 else
4910 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4911 }
4912
Chris Lattnerdf17af12003-08-12 21:53:41 +00004913 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4914 if (!isLeftShift)
Reid Spencerb83eb642006-10-20 07:07:24 +00004915 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Chris Lattner87d84292006-10-20 18:20:21 +00004916 if (CSI->isAllOnesValue() && Op0->getType()->isSigned())
Chris Lattnerdf17af12003-08-12 21:53:41 +00004917 return ReplaceInstUsesWith(I, CSI);
4918
Chris Lattner2eefe512004-04-09 19:05:30 +00004919 // Try to fold constant and into select arguments.
4920 if (isa<Constant>(Op0))
4921 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004922 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004923 return R;
4924
Chris Lattner120347e2005-05-08 17:34:56 +00004925 // See if we can turn a signed shr into an unsigned shr.
Chris Lattner65b72ba2006-09-18 04:22:48 +00004926 if (I.isArithmeticShift()) {
Chris Lattner3bedbd92006-02-07 07:27:52 +00004927 if (MaskedValueIsZero(Op0,
4928 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
Chris Lattner120347e2005-05-08 17:34:56 +00004929 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4930 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4931 I.getName()), I);
4932 return new CastInst(V, I.getType());
4933 }
4934 }
Jeff Cohen00b168892005-07-27 06:12:32 +00004935
Reid Spencerb83eb642006-10-20 07:07:24 +00004936 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
4937 if (CUI->getType()->isUnsigned())
4938 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4939 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004940 return 0;
4941}
4942
Reid Spencerb83eb642006-10-20 07:07:24 +00004943Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Chris Lattner4d5542c2006-01-06 07:12:35 +00004944 ShiftInst &I) {
4945 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner830ed032006-01-06 07:22:22 +00004946 bool isSignedShift = Op0->getType()->isSigned();
4947 bool isUnsignedShift = !isSignedShift;
Chris Lattner4d5542c2006-01-06 07:12:35 +00004948
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00004949 // See if we can simplify any instructions used by the instruction whose sole
4950 // purpose is to compute bits we don't care about.
4951 uint64_t KnownZero, KnownOne;
4952 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4953 KnownZero, KnownOne))
4954 return &I;
4955
Chris Lattner4d5542c2006-01-06 07:12:35 +00004956 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4957 // of a signed value.
4958 //
4959 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00004960 if (Op1->getZExtValue() >= TypeBits) {
Chris Lattner830ed032006-01-06 07:22:22 +00004961 if (isUnsignedShift || isLeftShift)
Chris Lattner4d5542c2006-01-06 07:12:35 +00004962 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4963 else {
Reid Spencerb83eb642006-10-20 07:07:24 +00004964 I.setOperand(1, ConstantInt::get(Type::UByteTy, TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00004965 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00004966 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00004967 }
4968
4969 // ((X*C1) << C2) == (X * (C1 << C2))
4970 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4971 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4972 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4973 return BinaryOperator::createMul(BO->getOperand(0),
4974 ConstantExpr::getShl(BOOp, Op1));
4975
4976 // Try to fold constant and into select arguments.
4977 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4978 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4979 return R;
4980 if (isa<PHINode>(Op0))
4981 if (Instruction *NV = FoldOpIntoPhi(I))
4982 return NV;
4983
4984 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00004985 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4986 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4987 Value *V1, *V2;
4988 ConstantInt *CC;
4989 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00004990 default: break;
4991 case Instruction::Add:
4992 case Instruction::And:
4993 case Instruction::Or:
4994 case Instruction::Xor:
4995 // These operators commute.
4996 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00004997 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4998 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00004999 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005000 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005001 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005002 Op0BO->getName());
5003 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005004 Instruction *X =
5005 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5006 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005007 InsertNewInstBefore(X, I); // (X + (Y << C))
5008 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005009 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005010 return BinaryOperator::createAnd(X, C2);
5011 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005012
Chris Lattner150f12a2005-09-18 06:30:59 +00005013 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5014 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5015 match(Op0BO->getOperand(1),
5016 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005017 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005018 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005019 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005020 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005021 Op0BO->getName());
5022 InsertNewInstBefore(YS, I); // (Y << C)
5023 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005024 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005025 V1->getName()+".mask");
5026 InsertNewInstBefore(XM, I); // X & (CC << C)
5027
5028 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5029 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005030
Chris Lattner150f12a2005-09-18 06:30:59 +00005031 // FALL THROUGH.
Chris Lattner11021cb2005-09-18 05:12:10 +00005032 case Instruction::Sub:
5033 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005034 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5035 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005036 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005037 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005038 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005039 Op0BO->getName());
5040 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005041 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00005042 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005043 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00005044 InsertNewInstBefore(X, I); // (X + (Y << C))
5045 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
Chris Lattner4d5542c2006-01-06 07:12:35 +00005046 C2 = ConstantExpr::getShl(C2, Op1);
Chris Lattner150f12a2005-09-18 06:30:59 +00005047 return BinaryOperator::createAnd(X, C2);
5048 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005049
Chris Lattner13d4ab42006-05-31 21:14:00 +00005050 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00005051 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5052 match(Op0BO->getOperand(0),
5053 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00005054 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00005055 cast<BinaryOperator>(Op0BO->getOperand(0))
5056 ->getOperand(0)->hasOneUse()) {
Chris Lattner150f12a2005-09-18 06:30:59 +00005057 Instruction *YS = new ShiftInst(Instruction::Shl,
Chris Lattner4d5542c2006-01-06 07:12:35 +00005058 Op0BO->getOperand(1), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00005059 Op0BO->getName());
5060 InsertNewInstBefore(YS, I); // (Y << C)
5061 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00005062 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00005063 V1->getName()+".mask");
5064 InsertNewInstBefore(XM, I); // X & (CC << C)
5065
Chris Lattner13d4ab42006-05-31 21:14:00 +00005066 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00005067 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00005068
Chris Lattner11021cb2005-09-18 05:12:10 +00005069 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005070 }
5071
5072
5073 // If the operand is an bitwise operator with a constant RHS, and the
5074 // shift is the only use, we can pull it out of the shift.
5075 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5076 bool isValid = true; // Valid only for And, Or, Xor
5077 bool highBitSet = false; // Transform if high bit of constant set?
5078
5079 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00005080 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00005081 case Instruction::Add:
5082 isValid = isLeftShift;
5083 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00005084 case Instruction::Or:
5085 case Instruction::Xor:
5086 highBitSet = false;
5087 break;
5088 case Instruction::And:
5089 highBitSet = true;
5090 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005091 }
5092
5093 // If this is a signed shift right, and the high bit is modified
5094 // by the logical operation, do not perform the transformation.
5095 // The highBitSet boolean indicates the value of the high bit of
5096 // the constant which would cause it to be modified for this
5097 // operation.
5098 //
Chris Lattner830ed032006-01-06 07:22:22 +00005099 if (isValid && !isLeftShift && isSignedShift) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005100 uint64_t Val = Op0C->getZExtValue();
Chris Lattner4d5542c2006-01-06 07:12:35 +00005101 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5102 }
5103
5104 if (isValid) {
5105 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5106
5107 Instruction *NewShift =
5108 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5109 Op0BO->getName());
5110 Op0BO->setName("");
5111 InsertNewInstBefore(NewShift, I);
5112
5113 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5114 NewRHS);
5115 }
5116 }
5117 }
5118 }
5119
Chris Lattnerad0124c2006-01-06 07:52:12 +00005120 // Find out if this is a shift of a shift by a constant.
5121 ShiftInst *ShiftOp = 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005122 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
Chris Lattnerad0124c2006-01-06 07:52:12 +00005123 ShiftOp = Op0SI;
5124 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5125 // If this is a noop-integer case of a shift instruction, use the shift.
5126 if (CI->getOperand(0)->getType()->isInteger() &&
5127 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5128 CI->getType()->getPrimitiveSizeInBits() &&
5129 isa<ShiftInst>(CI->getOperand(0))) {
5130 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5131 }
5132 }
5133
Reid Spencerb83eb642006-10-20 07:07:24 +00005134 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005135 // Find the operands and properties of the input shift. Note that the
5136 // signedness of the input shift may differ from the current shift if there
5137 // is a noop cast between the two.
5138 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5139 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
Chris Lattnere8d56c52006-01-07 01:32:28 +00005140 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
Chris Lattnerad0124c2006-01-06 07:52:12 +00005141
Reid Spencerb83eb642006-10-20 07:07:24 +00005142 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Chris Lattnerad0124c2006-01-06 07:52:12 +00005143
Reid Spencerb83eb642006-10-20 07:07:24 +00005144 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5145 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
Chris Lattnerad0124c2006-01-06 07:52:12 +00005146
5147 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5148 if (isLeftShift == isShiftOfLeftShift) {
5149 // Do not fold these shifts if the first one is signed and the second one
5150 // is unsigned and this is a right shift. Further, don't do any folding
5151 // on them.
5152 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5153 return 0;
Chris Lattner4d5542c2006-01-06 07:12:35 +00005154
Chris Lattnerad0124c2006-01-06 07:52:12 +00005155 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5156 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5157 Amt = Op0->getType()->getPrimitiveSizeInBits();
Chris Lattner4d5542c2006-01-06 07:12:35 +00005158
Chris Lattnerad0124c2006-01-06 07:52:12 +00005159 Value *Op = ShiftOp->getOperand(0);
5160 if (isShiftOfSignedShift != isSignedShift)
5161 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5162 return new ShiftInst(I.getOpcode(), Op,
Reid Spencerb83eb642006-10-20 07:07:24 +00005163 ConstantInt::get(Type::UByteTy, Amt));
Chris Lattnerad0124c2006-01-06 07:52:12 +00005164 }
5165
5166 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5167 // signed types, we can only support the (A >> c1) << c2 configuration,
5168 // because it can not turn an arbitrary bit of A into a sign bit.
5169 if (isUnsignedShift || isLeftShift) {
5170 // Calculate bitmask for what gets shifted off the edge.
5171 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5172 if (isLeftShift)
5173 C = ConstantExpr::getShl(C, ShiftAmt1C);
5174 else
Chris Lattnere8d56c52006-01-07 01:32:28 +00005175 C = ConstantExpr::getUShr(C, ShiftAmt1C);
Chris Lattnerad0124c2006-01-06 07:52:12 +00005176
5177 Value *Op = ShiftOp->getOperand(0);
5178 if (isShiftOfSignedShift != isSignedShift)
5179 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
5180
5181 Instruction *Mask =
5182 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5183 InsertNewInstBefore(Mask, I);
5184
5185 // Figure out what flavor of shift we should use...
Chris Lattnere8d56c52006-01-07 01:32:28 +00005186 if (ShiftAmt1 == ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005187 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
Chris Lattnere8d56c52006-01-07 01:32:28 +00005188 } else if (ShiftAmt1 < ShiftAmt2) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005189 return new ShiftInst(I.getOpcode(), Mask,
Reid Spencerb83eb642006-10-20 07:07:24 +00005190 ConstantInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005191 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5192 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5193 // Make sure to emit an unsigned shift right, not a signed one.
5194 Mask = InsertNewInstBefore(new CastInst(Mask,
5195 Mask->getType()->getUnsignedVersion(),
5196 Op->getName()), I);
5197 Mask = new ShiftInst(Instruction::Shr, Mask,
Reid Spencerb83eb642006-10-20 07:07:24 +00005198 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005199 InsertNewInstBefore(Mask, I);
5200 return new CastInst(Mask, I.getType());
5201 } else {
5202 return new ShiftInst(ShiftOp->getOpcode(), Mask,
Reid Spencerb83eb642006-10-20 07:07:24 +00005203 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005204 }
5205 } else {
5206 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
5207 Op = InsertNewInstBefore(new CastInst(Mask,
5208 I.getType()->getSignedVersion(),
5209 Mask->getName()), I);
5210 Instruction *Shift =
5211 new ShiftInst(ShiftOp->getOpcode(), Op,
Reid Spencerb83eb642006-10-20 07:07:24 +00005212 ConstantInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
Chris Lattnere8d56c52006-01-07 01:32:28 +00005213 InsertNewInstBefore(Shift, I);
5214
5215 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5216 C = ConstantExpr::getShl(C, Op1);
5217 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5218 InsertNewInstBefore(Mask, I);
5219 return new CastInst(Mask, I.getType());
Chris Lattnerad0124c2006-01-06 07:52:12 +00005220 }
5221 } else {
Chris Lattnere8d56c52006-01-07 01:32:28 +00005222 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
Chris Lattnerad0124c2006-01-06 07:52:12 +00005223 // this case, C1 == C2 and C1 is 8, 16, or 32.
5224 if (ShiftAmt1 == ShiftAmt2) {
5225 const Type *SExtType = 0;
Chris Lattner94046b42006-04-28 22:21:41 +00005226 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
Chris Lattnerad0124c2006-01-06 07:52:12 +00005227 case 8 : SExtType = Type::SByteTy; break;
5228 case 16: SExtType = Type::ShortTy; break;
5229 case 32: SExtType = Type::IntTy; break;
5230 }
5231
5232 if (SExtType) {
5233 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5234 SExtType, "sext");
5235 InsertNewInstBefore(NewTrunc, I);
5236 return new CastInst(NewTrunc, I.getType());
Chris Lattnerdf17af12003-08-12 21:53:41 +00005237 }
Chris Lattner11021cb2005-09-18 05:12:10 +00005238 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00005239 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00005240 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005241 return 0;
5242}
5243
Chris Lattnera1be5662002-05-02 17:06:02 +00005244
Chris Lattnercfd65102005-10-29 04:36:15 +00005245/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5246/// expression. If so, decompose it, returning some value X, such that Val is
5247/// X*Scale+Offset.
5248///
5249static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5250 unsigned &Offset) {
5251 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00005252 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5253 if (CI->getType()->isUnsigned()) {
5254 Offset = CI->getZExtValue();
5255 Scale = 1;
5256 return ConstantInt::get(Type::UIntTy, 0);
5257 }
Chris Lattnercfd65102005-10-29 04:36:15 +00005258 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5259 if (I->getNumOperands() == 2) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005260 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5261 if (CUI->getType()->isUnsigned()) {
5262 if (I->getOpcode() == Instruction::Shl) {
5263 // This is a value scaled by '1 << the shift amt'.
5264 Scale = 1U << CUI->getZExtValue();
5265 Offset = 0;
5266 return I->getOperand(0);
5267 } else if (I->getOpcode() == Instruction::Mul) {
5268 // This value is scaled by 'CUI'.
5269 Scale = CUI->getZExtValue();
5270 Offset = 0;
5271 return I->getOperand(0);
5272 } else if (I->getOpcode() == Instruction::Add) {
5273 // We have X+C. Check to see if we really have (X*C2)+C1,
5274 // where C1 is divisible by C2.
5275 unsigned SubScale;
5276 Value *SubVal =
5277 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5278 Offset += CUI->getZExtValue();
5279 if (SubScale > 1 && (Offset % SubScale == 0)) {
5280 Scale = SubScale;
5281 return SubVal;
5282 }
Chris Lattnercfd65102005-10-29 04:36:15 +00005283 }
5284 }
5285 }
5286 }
5287 }
5288
5289 // Otherwise, we can't look past this.
5290 Scale = 1;
5291 Offset = 0;
5292 return Val;
5293}
5294
5295
Chris Lattnerb3f83972005-10-24 06:03:58 +00005296/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5297/// try to eliminate the cast by moving the type information into the alloc.
5298Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5299 AllocationInst &AI) {
5300 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005301 if (!PTy) return 0; // Not casting the allocation to a pointer type.
Chris Lattnerb3f83972005-10-24 06:03:58 +00005302
Chris Lattnerb53c2382005-10-24 06:22:12 +00005303 // Remove any uses of AI that are dead.
5304 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5305 std::vector<Instruction*> DeadUsers;
5306 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5307 Instruction *User = cast<Instruction>(*UI++);
5308 if (isInstructionTriviallyDead(User)) {
5309 while (UI != E && *UI == User)
5310 ++UI; // If this instruction uses AI more than once, don't break UI.
5311
5312 // Add operands to the worklist.
5313 AddUsesToWorkList(*User);
5314 ++NumDeadInst;
5315 DEBUG(std::cerr << "IC: DCE: " << *User);
5316
5317 User->eraseFromParent();
5318 removeFromWorkList(User);
5319 }
5320 }
5321
Chris Lattnerb3f83972005-10-24 06:03:58 +00005322 // Get the type really allocated and the type casted to.
5323 const Type *AllocElTy = AI.getAllocatedType();
5324 const Type *CastElTy = PTy->getElementType();
5325 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00005326
Chris Lattnere831b9a2006-10-01 19:40:58 +00005327 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5328 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00005329 if (CastElTyAlign < AllocElTyAlign) return 0;
5330
Chris Lattner39387a52005-10-24 06:35:18 +00005331 // If the allocation has multiple uses, only promote it if we are strictly
5332 // increasing the alignment of the resultant allocation. If we keep it the
5333 // same, we open the door to infinite loops of various kinds.
5334 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5335
Chris Lattnerb3f83972005-10-24 06:03:58 +00005336 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5337 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005338 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00005339
Chris Lattner455fcc82005-10-29 03:19:53 +00005340 // See if we can satisfy the modulus by pulling a scale out of the array
5341 // size argument.
Chris Lattnercfd65102005-10-29 04:36:15 +00005342 unsigned ArraySizeScale, ArrayOffset;
5343 Value *NumElements = // See if the array size is a decomposable linear expr.
5344 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5345
Chris Lattner455fcc82005-10-29 03:19:53 +00005346 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5347 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00005348 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5349 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00005350
Chris Lattner455fcc82005-10-29 03:19:53 +00005351 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5352 Value *Amt = 0;
5353 if (Scale == 1) {
5354 Amt = NumElements;
5355 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00005356 // If the allocation size is constant, form a constant mul expression
5357 Amt = ConstantInt::get(Type::UIntTy, Scale);
5358 if (isa<ConstantInt>(NumElements) && NumElements->getType()->isUnsigned())
5359 Amt = ConstantExpr::getMul(
5360 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5361 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00005362 else if (Scale != 1) {
5363 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5364 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00005365 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005366 }
5367
Chris Lattnercfd65102005-10-29 04:36:15 +00005368 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005369 Value *Off = ConstantInt::get(Type::UIntTy, Offset);
Chris Lattnercfd65102005-10-29 04:36:15 +00005370 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5371 Amt = InsertNewInstBefore(Tmp, AI);
5372 }
5373
Chris Lattnerb3f83972005-10-24 06:03:58 +00005374 std::string Name = AI.getName(); AI.setName("");
5375 AllocationInst *New;
5376 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00005377 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00005378 else
Nate Begeman14b05292005-11-05 09:21:28 +00005379 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
Chris Lattnerb3f83972005-10-24 06:03:58 +00005380 InsertNewInstBefore(New, AI);
Chris Lattner39387a52005-10-24 06:35:18 +00005381
5382 // If the allocation has multiple uses, insert a cast and change all things
5383 // that used it to use the new cast. This will also hack on CI, but it will
5384 // die soon.
5385 if (!AI.hasOneUse()) {
5386 AddUsesToWorkList(AI);
5387 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5388 InsertNewInstBefore(NewCast, AI);
5389 AI.replaceAllUsesWith(NewCast);
5390 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00005391 return ReplaceInstUsesWith(CI, New);
5392}
5393
Chris Lattner70074e02006-05-13 02:06:03 +00005394/// CanEvaluateInDifferentType - Return true if we can take the specified value
5395/// and return it without inserting any new casts. This is used by code that
5396/// tries to decide whether promoting or shrinking integer operations to wider
5397/// or smaller types will allow us to eliminate a truncate or extend.
5398static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5399 int &NumCastsRemoved) {
5400 if (isa<Constant>(V)) return true;
5401
5402 Instruction *I = dyn_cast<Instruction>(V);
5403 if (!I || !I->hasOneUse()) return false;
5404
5405 switch (I->getOpcode()) {
5406 case Instruction::And:
5407 case Instruction::Or:
5408 case Instruction::Xor:
5409 // These operators can all arbitrarily be extended or truncated.
5410 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5411 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5412 case Instruction::Cast:
5413 // If this is a cast from the destination type, we can trivially eliminate
5414 // it, and this will remove a cast overall.
5415 if (I->getOperand(0)->getType() == Ty) {
Chris Lattnerd2280182006-06-28 17:34:50 +00005416 // If the first operand is itself a cast, and is eliminable, do not count
5417 // this as an eliminable cast. We would prefer to eliminate those two
5418 // casts first.
5419 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5420 return true;
5421
Chris Lattner70074e02006-05-13 02:06:03 +00005422 ++NumCastsRemoved;
5423 return true;
5424 }
5425 // TODO: Can handle more cases here.
5426 break;
5427 }
5428
5429 return false;
5430}
5431
5432/// EvaluateInDifferentType - Given an expression that
5433/// CanEvaluateInDifferentType returns true for, actually insert the code to
5434/// evaluate the expression.
5435Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5436 if (Constant *C = dyn_cast<Constant>(V))
5437 return ConstantExpr::getCast(C, Ty);
5438
5439 // Otherwise, it must be an instruction.
5440 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00005441 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00005442 switch (I->getOpcode()) {
5443 case Instruction::And:
5444 case Instruction::Or:
5445 case Instruction::Xor: {
5446 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5447 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5448 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5449 LHS, RHS, I->getName());
5450 break;
5451 }
5452 case Instruction::Cast:
5453 // If this is a cast from the destination type, return the input.
5454 if (I->getOperand(0)->getType() == Ty)
5455 return I->getOperand(0);
5456
5457 // TODO: Can handle more cases here.
5458 assert(0 && "Unreachable!");
5459 break;
5460 }
5461
5462 return InsertNewInstBefore(Res, *I);
5463}
5464
Chris Lattnerb3f83972005-10-24 06:03:58 +00005465
Chris Lattnera1be5662002-05-02 17:06:02 +00005466// CastInst simplification
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005467//
Chris Lattner7e708292002-06-25 16:13:24 +00005468Instruction *InstCombiner::visitCastInst(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00005469 Value *Src = CI.getOperand(0);
5470
Chris Lattnera1be5662002-05-02 17:06:02 +00005471 // If the user is casting a value to the same type, eliminate this cast
5472 // instruction...
Chris Lattner79d35b32003-06-23 21:59:52 +00005473 if (CI.getType() == Src->getType())
5474 return ReplaceInstUsesWith(CI, Src);
Chris Lattnera1be5662002-05-02 17:06:02 +00005475
Chris Lattnere87597f2004-10-16 18:11:37 +00005476 if (isa<UndefValue>(Src)) // cast undef -> undef
5477 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5478
Chris Lattnera1be5662002-05-02 17:06:02 +00005479 // If casting the result of another cast instruction, try to eliminate this
5480 // one!
5481 //
Chris Lattner6e7ba452005-01-01 16:22:27 +00005482 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5483 Value *A = CSrc->getOperand(0);
5484 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5485 CI.getType(), TD)) {
Chris Lattnera1be5662002-05-02 17:06:02 +00005486 // This instruction now refers directly to the cast's src operand. This
5487 // has a good chance of making CSrc dead.
Chris Lattner7e708292002-06-25 16:13:24 +00005488 CI.setOperand(0, CSrc->getOperand(0));
5489 return &CI;
Chris Lattnera1be5662002-05-02 17:06:02 +00005490 }
5491
Chris Lattner8fd217c2002-08-02 20:00:25 +00005492 // If this is an A->B->A cast, and we are dealing with integral types, try
5493 // to convert this into a logical 'and' instruction.
5494 //
Misha Brukmanfd939082005-04-21 23:48:37 +00005495 if (A->getType()->isInteger() &&
Chris Lattner0c4e8862002-09-03 01:08:28 +00005496 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
Chris Lattner6e7ba452005-01-01 16:22:27 +00005497 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
Chris Lattner484d3cf2005-04-24 06:59:08 +00005498 CSrc->getType()->getPrimitiveSizeInBits() <
5499 CI.getType()->getPrimitiveSizeInBits()&&
5500 A->getType()->getPrimitiveSizeInBits() ==
5501 CI.getType()->getPrimitiveSizeInBits()) {
Chris Lattner8fd217c2002-08-02 20:00:25 +00005502 assert(CSrc->getType() != Type::ULongTy &&
5503 "Cannot have type bigger than ulong!");
Chris Lattner1a074fc2006-02-07 07:00:41 +00005504 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
Reid Spencerb83eb642006-10-20 07:07:24 +00005505 Constant *AndOp = ConstantInt::get(A->getType()->getUnsignedVersion(),
Chris Lattner6e7ba452005-01-01 16:22:27 +00005506 AndValue);
5507 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5508 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5509 if (And->getType() != CI.getType()) {
5510 And->setName(CSrc->getName()+".mask");
5511 InsertNewInstBefore(And, CI);
5512 And = new CastInst(And, CI.getType());
5513 }
5514 return And;
Chris Lattner8fd217c2002-08-02 20:00:25 +00005515 }
5516 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00005517
Chris Lattnera710ddc2004-05-25 04:29:21 +00005518 // If this is a cast to bool, turn it into the appropriate setne instruction.
5519 if (CI.getType() == Type::BoolTy)
Chris Lattner48595f12004-06-10 02:07:29 +00005520 return BinaryOperator::createSetNE(CI.getOperand(0),
Chris Lattnera710ddc2004-05-25 04:29:21 +00005521 Constant::getNullValue(CI.getOperand(0)->getType()));
5522
Chris Lattner6dce1a72006-02-07 06:56:34 +00005523 // See if we can simplify any instructions used by the LHS whose sole
5524 // purpose is to compute bits we don't care about.
Chris Lattner255d8912006-02-11 09:31:47 +00005525 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5526 uint64_t KnownZero, KnownOne;
5527 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5528 KnownZero, KnownOne))
5529 return &CI;
5530 }
Chris Lattner6dce1a72006-02-07 06:56:34 +00005531
Chris Lattner797249b2003-06-21 23:12:02 +00005532 // If casting the result of a getelementptr instruction with no offset, turn
5533 // this into a cast of the original pointer!
5534 //
Chris Lattner79d35b32003-06-23 21:59:52 +00005535 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner797249b2003-06-21 23:12:02 +00005536 bool AllZeroOperands = true;
5537 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5538 if (!isa<Constant>(GEP->getOperand(i)) ||
5539 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5540 AllZeroOperands = false;
5541 break;
5542 }
5543 if (AllZeroOperands) {
5544 CI.setOperand(0, GEP->getOperand(0));
5545 return &CI;
5546 }
5547 }
5548
Chris Lattnerbc61e662003-11-02 05:57:39 +00005549 // If we are casting a malloc or alloca to a pointer to a type of the same
5550 // size, rewrite the allocation instruction to allocate the "right" type.
5551 //
5552 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
Chris Lattnerb3f83972005-10-24 06:03:58 +00005553 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5554 return V;
Chris Lattnerbc61e662003-11-02 05:57:39 +00005555
Chris Lattner6e7ba452005-01-01 16:22:27 +00005556 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5557 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5558 return NV;
Chris Lattner4e998b22004-09-29 05:07:12 +00005559 if (isa<PHINode>(Src))
5560 if (Instruction *NV = FoldOpIntoPhi(CI))
5561 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00005562
5563 // If the source and destination are pointers, and this cast is equivalent to
5564 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5565 // This can enhance SROA and other transforms that want type-safe pointers.
5566 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5567 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5568 const Type *DstTy = DstPTy->getElementType();
5569 const Type *SrcTy = SrcPTy->getElementType();
5570
5571 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5572 unsigned NumZeros = 0;
5573 while (SrcTy != DstTy &&
Chris Lattner63d32202006-09-11 21:43:16 +00005574 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5575 SrcTy->getNumContainedTypes() /* not "{}" */) {
Chris Lattner9fb92132006-04-12 18:09:35 +00005576 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5577 ++NumZeros;
5578 }
Chris Lattner4e998b22004-09-29 05:07:12 +00005579
Chris Lattner9fb92132006-04-12 18:09:35 +00005580 // If we found a path from the src to dest, create the getelementptr now.
5581 if (SrcTy == DstTy) {
5582 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5583 return new GetElementPtrInst(Src, Idxs);
5584 }
5585 }
5586
Chris Lattner24c8e382003-07-24 17:35:25 +00005587 // If the source value is an instruction with only this use, we can attempt to
5588 // propagate the cast into the instruction. Also, only handle integral types
5589 // for now.
Chris Lattner01575b72006-05-25 23:24:33 +00005590 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
Chris Lattnerfd059242003-10-15 16:48:29 +00005591 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
Chris Lattner24c8e382003-07-24 17:35:25 +00005592 CI.getType()->isInteger()) { // Don't mess with casts to bool here
Chris Lattner70074e02006-05-13 02:06:03 +00005593
5594 int NumCastsRemoved = 0;
5595 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5596 // If this cast is a truncate, evaluting in a different type always
5597 // eliminates the cast, so it is always a win. If this is a noop-cast
5598 // this just removes a noop cast which isn't pointful, but simplifies
5599 // the code. If this is a zero-extension, we need to do an AND to
5600 // maintain the clear top-part of the computation, so we require that
5601 // the input have eliminated at least one cast. If this is a sign
5602 // extension, we insert two new casts (to do the extension) so we
5603 // require that two casts have been eliminated.
5604 bool DoXForm;
5605 switch (getCastType(Src->getType(), CI.getType())) {
5606 default: assert(0 && "Unknown cast type!");
5607 case Noop:
5608 case Truncate:
5609 DoXForm = true;
5610 break;
5611 case Zeroext:
5612 DoXForm = NumCastsRemoved >= 1;
5613 break;
5614 case Signext:
5615 DoXForm = NumCastsRemoved >= 2;
5616 break;
5617 }
5618
5619 if (DoXForm) {
5620 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5621 assert(Res->getType() == CI.getType());
5622 switch (getCastType(Src->getType(), CI.getType())) {
5623 default: assert(0 && "Unknown cast type!");
5624 case Noop:
5625 case Truncate:
5626 // Just replace this cast with the result.
5627 return ReplaceInstUsesWith(CI, Res);
5628 case Zeroext: {
5629 // We need to emit an AND to clear the high bits.
5630 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5631 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5632 assert(SrcBitSize < DestBitSize && "Not a zext?");
Reid Spencerb83eb642006-10-20 07:07:24 +00005633 Constant *C =
5634 ConstantInt::get(Type::ULongTy, (1ULL << SrcBitSize)-1);
Chris Lattner70074e02006-05-13 02:06:03 +00005635 C = ConstantExpr::getCast(C, CI.getType());
5636 return BinaryOperator::createAnd(Res, C);
5637 }
5638 case Signext:
5639 // We need to emit a cast to truncate, then a cast to sext.
5640 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5641 CI.getType());
5642 }
5643 }
5644 }
5645
Chris Lattner24c8e382003-07-24 17:35:25 +00005646 const Type *DestTy = CI.getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005647 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5648 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
Chris Lattner24c8e382003-07-24 17:35:25 +00005649
5650 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5651 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5652
5653 switch (SrcI->getOpcode()) {
5654 case Instruction::Add:
5655 case Instruction::Mul:
5656 case Instruction::And:
5657 case Instruction::Or:
5658 case Instruction::Xor:
5659 // If we are discarding information, or just changing the sign, rewrite.
5660 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5661 // Don't insert two casts if they cannot be eliminated. We allow two
5662 // casts to be inserted if the sizes are the same. This could only be
5663 // converting signedness, which is a noop.
Chris Lattner59a20772004-07-20 05:21:00 +00005664 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5665 !ValueRequiresCast(Op0, DestTy, TD)) {
Chris Lattner24c8e382003-07-24 17:35:25 +00005666 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5667 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5668 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5669 ->getOpcode(), Op0c, Op1c);
5670 }
5671 }
Chris Lattner7aed7ac2005-05-06 02:07:39 +00005672
5673 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5674 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
Chris Lattner47811b72006-09-28 23:35:22 +00005675 Op1 == ConstantBool::getTrue() &&
Chris Lattner7aed7ac2005-05-06 02:07:39 +00005676 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5677 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5678 return BinaryOperator::createXor(New,
5679 ConstantInt::get(CI.getType(), 1));
5680 }
Chris Lattner24c8e382003-07-24 17:35:25 +00005681 break;
5682 case Instruction::Shl:
5683 // Allow changing the sign of the source operand. Do not allow changing
5684 // the size of the shift, UNLESS the shift amount is a constant. We
5685 // mush not change variable sized shifts to a smaller size, because it
5686 // is undefined to shift more bits out than exist in the value.
5687 if (DestBitSize == SrcBitSize ||
5688 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5689 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5690 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5691 }
5692 break;
Chris Lattnerd7115b02005-05-06 04:18:52 +00005693 case Instruction::Shr:
5694 // If this is a signed shr, and if all bits shifted in are about to be
5695 // truncated off, turn it into an unsigned shr to allow greater
5696 // simplifications.
5697 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5698 isa<ConstantInt>(Op1)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00005699 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
Chris Lattnerd7115b02005-05-06 04:18:52 +00005700 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5701 // Convert to unsigned.
5702 Value *N1 = InsertOperandCastBefore(Op0,
5703 Op0->getType()->getUnsignedVersion(), &CI);
5704 // Insert the new shift, which is now unsigned.
5705 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5706 Op1, Src->getName()), CI);
5707 return new CastInst(N1, CI.getType());
5708 }
5709 }
5710 break;
5711
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005712 case Instruction::SetEQ:
Chris Lattner693787a2005-05-04 19:10:26 +00005713 case Instruction::SetNE:
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005714 // We if we are just checking for a seteq of a single bit and casting it
5715 // to an integer. If so, shift the bit to the appropriate place then
5716 // cast to integer to avoid the comparison.
Chris Lattner693787a2005-05-04 19:10:26 +00005717 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005718 uint64_t Op1CV = Op1C->getZExtValue();
5719 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5720 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5721 // cast (X == 1) to int --> X iff X has only the low bit set.
5722 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5723 // cast (X != 0) to int --> X iff X has only the low bit set.
5724 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5725 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5726 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5727 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5728 // If Op1C some other power of two, convert:
5729 uint64_t KnownZero, KnownOne;
5730 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5731 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5732
5733 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5734 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5735 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5736 // (X&4) == 2 --> false
5737 // (X&4) != 2 --> true
Chris Lattner06e1e252006-02-28 19:47:20 +00005738 Constant *Res = ConstantBool::get(isSetNE);
5739 Res = ConstantExpr::getCast(Res, CI.getType());
5740 return ReplaceInstUsesWith(CI, Res);
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005741 }
5742
5743 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5744 Value *In = Op0;
5745 if (ShiftAmt) {
Chris Lattnerd1523802005-05-06 01:53:19 +00005746 // Perform an unsigned shr by shiftamt. Convert input to
5747 // unsigned if it is signed.
Chris Lattnerd1523802005-05-06 01:53:19 +00005748 if (In->getType()->isSigned())
5749 In = InsertNewInstBefore(new CastInst(In,
5750 In->getType()->getUnsignedVersion(), In->getName()),CI);
5751 // Insert the shift to put the result in the low bit.
5752 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005753 ConstantInt::get(Type::UByteTy, ShiftAmt),
5754 In->getName()+".lobit"), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005755 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005756
5757 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5758 Constant *One = ConstantInt::get(In->getType(), 1);
5759 In = BinaryOperator::createXor(In, One, "tmp");
5760 InsertNewInstBefore(cast<Instruction>(In), CI);
Chris Lattnerd1523802005-05-06 01:53:19 +00005761 }
Chris Lattner3e88a4d2006-02-27 02:38:23 +00005762
5763 if (CI.getType() == In->getType())
5764 return ReplaceInstUsesWith(CI, In);
5765 else
5766 return new CastInst(In, CI.getType());
Chris Lattnerd1523802005-05-06 01:53:19 +00005767 }
Chris Lattner693787a2005-05-04 19:10:26 +00005768 }
5769 }
5770 break;
Chris Lattner24c8e382003-07-24 17:35:25 +00005771 }
5772 }
Chris Lattner01575b72006-05-25 23:24:33 +00005773
5774 if (SrcI->hasOneUse()) {
5775 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5776 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5777 // because the inputs are known to be a vector. Check to see if this is
5778 // a cast to a vector with the same # elts.
5779 if (isa<PackedType>(CI.getType()) &&
5780 cast<PackedType>(CI.getType())->getNumElements() ==
5781 SVI->getType()->getNumElements()) {
5782 CastInst *Tmp;
5783 // If either of the operands is a cast from CI.getType(), then
5784 // evaluating the shuffle in the casted destination's type will allow
5785 // us to eliminate at least one cast.
5786 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5787 Tmp->getOperand(0)->getType() == CI.getType()) ||
5788 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
Chris Lattner18a4af22006-06-06 22:26:02 +00005789 Tmp->getOperand(0)->getType() == CI.getType())) {
Chris Lattner01575b72006-05-25 23:24:33 +00005790 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5791 CI.getType(), &CI);
5792 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5793 CI.getType(), &CI);
5794 // Return a new shuffle vector. Use the same element ID's, as we
5795 // know the vector types match #elts.
5796 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5797 }
5798 }
5799 }
5800 }
5801 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00005802
Chris Lattnerdd841ae2002-04-18 17:39:14 +00005803 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00005804}
5805
Chris Lattnere576b912004-04-09 23:46:01 +00005806/// GetSelectFoldableOperands - We want to turn code that looks like this:
5807/// %C = or %A, %B
5808/// %D = select %cond, %C, %A
5809/// into:
5810/// %C = select %cond, %B, 0
5811/// %D = or %A, %C
5812///
5813/// Assuming that the specified instruction is an operand to the select, return
5814/// a bitmask indicating which operands of this instruction are foldable if they
5815/// equal the other incoming value of the select.
5816///
5817static unsigned GetSelectFoldableOperands(Instruction *I) {
5818 switch (I->getOpcode()) {
5819 case Instruction::Add:
5820 case Instruction::Mul:
5821 case Instruction::And:
5822 case Instruction::Or:
5823 case Instruction::Xor:
5824 return 3; // Can fold through either operand.
5825 case Instruction::Sub: // Can only fold on the amount subtracted.
5826 case Instruction::Shl: // Can only fold on the shift amount.
5827 case Instruction::Shr:
Misha Brukmanfd939082005-04-21 23:48:37 +00005828 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00005829 default:
5830 return 0; // Cannot fold
5831 }
5832}
5833
5834/// GetSelectFoldableConstant - For the same transformation as the previous
5835/// function, return the identity constant that goes into the select.
5836static Constant *GetSelectFoldableConstant(Instruction *I) {
5837 switch (I->getOpcode()) {
5838 default: assert(0 && "This cannot happen!"); abort();
5839 case Instruction::Add:
5840 case Instruction::Sub:
5841 case Instruction::Or:
5842 case Instruction::Xor:
5843 return Constant::getNullValue(I->getType());
5844 case Instruction::Shl:
5845 case Instruction::Shr:
5846 return Constant::getNullValue(Type::UByteTy);
5847 case Instruction::And:
5848 return ConstantInt::getAllOnesValue(I->getType());
5849 case Instruction::Mul:
5850 return ConstantInt::get(I->getType(), 1);
5851 }
5852}
5853
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005854/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5855/// have the same opcode and only one use each. Try to simplify this.
5856Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5857 Instruction *FI) {
5858 if (TI->getNumOperands() == 1) {
5859 // If this is a non-volatile load or a cast from the same type,
5860 // merge.
5861 if (TI->getOpcode() == Instruction::Cast) {
5862 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5863 return 0;
5864 } else {
5865 return 0; // unknown unary op.
5866 }
Misha Brukmanfd939082005-04-21 23:48:37 +00005867
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00005868 // Fold this by inserting a select from the input values.
5869 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5870 FI->getOperand(0), SI.getName()+".v");
5871 InsertNewInstBefore(NewSI, SI);
5872 return new CastInst(NewSI, TI->getType());
5873 }
5874
5875 // Only handle binary operators here.
5876 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5877 return 0;
5878
5879 // Figure out if the operations have any operands in common.
5880 Value *MatchOp, *OtherOpT, *OtherOpF;
5881 bool MatchIsOpZero;
5882 if (TI->getOperand(0) == FI->getOperand(0)) {
5883 MatchOp = TI->getOperand(0);
5884 OtherOpT = TI->getOperand(1);
5885 OtherOpF = FI->getOperand(1);
5886 MatchIsOpZero = true;
5887 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5888 MatchOp = TI->getOperand(1);
5889 OtherOpT = TI->getOperand(0);
5890 OtherOpF = FI->getOperand(0);
5891 MatchIsOpZero = false;
5892 } else if (!TI->isCommutative()) {
5893 return 0;
5894 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5895 MatchOp = TI->getOperand(0);
5896 OtherOpT = TI->getOperand(1);
5897 OtherOpF = FI->getOperand(0);
5898 MatchIsOpZero = true;
5899 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5900 MatchOp = TI->getOperand(1);
5901 OtherOpT = TI->getOperand(0);
5902 OtherOpF = FI->getOperand(1);
5903 MatchIsOpZero = true;
5904 } else {
5905 return 0;
5906 }
5907
5908 // If we reach here, they do have operations in common.
5909 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5910 OtherOpF, SI.getName()+".v");
5911 InsertNewInstBefore(NewSI, SI);
5912
5913 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5914 if (MatchIsOpZero)
5915 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5916 else
5917 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5918 } else {
5919 if (MatchIsOpZero)
5920 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5921 else
5922 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5923 }
5924}
5925
Chris Lattner3d69f462004-03-12 05:52:32 +00005926Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005927 Value *CondVal = SI.getCondition();
5928 Value *TrueVal = SI.getTrueValue();
5929 Value *FalseVal = SI.getFalseValue();
5930
5931 // select true, X, Y -> X
5932 // select false, X, Y -> Y
5933 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
Chris Lattner47811b72006-09-28 23:35:22 +00005934 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00005935
5936 // select C, X, X -> X
5937 if (TrueVal == FalseVal)
5938 return ReplaceInstUsesWith(SI, TrueVal);
5939
Chris Lattnere87597f2004-10-16 18:11:37 +00005940 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5941 return ReplaceInstUsesWith(SI, FalseVal);
5942 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5943 return ReplaceInstUsesWith(SI, TrueVal);
5944 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5945 if (isa<Constant>(TrueVal))
5946 return ReplaceInstUsesWith(SI, TrueVal);
5947 else
5948 return ReplaceInstUsesWith(SI, FalseVal);
5949 }
5950
Chris Lattner0c199a72004-04-08 04:43:23 +00005951 if (SI.getType() == Type::BoolTy)
5952 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
Chris Lattner47811b72006-09-28 23:35:22 +00005953 if (C->getValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00005954 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005955 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005956 } else {
5957 // Change: A = select B, false, C --> A = and !B, C
5958 Value *NotCond =
5959 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5960 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005961 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005962 }
5963 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
Chris Lattner47811b72006-09-28 23:35:22 +00005964 if (C->getValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00005965 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00005966 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005967 } else {
5968 // Change: A = select B, C, true --> A = or !B, C
5969 Value *NotCond =
5970 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5971 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00005972 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00005973 }
5974 }
5975
Chris Lattner2eefe512004-04-09 19:05:30 +00005976 // Selecting between two integer constants?
5977 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5978 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5979 // select C, 1, 0 -> cast C to int
Reid Spencerb83eb642006-10-20 07:07:24 +00005980 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
Chris Lattner2eefe512004-04-09 19:05:30 +00005981 return new CastInst(CondVal, SI.getType());
Reid Spencerb83eb642006-10-20 07:07:24 +00005982 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
Chris Lattner2eefe512004-04-09 19:05:30 +00005983 // select C, 0, 1 -> cast !C to int
5984 Value *NotCond =
5985 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00005986 "not."+CondVal->getName()), SI);
Chris Lattner2eefe512004-04-09 19:05:30 +00005987 return new CastInst(NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00005988 }
Chris Lattner457dd822004-06-09 07:59:58 +00005989
Chris Lattnerb8456462006-09-20 04:44:59 +00005990 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
5991
5992 // (x <s 0) ? -1 : 0 -> sra x, 31
5993 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
5994 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
5995 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
5996 bool CanXForm = false;
5997 if (CmpCst->getType()->isSigned())
5998 CanXForm = CmpCst->isNullValue() &&
5999 IC->getOpcode() == Instruction::SetLT;
6000 else {
6001 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00006002 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
Chris Lattnerb8456462006-09-20 04:44:59 +00006003 IC->getOpcode() == Instruction::SetGT;
6004 }
6005
6006 if (CanXForm) {
6007 // The comparison constant and the result are not neccessarily the
6008 // same width. In any case, the first step to do is make sure
6009 // that X is signed.
6010 Value *X = IC->getOperand(0);
6011 if (!X->getType()->isSigned())
6012 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
6013
6014 // Now that X is signed, we have to make the all ones value. Do
6015 // this by inserting a new SRA.
6016 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencerb83eb642006-10-20 07:07:24 +00006017 Constant *ShAmt = ConstantInt::get(Type::UByteTy, Bits-1);
Chris Lattnerb8456462006-09-20 04:44:59 +00006018 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
6019 ShAmt, "ones");
6020 InsertNewInstBefore(SRA, SI);
6021
6022 // Finally, convert to the type of the select RHS. If this is
6023 // smaller than the compare value, it will truncate the ones to
6024 // fit. If it is larger, it will sext the ones to fit.
6025 return new CastInst(SRA, SI.getType());
6026 }
6027 }
6028
6029
6030 // If one of the constants is zero (we know they can't both be) and we
6031 // have a setcc instruction with zero, and we have an 'and' with the
6032 // non-constant value, eliminate this whole mess. This corresponds to
6033 // cases like this: ((X & 27) ? 27 : 0)
6034 if (TrueValC->isNullValue() || FalseValC->isNullValue())
Chris Lattner65b72ba2006-09-18 04:22:48 +00006035 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006036 cast<Constant>(IC->getOperand(1))->isNullValue())
6037 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6038 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00006039 isa<ConstantInt>(ICA->getOperand(1)) &&
6040 (ICA->getOperand(1) == TrueValC ||
6041 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00006042 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6043 // Okay, now we know that everything is set up, we just don't
6044 // know whether we have a setne or seteq and whether the true or
6045 // false val is the zero.
6046 bool ShouldNotVal = !TrueValC->isNullValue();
6047 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6048 Value *V = ICA;
6049 if (ShouldNotVal)
6050 V = InsertNewInstBefore(BinaryOperator::create(
6051 Instruction::Xor, V, ICA->getOperand(1)), SI);
6052 return ReplaceInstUsesWith(SI, V);
6053 }
Chris Lattnerb8456462006-09-20 04:44:59 +00006054 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00006055 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00006056
6057 // See if we are selecting two values based on a comparison of the two values.
6058 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6059 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6060 // Transform (X == Y) ? X : Y -> Y
6061 if (SCI->getOpcode() == Instruction::SetEQ)
6062 return ReplaceInstUsesWith(SI, FalseVal);
6063 // Transform (X != Y) ? X : Y -> X
6064 if (SCI->getOpcode() == Instruction::SetNE)
6065 return ReplaceInstUsesWith(SI, TrueVal);
6066 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6067
6068 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6069 // Transform (X == Y) ? Y : X -> X
6070 if (SCI->getOpcode() == Instruction::SetEQ)
Chris Lattnerfbede522004-04-11 01:39:19 +00006071 return ReplaceInstUsesWith(SI, FalseVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00006072 // Transform (X != Y) ? Y : X -> Y
6073 if (SCI->getOpcode() == Instruction::SetNE)
Chris Lattnerfbede522004-04-11 01:39:19 +00006074 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00006075 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6076 }
6077 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006078
Chris Lattner87875da2005-01-13 22:52:24 +00006079 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6080 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6081 if (TI->hasOneUse() && FI->hasOneUse()) {
6082 bool isInverse = false;
6083 Instruction *AddOp = 0, *SubOp = 0;
6084
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00006085 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6086 if (TI->getOpcode() == FI->getOpcode())
6087 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6088 return IV;
6089
6090 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6091 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00006092 if (TI->getOpcode() == Instruction::Sub &&
6093 FI->getOpcode() == Instruction::Add) {
6094 AddOp = FI; SubOp = TI;
6095 } else if (FI->getOpcode() == Instruction::Sub &&
6096 TI->getOpcode() == Instruction::Add) {
6097 AddOp = TI; SubOp = FI;
6098 }
6099
6100 if (AddOp) {
6101 Value *OtherAddOp = 0;
6102 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6103 OtherAddOp = AddOp->getOperand(1);
6104 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6105 OtherAddOp = AddOp->getOperand(0);
6106 }
6107
6108 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00006109 // So at this point we know we have (Y -> OtherAddOp):
6110 // select C, (add X, Y), (sub X, Z)
6111 Value *NegVal; // Compute -Z
6112 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6113 NegVal = ConstantExpr::getNeg(C);
6114 } else {
6115 NegVal = InsertNewInstBefore(
6116 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00006117 }
Chris Lattner97f37a42006-02-24 18:05:58 +00006118
6119 Value *NewTrueOp = OtherAddOp;
6120 Value *NewFalseOp = NegVal;
6121 if (AddOp != TI)
6122 std::swap(NewTrueOp, NewFalseOp);
6123 Instruction *NewSel =
6124 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6125
6126 NewSel = InsertNewInstBefore(NewSel, SI);
6127 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00006128 }
6129 }
6130 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006131
Chris Lattnere576b912004-04-09 23:46:01 +00006132 // See if we can fold the select into one of our operands.
6133 if (SI.getType()->isInteger()) {
6134 // See the comment above GetSelectFoldableOperands for a description of the
6135 // transformation we are doing here.
6136 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6137 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6138 !isa<Constant>(FalseVal))
6139 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6140 unsigned OpToFold = 0;
6141 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6142 OpToFold = 1;
6143 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6144 OpToFold = 2;
6145 }
6146
6147 if (OpToFold) {
6148 Constant *C = GetSelectFoldableConstant(TVI);
6149 std::string Name = TVI->getName(); TVI->setName("");
6150 Instruction *NewSel =
6151 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6152 Name);
6153 InsertNewInstBefore(NewSel, SI);
6154 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6155 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6156 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6157 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6158 else {
6159 assert(0 && "Unknown instruction!!");
6160 }
6161 }
6162 }
Chris Lattnera96879a2004-09-29 17:40:11 +00006163
Chris Lattnere576b912004-04-09 23:46:01 +00006164 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6165 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6166 !isa<Constant>(TrueVal))
6167 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6168 unsigned OpToFold = 0;
6169 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6170 OpToFold = 1;
6171 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6172 OpToFold = 2;
6173 }
6174
6175 if (OpToFold) {
6176 Constant *C = GetSelectFoldableConstant(FVI);
6177 std::string Name = FVI->getName(); FVI->setName("");
6178 Instruction *NewSel =
6179 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6180 Name);
6181 InsertNewInstBefore(NewSel, SI);
6182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6183 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6184 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6185 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6186 else {
6187 assert(0 && "Unknown instruction!!");
6188 }
6189 }
6190 }
6191 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00006192
6193 if (BinaryOperator::isNot(CondVal)) {
6194 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6195 SI.setOperand(1, FalseVal);
6196 SI.setOperand(2, TrueVal);
6197 return &SI;
6198 }
6199
Chris Lattner3d69f462004-03-12 05:52:32 +00006200 return 0;
6201}
6202
Chris Lattner95a959d2006-03-06 20:18:44 +00006203/// GetKnownAlignment - If the specified pointer has an alignment that we can
6204/// determine, return it, otherwise return 0.
6205static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6206 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6207 unsigned Align = GV->getAlignment();
6208 if (Align == 0 && TD)
6209 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6210 return Align;
6211 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6212 unsigned Align = AI->getAlignment();
6213 if (Align == 0 && TD) {
6214 if (isa<AllocaInst>(AI))
6215 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6216 else if (isa<MallocInst>(AI)) {
6217 // Malloc returns maximally aligned memory.
6218 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6219 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6220 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6221 }
6222 }
6223 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00006224 } else if (isa<CastInst>(V) ||
6225 (isa<ConstantExpr>(V) &&
6226 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6227 User *CI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00006228 if (isa<PointerType>(CI->getOperand(0)->getType()))
6229 return GetKnownAlignment(CI->getOperand(0), TD);
6230 return 0;
Chris Lattner51c26e92006-03-07 01:28:57 +00006231 } else if (isa<GetElementPtrInst>(V) ||
6232 (isa<ConstantExpr>(V) &&
6233 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6234 User *GEPI = cast<User>(V);
Chris Lattner95a959d2006-03-06 20:18:44 +00006235 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6236 if (BaseAlignment == 0) return 0;
6237
6238 // If all indexes are zero, it is just the alignment of the base pointer.
6239 bool AllZeroOperands = true;
6240 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6241 if (!isa<Constant>(GEPI->getOperand(i)) ||
6242 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6243 AllZeroOperands = false;
6244 break;
6245 }
6246 if (AllZeroOperands)
6247 return BaseAlignment;
6248
6249 // Otherwise, if the base alignment is >= the alignment we expect for the
6250 // base pointer type, then we know that the resultant pointer is aligned at
6251 // least as much as its type requires.
6252 if (!TD) return 0;
6253
6254 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6255 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
Chris Lattner51c26e92006-03-07 01:28:57 +00006256 <= BaseAlignment) {
6257 const Type *GEPTy = GEPI->getType();
6258 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6259 }
Chris Lattner95a959d2006-03-06 20:18:44 +00006260 return 0;
6261 }
6262 return 0;
6263}
6264
Chris Lattner3d69f462004-03-12 05:52:32 +00006265
Chris Lattner8b0ea312006-01-13 20:11:04 +00006266/// visitCallInst - CallInst simplification. This mostly only handles folding
6267/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6268/// the heavy lifting.
6269///
Chris Lattner9fe38862003-06-19 17:00:31 +00006270Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00006271 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6272 if (!II) return visitCallSite(&CI);
6273
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006274 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6275 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00006276 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006277 bool Changed = false;
6278
6279 // memmove/cpy/set of zero bytes is a noop.
6280 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6281 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6282
Chris Lattner35b9e482004-10-12 04:52:52 +00006283 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00006284 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006285 // Replace the instruction with just byte operations. We would
6286 // transform other cases to loads/stores, but we don't know if
6287 // alignment is sufficient.
6288 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006289 }
6290
Chris Lattner35b9e482004-10-12 04:52:52 +00006291 // If we have a memmove and the source operation is a constant global,
6292 // then the source and dest pointers can't alias, so we can change this
6293 // into a call to memcpy.
Chris Lattner95a959d2006-03-06 20:18:44 +00006294 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00006295 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6296 if (GVSrc->isConstant()) {
6297 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner21959392006-03-03 01:34:17 +00006298 const char *Name;
6299 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6300 Type::UIntTy)
6301 Name = "llvm.memcpy.i32";
6302 else
6303 Name = "llvm.memcpy.i64";
6304 Function *MemCpy = M->getOrInsertFunction(Name,
Chris Lattner35b9e482004-10-12 04:52:52 +00006305 CI.getCalledFunction()->getFunctionType());
6306 CI.setOperand(0, MemCpy);
6307 Changed = true;
6308 }
Chris Lattner95a959d2006-03-06 20:18:44 +00006309 }
Chris Lattner35b9e482004-10-12 04:52:52 +00006310
Chris Lattner95a959d2006-03-06 20:18:44 +00006311 // If we can determine a pointer alignment that is bigger than currently
6312 // set, update the alignment.
6313 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6314 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6315 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6316 unsigned Align = std::min(Alignment1, Alignment2);
Reid Spencerb83eb642006-10-20 07:07:24 +00006317 if (MI->getAlignment()->getZExtValue() < Align) {
6318 MI->setAlignment(ConstantInt::get(Type::UIntTy, Align));
Chris Lattner95a959d2006-03-06 20:18:44 +00006319 Changed = true;
6320 }
6321 } else if (isa<MemSetInst>(MI)) {
6322 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00006323 if (MI->getAlignment()->getZExtValue() < Alignment) {
6324 MI->setAlignment(ConstantInt::get(Type::UIntTy, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00006325 Changed = true;
6326 }
6327 }
6328
Chris Lattner8b0ea312006-01-13 20:11:04 +00006329 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00006330 } else {
6331 switch (II->getIntrinsicID()) {
6332 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00006333 case Intrinsic::ppc_altivec_lvx:
6334 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00006335 case Intrinsic::x86_sse_loadu_ps:
6336 case Intrinsic::x86_sse2_loadu_pd:
6337 case Intrinsic::x86_sse2_loadu_dq:
6338 // Turn PPC lvx -> load if the pointer is known aligned.
6339 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner82ed58f2006-04-02 05:30:25 +00006340 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00006341 Value *Ptr = InsertCastBefore(II->getOperand(1),
6342 PointerType::get(II->getType()), CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00006343 return new LoadInst(Ptr);
6344 }
6345 break;
6346 case Intrinsic::ppc_altivec_stvx:
6347 case Intrinsic::ppc_altivec_stvxl:
6348 // Turn stvx -> store if the pointer is known aligned.
6349 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00006350 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6351 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00006352 return new StoreInst(II->getOperand(1), Ptr);
6353 }
6354 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00006355 case Intrinsic::x86_sse_storeu_ps:
6356 case Intrinsic::x86_sse2_storeu_pd:
6357 case Intrinsic::x86_sse2_storeu_dq:
6358 case Intrinsic::x86_sse2_storel_dq:
6359 // Turn X86 storeu -> store if the pointer is known aligned.
6360 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6361 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6362 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6363 return new StoreInst(II->getOperand(2), Ptr);
6364 }
6365 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00006366
6367 case Intrinsic::x86_sse_cvttss2si: {
6368 // These intrinsics only demands the 0th element of its input vector. If
6369 // we can simplify the input based on that, do so now.
6370 uint64_t UndefElts;
6371 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6372 UndefElts)) {
6373 II->setOperand(1, V);
6374 return II;
6375 }
6376 break;
6377 }
6378
Chris Lattnere2ed0572006-04-06 19:19:17 +00006379 case Intrinsic::ppc_altivec_vperm:
6380 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6381 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6382 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6383
6384 // Check that all of the elements are integer constants or undefs.
6385 bool AllEltsOk = true;
6386 for (unsigned i = 0; i != 16; ++i) {
6387 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6388 !isa<UndefValue>(Mask->getOperand(i))) {
6389 AllEltsOk = false;
6390 break;
6391 }
6392 }
6393
6394 if (AllEltsOk) {
6395 // Cast the input vectors to byte vectors.
6396 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6397 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6398 Value *Result = UndefValue::get(Op0->getType());
6399
6400 // Only extract each element once.
6401 Value *ExtractedElts[32];
6402 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6403
6404 for (unsigned i = 0; i != 16; ++i) {
6405 if (isa<UndefValue>(Mask->getOperand(i)))
6406 continue;
Reid Spencerb83eb642006-10-20 07:07:24 +00006407 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00006408 Idx &= 31; // Match the hardware behavior.
6409
6410 if (ExtractedElts[Idx] == 0) {
6411 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00006412 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00006413 InsertNewInstBefore(Elt, CI);
6414 ExtractedElts[Idx] = Elt;
6415 }
6416
6417 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00006418 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00006419 InsertNewInstBefore(cast<Instruction>(Result), CI);
6420 }
6421 return new CastInst(Result, CI.getType());
6422 }
6423 }
6424 break;
6425
Chris Lattnera728ddc2006-01-13 21:28:09 +00006426 case Intrinsic::stackrestore: {
6427 // If the save is right next to the restore, remove the restore. This can
6428 // happen when variable allocas are DCE'd.
6429 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6430 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6431 BasicBlock::iterator BI = SS;
6432 if (&*++BI == II)
6433 return EraseInstFromFunction(CI);
6434 }
6435 }
6436
6437 // If the stack restore is in a return/unwind block and if there are no
6438 // allocas or calls between the restore and the return, nuke the restore.
6439 TerminatorInst *TI = II->getParent()->getTerminator();
6440 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6441 BasicBlock::iterator BI = II;
6442 bool CannotRemove = false;
6443 for (++BI; &*BI != TI; ++BI) {
6444 if (isa<AllocaInst>(BI) ||
6445 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6446 CannotRemove = true;
6447 break;
6448 }
6449 }
6450 if (!CannotRemove)
6451 return EraseInstFromFunction(CI);
6452 }
6453 break;
6454 }
6455 }
Chris Lattner35b9e482004-10-12 04:52:52 +00006456 }
6457
Chris Lattner8b0ea312006-01-13 20:11:04 +00006458 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00006459}
6460
6461// InvokeInst simplification
6462//
6463Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00006464 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00006465}
6466
Chris Lattnera44d8a22003-10-07 22:32:43 +00006467// visitCallSite - Improvements for call and invoke instructions.
6468//
6469Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00006470 bool Changed = false;
6471
6472 // If the callee is a constexpr cast of a function, attempt to move the cast
6473 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00006474 if (transformConstExprCastCall(CS)) return 0;
6475
Chris Lattner6c266db2003-10-07 22:54:13 +00006476 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00006477
Chris Lattner08b22ec2005-05-13 07:09:09 +00006478 if (Function *CalleeF = dyn_cast<Function>(Callee))
6479 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6480 Instruction *OldCall = CS.getInstruction();
6481 // If the call and callee calling conventions don't match, this call must
6482 // be unreachable, as the call is undefined.
Chris Lattner47811b72006-09-28 23:35:22 +00006483 new StoreInst(ConstantBool::getTrue(),
Chris Lattner08b22ec2005-05-13 07:09:09 +00006484 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6485 if (!OldCall->use_empty())
6486 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6487 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6488 return EraseInstFromFunction(*OldCall);
6489 return 0;
6490 }
6491
Chris Lattner17be6352004-10-18 02:59:09 +00006492 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6493 // This instruction is not reachable, just remove it. We insert a store to
6494 // undef so that we know that this code is not reachable, despite the fact
6495 // that we can't modify the CFG here.
Chris Lattner47811b72006-09-28 23:35:22 +00006496 new StoreInst(ConstantBool::getTrue(),
Chris Lattner17be6352004-10-18 02:59:09 +00006497 UndefValue::get(PointerType::get(Type::BoolTy)),
6498 CS.getInstruction());
6499
6500 if (!CS.getInstruction()->use_empty())
6501 CS.getInstruction()->
6502 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6503
6504 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6505 // Don't break the CFG, insert a dummy cond branch.
6506 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Chris Lattner47811b72006-09-28 23:35:22 +00006507 ConstantBool::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00006508 }
Chris Lattner17be6352004-10-18 02:59:09 +00006509 return EraseInstFromFunction(*CS.getInstruction());
6510 }
Chris Lattnere87597f2004-10-16 18:11:37 +00006511
Chris Lattner6c266db2003-10-07 22:54:13 +00006512 const PointerType *PTy = cast<PointerType>(Callee->getType());
6513 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6514 if (FTy->isVarArg()) {
6515 // See if we can optimize any arguments passed through the varargs area of
6516 // the call.
6517 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6518 E = CS.arg_end(); I != E; ++I)
6519 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6520 // If this cast does not effect the value passed through the varargs
6521 // area, we can eliminate the use of the cast.
6522 Value *Op = CI->getOperand(0);
6523 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6524 *I = Op;
6525 Changed = true;
6526 }
6527 }
6528 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006529
Chris Lattner6c266db2003-10-07 22:54:13 +00006530 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00006531}
6532
Chris Lattner9fe38862003-06-19 17:00:31 +00006533// transformConstExprCastCall - If the callee is a constexpr cast of a function,
6534// attempt to move the cast to the arguments of the call/invoke.
6535//
6536bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6537 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6538 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Chris Lattner9db07b92004-07-18 18:59:44 +00006539 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00006540 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00006541 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00006542 Instruction *Caller = CS.getInstruction();
6543
6544 // Okay, this is a cast from a function to a different type. Unless doing so
6545 // would cause a type conversion of one of our arguments, change this call to
6546 // be a direct call with arguments casted to the appropriate types.
6547 //
6548 const FunctionType *FT = Callee->getFunctionType();
6549 const Type *OldRetTy = Caller->getType();
6550
Chris Lattnerf78616b2004-01-14 06:06:08 +00006551 // Check to see if we are changing the return type...
6552 if (OldRetTy != FT->getReturnType()) {
6553 if (Callee->isExternal() &&
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00006554 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6555 (isa<PointerType>(FT->getReturnType()) &&
Andrew Lenharth7a31b972006-04-20 15:41:37 +00006556 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
Andrew Lenharth8117f9a2006-04-20 14:56:47 +00006557 && !Caller->use_empty())
Chris Lattnerf78616b2004-01-14 06:06:08 +00006558 return false; // Cannot transform this return value...
6559
6560 // If the callsite is an invoke instruction, and the return value is used by
6561 // a PHI node in a successor, we cannot change the return type of the call
6562 // because there is no place to put the cast instruction (without breaking
6563 // the critical edge). Bail out in this case.
6564 if (!Caller->use_empty())
6565 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6566 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6567 UI != E; ++UI)
6568 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6569 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00006570 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00006571 return false;
6572 }
Chris Lattner9fe38862003-06-19 17:00:31 +00006573
6574 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6575 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00006576
Chris Lattner9fe38862003-06-19 17:00:31 +00006577 CallSite::arg_iterator AI = CS.arg_begin();
6578 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6579 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00006580 const Type *ActTy = (*AI)->getType();
Reid Spencerb83eb642006-10-20 07:07:24 +00006581 ConstantInt* c = dyn_cast<ConstantInt>(*AI);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00006582 //Either we can cast directly, or we can upconvert the argument
6583 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6584 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6585 ParamTy->isSigned() == ActTy->isSigned() &&
6586 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6587 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
Reid Spencerb83eb642006-10-20 07:07:24 +00006588 c->getSExtValue() > 0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006589 if (Callee->isExternal() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00006590 }
6591
6592 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6593 Callee->isExternal())
6594 return false; // Do not delete arguments unless we have a function body...
6595
6596 // Okay, we decided that this is a safe thing to do: go ahead and start
6597 // inserting cast instructions as necessary...
6598 std::vector<Value*> Args;
6599 Args.reserve(NumActualArgs);
6600
6601 AI = CS.arg_begin();
6602 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6603 const Type *ParamTy = FT->getParamType(i);
6604 if ((*AI)->getType() == ParamTy) {
6605 Args.push_back(*AI);
6606 } else {
Chris Lattner0c199a72004-04-08 04:43:23 +00006607 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6608 *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00006609 }
6610 }
6611
6612 // If the function takes more arguments than the call was taking, add them
6613 // now...
6614 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6615 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6616
6617 // If we are removing arguments to the function, emit an obnoxious warning...
6618 if (FT->getNumParams() < NumActualArgs)
6619 if (!FT->isVarArg()) {
6620 std::cerr << "WARNING: While resolving call to function '"
6621 << Callee->getName() << "' arguments were dropped!\n";
6622 } else {
6623 // Add all of the arguments in their promoted form to the arg list...
6624 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6625 const Type *PTy = getPromotedType((*AI)->getType());
6626 if (PTy != (*AI)->getType()) {
6627 // Must promote to pass through va_arg area!
6628 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6629 InsertNewInstBefore(Cast, *Caller);
6630 Args.push_back(Cast);
6631 } else {
6632 Args.push_back(*AI);
6633 }
6634 }
6635 }
6636
6637 if (FT->getReturnType() == Type::VoidTy)
6638 Caller->setName(""); // Void type should not have a name...
6639
6640 Instruction *NC;
6641 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00006642 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
Chris Lattner9fe38862003-06-19 17:00:31 +00006643 Args, Caller->getName(), Caller);
Chris Lattnere4370262005-05-14 12:25:32 +00006644 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00006645 } else {
6646 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
Chris Lattnera9e92112005-05-06 06:48:21 +00006647 if (cast<CallInst>(Caller)->isTailCall())
6648 cast<CallInst>(NC)->setTailCall();
Chris Lattnere4370262005-05-14 12:25:32 +00006649 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Chris Lattner9fe38862003-06-19 17:00:31 +00006650 }
6651
6652 // Insert a cast of the return type as necessary...
6653 Value *NV = NC;
6654 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6655 if (NV->getType() != Type::VoidTy) {
6656 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00006657
6658 // If this is an invoke instruction, we should insert it after the first
6659 // non-phi, instruction in the normal successor block.
6660 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6661 BasicBlock::iterator I = II->getNormalDest()->begin();
6662 while (isa<PHINode>(I)) ++I;
6663 InsertNewInstBefore(NC, *I);
6664 } else {
6665 // Otherwise, it's a call, just insert cast right after the call instr
6666 InsertNewInstBefore(NC, *Caller);
6667 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00006668 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00006669 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00006670 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00006671 }
6672 }
6673
6674 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6675 Caller->replaceAllUsesWith(NV);
6676 Caller->getParent()->getInstList().erase(Caller);
6677 removeFromWorkList(Caller);
6678 return true;
6679}
6680
6681
Chris Lattnerbac32862004-11-14 19:13:23 +00006682// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6683// operator and they all are only used by the PHI, PHI together their
6684// inputs, and do the operation once, to the result of the PHI.
6685Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6686 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6687
6688 // Scan the instruction, looking for input operations that can be folded away.
6689 // If all input operands to the phi are the same instruction (e.g. a cast from
6690 // the same type or "+42") we can pull the operation through the PHI, reducing
6691 // code size and simplifying code.
6692 Constant *ConstantOp = 0;
6693 const Type *CastSrcTy = 0;
6694 if (isa<CastInst>(FirstInst)) {
6695 CastSrcTy = FirstInst->getOperand(0)->getType();
6696 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6697 // Can fold binop or shift if the RHS is a constant.
6698 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6699 if (ConstantOp == 0) return 0;
6700 } else {
6701 return 0; // Cannot fold this operation.
6702 }
6703
6704 // Check to see if all arguments are the same operation.
6705 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6706 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6707 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6708 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6709 return 0;
6710 if (CastSrcTy) {
6711 if (I->getOperand(0)->getType() != CastSrcTy)
6712 return 0; // Cast operation must match.
6713 } else if (I->getOperand(1) != ConstantOp) {
6714 return 0;
6715 }
6716 }
6717
6718 // Okay, they are all the same operation. Create a new PHI node of the
6719 // correct type, and PHI together all of the LHS's of the instructions.
6720 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6721 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00006722 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00006723
6724 Value *InVal = FirstInst->getOperand(0);
6725 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00006726
6727 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00006728 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6729 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6730 if (NewInVal != InVal)
6731 InVal = 0;
6732 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6733 }
6734
6735 Value *PhiVal;
6736 if (InVal) {
6737 // The new PHI unions all of the same values together. This is really
6738 // common, so we handle it intelligently here for compile-time speed.
6739 PhiVal = InVal;
6740 delete NewPN;
6741 } else {
6742 InsertNewInstBefore(NewPN, PN);
6743 PhiVal = NewPN;
6744 }
Misha Brukmanfd939082005-04-21 23:48:37 +00006745
Chris Lattnerbac32862004-11-14 19:13:23 +00006746 // Insert and return the new operation.
6747 if (isa<CastInst>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00006748 return new CastInst(PhiVal, PN.getType());
Chris Lattnerbac32862004-11-14 19:13:23 +00006749 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00006750 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00006751 else
6752 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
Chris Lattnerb5893442004-11-14 19:29:34 +00006753 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00006754}
Chris Lattnera1be5662002-05-02 17:06:02 +00006755
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006756/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6757/// that is dead.
6758static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6759 if (PN->use_empty()) return true;
6760 if (!PN->hasOneUse()) return false;
6761
6762 // Remember this node, and if we find the cycle, return.
6763 if (!PotentiallyDeadPHIs.insert(PN).second)
6764 return true;
6765
6766 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6767 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00006768
Chris Lattnera3fd1c52005-01-17 05:10:15 +00006769 return false;
6770}
6771
Chris Lattner473945d2002-05-06 18:06:38 +00006772// PHINode simplification
6773//
Chris Lattner7e708292002-06-25 16:13:24 +00006774Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00006775 // If LCSSA is around, don't mess with Phi nodes
6776 if (mustPreserveAnalysisID(LCSSAID)) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00006777
Owen Anderson7e057142006-07-10 22:03:18 +00006778 if (Value *V = PN.hasConstantValue())
6779 return ReplaceInstUsesWith(PN, V);
6780
6781 // If the only user of this instruction is a cast instruction, and all of the
6782 // incoming values are constants, change this PHI to merge together the casted
6783 // constants.
6784 if (PN.hasOneUse())
6785 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6786 if (CI->getType() != PN.getType()) { // noop casts will be folded
6787 bool AllConstant = true;
6788 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6789 if (!isa<Constant>(PN.getIncomingValue(i))) {
6790 AllConstant = false;
6791 break;
6792 }
6793 if (AllConstant) {
6794 // Make a new PHI with all casted values.
6795 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6796 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6797 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6798 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6799 PN.getIncomingBlock(i));
6800 }
6801
6802 // Update the cast instruction.
6803 CI->setOperand(0, New);
6804 WorkList.push_back(CI); // revisit the cast instruction to fold.
6805 WorkList.push_back(New); // Make sure to revisit the new Phi
6806 return &PN; // PN is now dead!
6807 }
6808 }
6809
6810 // If all PHI operands are the same operation, pull them through the PHI,
6811 // reducing code size.
6812 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6813 PN.getIncomingValue(0)->hasOneUse())
6814 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6815 return Result;
6816
6817 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6818 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6819 // PHI)... break the cycle.
6820 if (PN.hasOneUse())
6821 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6822 std::set<PHINode*> PotentiallyDeadPHIs;
6823 PotentiallyDeadPHIs.insert(&PN);
6824 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6825 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6826 }
6827
Chris Lattner60921c92003-12-19 05:58:40 +00006828 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00006829}
6830
Chris Lattner28977af2004-04-05 01:30:19 +00006831static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6832 Instruction *InsertPoint,
6833 InstCombiner *IC) {
6834 unsigned PS = IC->getTargetData().getPointerSize();
6835 const Type *VTy = V->getType();
Chris Lattner28977af2004-04-05 01:30:19 +00006836 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6837 // We must insert a cast to ensure we sign-extend.
6838 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6839 V->getName()), *InsertPoint);
6840 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6841 *InsertPoint);
6842}
6843
Chris Lattnera1be5662002-05-02 17:06:02 +00006844
Chris Lattner7e708292002-06-25 16:13:24 +00006845Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00006846 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc54e2b82003-05-22 19:07:21 +00006847 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00006848 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006849 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00006850 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006851
Chris Lattnere87597f2004-10-16 18:11:37 +00006852 if (isa<UndefValue>(GEP.getOperand(0)))
6853 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6854
Chris Lattnerc6bd1952004-02-22 05:25:17 +00006855 bool HasZeroPointerIndex = false;
6856 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6857 HasZeroPointerIndex = C->isNullValue();
6858
6859 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00006860 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00006861
Chris Lattner28977af2004-04-05 01:30:19 +00006862 // Eliminate unneeded casts for indices.
6863 bool MadeChange = false;
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006864 gep_type_iterator GTI = gep_type_begin(GEP);
6865 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6866 if (isa<SequentialType>(*GTI)) {
6867 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6868 Value *Src = CI->getOperand(0);
6869 const Type *SrcTy = Src->getType();
6870 const Type *DestTy = CI->getType();
6871 if (Src->getType()->isInteger()) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006872 if (SrcTy->getPrimitiveSizeInBits() ==
6873 DestTy->getPrimitiveSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006874 // We can always eliminate a cast from ulong or long to the other.
6875 // We can always eliminate a cast from uint to int or the other on
6876 // 32-bit pointer platforms.
Chris Lattner484d3cf2005-04-24 06:59:08 +00006877 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006878 MadeChange = true;
6879 GEP.setOperand(i, Src);
6880 }
6881 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6882 SrcTy->getPrimitiveSize() == 4) {
6883 // We can always eliminate a cast from int to [u]long. We can
6884 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6885 // pointer target.
Misha Brukmanfd939082005-04-21 23:48:37 +00006886 if (SrcTy->isSigned() ||
Chris Lattner484d3cf2005-04-24 06:59:08 +00006887 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006888 MadeChange = true;
6889 GEP.setOperand(i, Src);
6890 }
Chris Lattner28977af2004-04-05 01:30:19 +00006891 }
6892 }
6893 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006894 // If we are using a wider index than needed for this platform, shrink it
6895 // to what we need. If the incoming value needs a cast instruction,
6896 // insert it. This explicit cast can make subsequent optimizations more
6897 // obvious.
6898 Value *Op = GEP.getOperand(i);
6899 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
Chris Lattner4f1134e2004-04-17 18:16:10 +00006900 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner67769e52004-07-20 01:48:15 +00006901 GEP.setOperand(i, ConstantExpr::getCast(C,
6902 TD->getIntPtrType()->getSignedVersion()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00006903 MadeChange = true;
6904 } else {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00006905 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6906 Op->getName()), GEP);
6907 GEP.setOperand(i, Op);
6908 MadeChange = true;
6909 }
Chris Lattner67769e52004-07-20 01:48:15 +00006910
6911 // If this is a constant idx, make sure to canonicalize it to be a signed
6912 // operand, otherwise CSE and other optimizations are pessimized.
Reid Spencerb83eb642006-10-20 07:07:24 +00006913 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op))
6914 if (CUI->getType()->isUnsigned()) {
6915 GEP.setOperand(i,
6916 ConstantExpr::getCast(CUI, CUI->getType()->getSignedVersion()));
6917 MadeChange = true;
6918 }
Chris Lattner28977af2004-04-05 01:30:19 +00006919 }
6920 if (MadeChange) return &GEP;
6921
Chris Lattner90ac28c2002-08-02 19:29:35 +00006922 // Combine Indices - If the source pointer to this getelementptr instruction
6923 // is a getelementptr instruction, combine the indices of the two
6924 // getelementptr instructions into a single instruction.
6925 //
Chris Lattnerebd985c2004-03-25 22:59:29 +00006926 std::vector<Value*> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00006927 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattnerebd985c2004-03-25 22:59:29 +00006928 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00006929
6930 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00006931 // Note that if our source is a gep chain itself that we wait for that
6932 // chain to be resolved before we perform this transformation. This
6933 // avoids us creating a TON of code in some cases.
6934 //
6935 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6936 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6937 return 0; // Wait until our source is folded to completion.
6938
Chris Lattner90ac28c2002-08-02 19:29:35 +00006939 std::vector<Value *> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00006940
6941 // Find out whether the last index in the source GEP is a sequential idx.
6942 bool EndsWithSequential = false;
6943 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6944 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00006945 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00006946
Chris Lattner90ac28c2002-08-02 19:29:35 +00006947 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00006948 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00006949 // Replace: gep (gep %P, long B), long A, ...
6950 // With: T = long A+B; gep %P, T, ...
6951 //
Chris Lattner620ce142004-05-07 22:09:22 +00006952 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00006953 if (SO1 == Constant::getNullValue(SO1->getType())) {
6954 Sum = GO1;
6955 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6956 Sum = SO1;
6957 } else {
6958 // If they aren't the same type, convert both to an integer of the
6959 // target's pointer size.
6960 if (SO1->getType() != GO1->getType()) {
6961 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6962 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6963 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6964 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6965 } else {
6966 unsigned PS = TD->getPointerSize();
Chris Lattner28977af2004-04-05 01:30:19 +00006967 if (SO1->getType()->getPrimitiveSize() == PS) {
6968 // Convert GO1 to SO1's type.
6969 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6970
6971 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6972 // Convert SO1 to GO1's type.
6973 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6974 } else {
6975 const Type *PT = TD->getIntPtrType();
6976 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6977 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6978 }
6979 }
6980 }
Chris Lattner620ce142004-05-07 22:09:22 +00006981 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6982 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6983 else {
Chris Lattner48595f12004-06-10 02:07:29 +00006984 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6985 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00006986 }
Chris Lattner28977af2004-04-05 01:30:19 +00006987 }
Chris Lattner620ce142004-05-07 22:09:22 +00006988
6989 // Recycle the GEP we already have if possible.
6990 if (SrcGEPOperands.size() == 2) {
6991 GEP.setOperand(0, SrcGEPOperands[0]);
6992 GEP.setOperand(1, Sum);
6993 return &GEP;
6994 } else {
6995 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6996 SrcGEPOperands.end()-1);
6997 Indices.push_back(Sum);
6998 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6999 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007000 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00007001 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007002 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00007003 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00007004 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7005 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00007006 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7007 }
7008
7009 if (!Indices.empty())
Chris Lattnerebd985c2004-03-25 22:59:29 +00007010 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00007011
Chris Lattner620ce142004-05-07 22:09:22 +00007012 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00007013 // GEP of global variable. If all of the indices for this GEP are
7014 // constants, we can promote this to a constexpr instead of an instruction.
7015
7016 // Scan for nonconstants...
7017 std::vector<Constant*> Indices;
7018 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7019 for (; I != E && isa<Constant>(*I); ++I)
7020 Indices.push_back(cast<Constant>(*I));
7021
7022 if (I == E) { // If they are all constants...
Chris Lattner9db07b92004-07-18 18:59:44 +00007023 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
Chris Lattner9b761232002-08-17 22:21:59 +00007024
7025 // Replace all uses of the GEP with the new constexpr...
7026 return ReplaceInstUsesWith(GEP, CE);
7027 }
Chris Lattnereed48272005-09-13 00:40:14 +00007028 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
7029 if (!isa<PointerType>(X->getType())) {
7030 // Not interesting. Source pointer must be a cast from pointer.
7031 } else if (HasZeroPointerIndex) {
7032 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7033 // into : GEP [10 x ubyte]* X, long 0, ...
7034 //
7035 // This occurs when the program declares an array extern like "int X[];"
7036 //
7037 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7038 const PointerType *XTy = cast<PointerType>(X->getType());
7039 if (const ArrayType *XATy =
7040 dyn_cast<ArrayType>(XTy->getElementType()))
7041 if (const ArrayType *CATy =
7042 dyn_cast<ArrayType>(CPTy->getElementType()))
7043 if (CATy->getElementType() == XATy->getElementType()) {
7044 // At this point, we know that the cast source type is a pointer
7045 // to an array of the same type as the destination pointer
7046 // array. Because the array type is never stepped over (there
7047 // is a leading zero) we can fold the cast into this GEP.
7048 GEP.setOperand(0, X);
7049 return &GEP;
7050 }
7051 } else if (GEP.getNumOperands() == 2) {
7052 // Transform things like:
Chris Lattner7835cdd2005-09-13 18:36:04 +00007053 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7054 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
Chris Lattnereed48272005-09-13 00:40:14 +00007055 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7056 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7057 if (isa<ArrayType>(SrcElTy) &&
7058 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7059 TD->getTypeSize(ResElTy)) {
7060 Value *V = InsertNewInstBefore(
7061 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7062 GEP.getOperand(1), GEP.getName()), GEP);
7063 return new CastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007064 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00007065
7066 // Transform things like:
7067 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7068 // (where tmp = 8*tmp2) into:
7069 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7070
7071 if (isa<ArrayType>(SrcElTy) &&
7072 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7073 uint64_t ArrayEltSize =
7074 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7075
7076 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7077 // allow either a mul, shift, or constant here.
7078 Value *NewIdx = 0;
7079 ConstantInt *Scale = 0;
7080 if (ArrayEltSize == 1) {
7081 NewIdx = GEP.getOperand(1);
7082 Scale = ConstantInt::get(NewIdx->getType(), 1);
7083 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00007084 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007085 Scale = CI;
7086 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7087 if (Inst->getOpcode() == Instruction::Shl &&
7088 isa<ConstantInt>(Inst->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007089 unsigned ShAmt =
7090 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
Chris Lattner7835cdd2005-09-13 18:36:04 +00007091 if (Inst->getType()->isSigned())
Reid Spencerb83eb642006-10-20 07:07:24 +00007092 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007093 else
Reid Spencerb83eb642006-10-20 07:07:24 +00007094 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
Chris Lattner7835cdd2005-09-13 18:36:04 +00007095 NewIdx = Inst->getOperand(0);
7096 } else if (Inst->getOpcode() == Instruction::Mul &&
7097 isa<ConstantInt>(Inst->getOperand(1))) {
7098 Scale = cast<ConstantInt>(Inst->getOperand(1));
7099 NewIdx = Inst->getOperand(0);
7100 }
7101 }
7102
7103 // If the index will be to exactly the right offset with the scale taken
7104 // out, perform the transformation.
Reid Spencerb83eb642006-10-20 07:07:24 +00007105 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7106 if (ConstantInt *C = dyn_cast<ConstantInt>(Scale))
7107 Scale = ConstantInt::get(Scale->getType(),
7108 Scale->getZExtValue() / ArrayEltSize);
7109 if (Scale->getZExtValue() != 1) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00007110 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7111 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7112 NewIdx = InsertNewInstBefore(Sc, GEP);
7113 }
7114
7115 // Insert the new GEP instruction.
7116 Instruction *Idx =
7117 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7118 NewIdx, GEP.getName());
7119 Idx = InsertNewInstBefore(Idx, GEP);
7120 return new CastInst(Idx, GEP.getType());
7121 }
7122 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00007123 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00007124 }
7125
Chris Lattner8a2a3112001-12-14 16:52:21 +00007126 return 0;
7127}
7128
Chris Lattner0864acf2002-11-04 16:18:53 +00007129Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7130 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7131 if (AI.isArrayAllocation()) // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00007132 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7133 const Type *NewTy =
7134 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00007135 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00007136
7137 // Create and insert the replacement instruction...
7138 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00007139 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00007140 else {
7141 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00007142 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00007143 }
Chris Lattner7c881df2004-03-19 06:08:10 +00007144
7145 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00007146
Chris Lattner0864acf2002-11-04 16:18:53 +00007147 // Scan to the end of the allocation instructions, to skip over a block of
7148 // allocas if possible...
7149 //
7150 BasicBlock::iterator It = New;
7151 while (isa<AllocationInst>(*It)) ++It;
7152
7153 // Now that I is pointing to the first non-allocation-inst in the block,
7154 // insert our getelementptr instruction...
7155 //
Chris Lattner693787a2005-05-04 19:10:26 +00007156 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7157 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7158 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00007159
7160 // Now make everything use the getelementptr instead of the original
7161 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00007162 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00007163 } else if (isa<UndefValue>(AI.getArraySize())) {
7164 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00007165 }
Chris Lattner7c881df2004-03-19 06:08:10 +00007166
7167 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7168 // Note that we only do this for alloca's, because malloc should allocate and
7169 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00007170 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Chris Lattnercf27afb2004-07-02 22:55:47 +00007171 TD->getTypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00007172 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7173
Chris Lattner0864acf2002-11-04 16:18:53 +00007174 return 0;
7175}
7176
Chris Lattner67b1e1b2003-12-07 01:24:23 +00007177Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7178 Value *Op = FI.getOperand(0);
7179
7180 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7181 if (CastInst *CI = dyn_cast<CastInst>(Op))
7182 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7183 FI.setOperand(0, CI->getOperand(0));
7184 return &FI;
7185 }
7186
Chris Lattner17be6352004-10-18 02:59:09 +00007187 // free undef -> unreachable.
7188 if (isa<UndefValue>(Op)) {
7189 // Insert a new store to null because we cannot modify the CFG here.
Chris Lattner47811b72006-09-28 23:35:22 +00007190 new StoreInst(ConstantBool::getTrue(),
Chris Lattner17be6352004-10-18 02:59:09 +00007191 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7192 return EraseInstFromFunction(FI);
7193 }
7194
Chris Lattner6160e852004-02-28 04:57:37 +00007195 // If we have 'free null' delete the instruction. This can happen in stl code
7196 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00007197 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00007198 return EraseInstFromFunction(FI);
Chris Lattner6160e852004-02-28 04:57:37 +00007199
Chris Lattner67b1e1b2003-12-07 01:24:23 +00007200 return 0;
7201}
7202
7203
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007204/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Chris Lattnerb89e0712004-07-13 01:49:43 +00007205static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7206 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00007207 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00007208
7209 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00007210 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00007211 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00007212
Chris Lattnera1c35382006-04-02 05:37:12 +00007213 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7214 isa<PackedType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00007215 // If the source is an array, the code below will not succeed. Check to
7216 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7217 // constants.
7218 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7219 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7220 if (ASrcTy->getNumElements() != 0) {
7221 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7222 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7223 SrcTy = cast<PointerType>(CastOp->getType());
7224 SrcPTy = SrcTy->getElementType();
7225 }
7226
Chris Lattnera1c35382006-04-02 05:37:12 +00007227 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7228 isa<PackedType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00007229 // Do not allow turning this into a load of an integer, which is then
7230 // casted to a pointer, this pessimizes pointer analysis a lot.
7231 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007232 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerf9527852005-01-31 04:50:46 +00007233 IC.getTargetData().getTypeSize(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00007234
Chris Lattnerf9527852005-01-31 04:50:46 +00007235 // Okay, we are casting from one integer or pointer type to another of
7236 // the same size. Instead of casting the pointer before the load, cast
7237 // the result of the loaded value.
7238 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7239 CI->getName(),
7240 LI.isVolatile()),LI);
7241 // Now cast the result of the load.
7242 return new CastInst(NewLoad, LI.getType());
7243 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00007244 }
7245 }
7246 return 0;
7247}
7248
Chris Lattnerc10aced2004-09-19 18:43:46 +00007249/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00007250/// from this value cannot trap. If it is not obviously safe to load from the
7251/// specified pointer, we do a quick local scan of the basic block containing
7252/// ScanFrom, to determine if the address is already accessed.
7253static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7254 // If it is an alloca or global variable, it is always safe to load from.
7255 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7256
7257 // Otherwise, be a little bit agressive by scanning the local block where we
7258 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00007259 // from/to. If so, the previous load or store would have already trapped,
7260 // so there is no harm doing an extra load (also, CSE will later eliminate
7261 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00007262 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7263
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00007264 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00007265 --BBI;
7266
7267 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7268 if (LI->getOperand(0) == V) return true;
7269 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7270 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00007271
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00007272 }
Chris Lattner8a375202004-09-19 19:18:10 +00007273 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00007274}
7275
Chris Lattner833b8a42003-06-26 05:06:25 +00007276Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7277 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00007278
Chris Lattner37366c12005-05-01 04:24:53 +00007279 // load (cast X) --> cast (load X) iff safe
7280 if (CastInst *CI = dyn_cast<CastInst>(Op))
7281 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7282 return Res;
7283
7284 // None of the following transforms are legal for volatile loads.
7285 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00007286
Chris Lattner62f254d2005-09-12 22:00:15 +00007287 if (&LI.getParent()->front() != &LI) {
7288 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00007289 // If the instruction immediately before this is a store to the same
7290 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00007291 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7292 if (SI->getOperand(1) == LI.getOperand(0))
7293 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00007294 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7295 if (LIB->getOperand(0) == LI.getOperand(0))
7296 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00007297 }
Chris Lattner37366c12005-05-01 04:24:53 +00007298
7299 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7300 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7301 isa<UndefValue>(GEPI->getOperand(0))) {
7302 // Insert a new store to null instruction before the load to indicate
7303 // that this code is not reachable. We do this instead of inserting
7304 // an unreachable instruction directly because we cannot modify the
7305 // CFG.
7306 new StoreInst(UndefValue::get(LI.getType()),
7307 Constant::getNullValue(Op->getType()), &LI);
7308 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7309 }
7310
Chris Lattnere87597f2004-10-16 18:11:37 +00007311 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00007312 // load null/undef -> undef
7313 if ((C->isNullValue() || isa<UndefValue>(C))) {
Chris Lattner17be6352004-10-18 02:59:09 +00007314 // Insert a new store to null instruction before the load to indicate that
7315 // this code is not reachable. We do this instead of inserting an
7316 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00007317 new StoreInst(UndefValue::get(LI.getType()),
7318 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00007319 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00007320 }
Chris Lattner833b8a42003-06-26 05:06:25 +00007321
Chris Lattnere87597f2004-10-16 18:11:37 +00007322 // Instcombine load (constant global) into the value loaded.
7323 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7324 if (GV->isConstant() && !GV->isExternal())
7325 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00007326
Chris Lattnere87597f2004-10-16 18:11:37 +00007327 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7328 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7329 if (CE->getOpcode() == Instruction::GetElementPtr) {
7330 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7331 if (GV->isConstant() && !GV->isExternal())
Chris Lattner363f2a22005-09-26 05:28:06 +00007332 if (Constant *V =
7333 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00007334 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00007335 if (CE->getOperand(0)->isNullValue()) {
7336 // Insert a new store to null instruction before the load to indicate
7337 // that this code is not reachable. We do this instead of inserting
7338 // an unreachable instruction directly because we cannot modify the
7339 // CFG.
7340 new StoreInst(UndefValue::get(LI.getType()),
7341 Constant::getNullValue(Op->getType()), &LI);
7342 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7343 }
7344
Chris Lattnere87597f2004-10-16 18:11:37 +00007345 } else if (CE->getOpcode() == Instruction::Cast) {
7346 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7347 return Res;
7348 }
7349 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00007350
Chris Lattner37366c12005-05-01 04:24:53 +00007351 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00007352 // Change select and PHI nodes to select values instead of addresses: this
7353 // helps alias analysis out a lot, allows many others simplifications, and
7354 // exposes redundancy in the code.
7355 //
7356 // Note that we cannot do the transformation unless we know that the
7357 // introduced loads cannot trap! Something like this is valid as long as
7358 // the condition is always false: load (select bool %C, int* null, int* %G),
7359 // but it would not be valid if we transformed it to load from null
7360 // unconditionally.
7361 //
7362 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7363 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00007364 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7365 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00007366 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00007367 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00007368 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00007369 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00007370 return new SelectInst(SI->getCondition(), V1, V2);
7371 }
7372
Chris Lattner684fe212004-09-23 15:46:00 +00007373 // load (select (cond, null, P)) -> load P
7374 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7375 if (C->isNullValue()) {
7376 LI.setOperand(0, SI->getOperand(2));
7377 return &LI;
7378 }
7379
7380 // load (select (cond, P, null)) -> load P
7381 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7382 if (C->isNullValue()) {
7383 LI.setOperand(0, SI->getOperand(1));
7384 return &LI;
7385 }
7386
Chris Lattnerc10aced2004-09-19 18:43:46 +00007387 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7388 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
Chris Lattner79f0c8e2004-09-20 10:15:10 +00007389 bool Safe = PN->getParent() == LI.getParent();
7390
7391 // Scan all of the instructions between the PHI and the load to make
7392 // sure there are no instructions that might possibly alter the value
7393 // loaded from the PHI.
7394 if (Safe) {
7395 BasicBlock::iterator I = &LI;
7396 for (--I; !isa<PHINode>(I); --I)
7397 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7398 Safe = false;
7399 break;
7400 }
7401 }
7402
7403 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
Chris Lattner8a375202004-09-19 19:18:10 +00007404 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00007405 PN->getIncomingBlock(i)->getTerminator()))
Chris Lattnerc10aced2004-09-19 18:43:46 +00007406 Safe = false;
Chris Lattner79f0c8e2004-09-20 10:15:10 +00007407
Chris Lattnerc10aced2004-09-19 18:43:46 +00007408 if (Safe) {
7409 // Create the PHI.
7410 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7411 InsertNewInstBefore(NewPN, *PN);
7412 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7413
7414 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7415 BasicBlock *BB = PN->getIncomingBlock(i);
7416 Value *&TheLoad = LoadMap[BB];
7417 if (TheLoad == 0) {
7418 Value *InVal = PN->getIncomingValue(i);
7419 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7420 InVal->getName()+".val"),
7421 *BB->getTerminator());
7422 }
7423 NewPN->addIncoming(TheLoad, BB);
7424 }
7425 return ReplaceInstUsesWith(LI, NewPN);
7426 }
7427 }
7428 }
Chris Lattner833b8a42003-06-26 05:06:25 +00007429 return 0;
7430}
7431
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007432/// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7433/// when possible.
7434static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7435 User *CI = cast<User>(SI.getOperand(1));
7436 Value *CastOp = CI->getOperand(0);
7437
7438 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7439 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7440 const Type *SrcPTy = SrcTy->getElementType();
7441
7442 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7443 // If the source is an array, the code below will not succeed. Check to
7444 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7445 // constants.
7446 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7447 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7448 if (ASrcTy->getNumElements() != 0) {
7449 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7450 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7451 SrcTy = cast<PointerType>(CastOp->getType());
7452 SrcPTy = SrcTy->getElementType();
7453 }
7454
7455 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007456 IC.getTargetData().getTypeSize(SrcPTy) ==
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007457 IC.getTargetData().getTypeSize(DestPTy)) {
7458
7459 // Okay, we are casting from one integer or pointer type to another of
7460 // the same size. Instead of casting the pointer before the store, cast
7461 // the value to be stored.
7462 Value *NewCast;
7463 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7464 NewCast = ConstantExpr::getCast(C, SrcPTy);
7465 else
7466 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7467 SrcPTy,
7468 SI.getOperand(0)->getName()+".c"), SI);
7469
7470 return new StoreInst(NewCast, CastOp);
7471 }
7472 }
7473 }
7474 return 0;
7475}
7476
Chris Lattner2f503e62005-01-31 05:36:43 +00007477Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7478 Value *Val = SI.getOperand(0);
7479 Value *Ptr = SI.getOperand(1);
7480
7481 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00007482 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00007483 ++NumCombined;
7484 return 0;
7485 }
7486
Chris Lattner9ca96412006-02-08 03:25:32 +00007487 // Do really simple DSE, to catch cases where there are several consequtive
7488 // stores to the same location, separated by a few arithmetic operations. This
7489 // situation often occurs with bitfield accesses.
7490 BasicBlock::iterator BBI = &SI;
7491 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7492 --ScanInsts) {
7493 --BBI;
7494
7495 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7496 // Prev store isn't volatile, and stores to the same location?
7497 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7498 ++NumDeadStore;
7499 ++BBI;
7500 EraseInstFromFunction(*PrevSI);
7501 continue;
7502 }
7503 break;
7504 }
7505
Chris Lattnerb4db97f2006-05-26 19:19:20 +00007506 // If this is a load, we have to stop. However, if the loaded value is from
7507 // the pointer we're loading and is producing the pointer we're storing,
7508 // then *this* store is dead (X = load P; store X -> P).
7509 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7510 if (LI == Val && LI->getOperand(0) == Ptr) {
7511 EraseInstFromFunction(SI);
7512 ++NumCombined;
7513 return 0;
7514 }
7515 // Otherwise, this is a load from some other location. Stores before it
7516 // may not be dead.
7517 break;
7518 }
7519
Chris Lattner9ca96412006-02-08 03:25:32 +00007520 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00007521 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00007522 break;
7523 }
7524
7525
7526 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00007527
7528 // store X, null -> turns into 'unreachable' in SimplifyCFG
7529 if (isa<ConstantPointerNull>(Ptr)) {
7530 if (!isa<UndefValue>(Val)) {
7531 SI.setOperand(0, UndefValue::get(Val->getType()));
7532 if (Instruction *U = dyn_cast<Instruction>(Val))
7533 WorkList.push_back(U); // Dropped a use.
7534 ++NumCombined;
7535 }
7536 return 0; // Do not modify these!
7537 }
7538
7539 // store undef, Ptr -> noop
7540 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00007541 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00007542 ++NumCombined;
7543 return 0;
7544 }
7545
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00007546 // If the pointer destination is a cast, see if we can fold the cast into the
7547 // source instead.
7548 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7549 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7550 return Res;
7551 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7552 if (CE->getOpcode() == Instruction::Cast)
7553 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7554 return Res;
7555
Chris Lattner408902b2005-09-12 23:23:25 +00007556
7557 // If this store is the last instruction in the basic block, and if the block
7558 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00007559 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00007560 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7561 if (BI->isUnconditional()) {
7562 // Check to see if the successor block has exactly two incoming edges. If
7563 // so, see if the other predecessor contains a store to the same location.
7564 // if so, insert a PHI node (if needed) and move the stores down.
7565 BasicBlock *Dest = BI->getSuccessor(0);
7566
7567 pred_iterator PI = pred_begin(Dest);
7568 BasicBlock *Other = 0;
7569 if (*PI != BI->getParent())
7570 Other = *PI;
7571 ++PI;
7572 if (PI != pred_end(Dest)) {
7573 if (*PI != BI->getParent())
7574 if (Other)
7575 Other = 0;
7576 else
7577 Other = *PI;
7578 if (++PI != pred_end(Dest))
7579 Other = 0;
7580 }
7581 if (Other) { // If only one other pred...
7582 BBI = Other->getTerminator();
7583 // Make sure this other block ends in an unconditional branch and that
7584 // there is an instruction before the branch.
7585 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7586 BBI != Other->begin()) {
7587 --BBI;
7588 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7589
7590 // If this instruction is a store to the same location.
7591 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7592 // Okay, we know we can perform this transformation. Insert a PHI
7593 // node now if we need it.
7594 Value *MergedVal = OtherStore->getOperand(0);
7595 if (MergedVal != SI.getOperand(0)) {
7596 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7597 PN->reserveOperandSpace(2);
7598 PN->addIncoming(SI.getOperand(0), SI.getParent());
7599 PN->addIncoming(OtherStore->getOperand(0), Other);
7600 MergedVal = InsertNewInstBefore(PN, Dest->front());
7601 }
7602
7603 // Advance to a place where it is safe to insert the new store and
7604 // insert it.
7605 BBI = Dest->begin();
7606 while (isa<PHINode>(BBI)) ++BBI;
7607 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7608 OtherStore->isVolatile()), *BBI);
7609
7610 // Nuke the old stores.
Chris Lattner9ca96412006-02-08 03:25:32 +00007611 EraseInstFromFunction(SI);
7612 EraseInstFromFunction(*OtherStore);
Chris Lattner408902b2005-09-12 23:23:25 +00007613 ++NumCombined;
7614 return 0;
7615 }
7616 }
7617 }
7618 }
7619
Chris Lattner2f503e62005-01-31 05:36:43 +00007620 return 0;
7621}
7622
7623
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00007624Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7625 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +00007626 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00007627 BasicBlock *TrueDest;
7628 BasicBlock *FalseDest;
7629 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7630 !isa<Constant>(X)) {
7631 // Swap Destinations and condition...
7632 BI.setCondition(X);
7633 BI.setSuccessor(0, FalseDest);
7634 BI.setSuccessor(1, TrueDest);
7635 return &BI;
7636 }
7637
7638 // Cannonicalize setne -> seteq
7639 Instruction::BinaryOps Op; Value *Y;
7640 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7641 TrueDest, FalseDest)))
7642 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7643 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7644 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7645 std::string Name = I->getName(); I->setName("");
7646 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7647 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
Chris Lattner40f5d702003-06-04 05:10:11 +00007648 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +00007649 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +00007650 BI.setSuccessor(0, FalseDest);
7651 BI.setSuccessor(1, TrueDest);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00007652 removeFromWorkList(I);
7653 I->getParent()->getInstList().erase(I);
7654 WorkList.push_back(cast<Instruction>(NewSCC));
Chris Lattner40f5d702003-06-04 05:10:11 +00007655 return &BI;
7656 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007657
Chris Lattnerc4d10eb2003-06-04 04:46:00 +00007658 return 0;
7659}
Chris Lattner0864acf2002-11-04 16:18:53 +00007660
Chris Lattner46238a62004-07-03 00:26:11 +00007661Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7662 Value *Cond = SI.getCondition();
7663 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7664 if (I->getOpcode() == Instruction::Add)
7665 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7666 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7667 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +00007668 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +00007669 AddRHS));
7670 SI.setOperand(0, I->getOperand(0));
7671 WorkList.push_back(I);
7672 return &SI;
7673 }
7674 }
7675 return 0;
7676}
7677
Chris Lattner220b0cf2006-03-05 00:22:33 +00007678/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7679/// is to leave as a vector operation.
7680static bool CheapToScalarize(Value *V, bool isConstant) {
7681 if (isa<ConstantAggregateZero>(V))
7682 return true;
7683 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7684 if (isConstant) return true;
7685 // If all elts are the same, we can extract.
7686 Constant *Op0 = C->getOperand(0);
7687 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7688 if (C->getOperand(i) != Op0)
7689 return false;
7690 return true;
7691 }
7692 Instruction *I = dyn_cast<Instruction>(V);
7693 if (!I) return false;
7694
7695 // Insert element gets simplified to the inserted element or is deleted if
7696 // this is constant idx extract element and its a constant idx insertelt.
7697 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7698 isa<ConstantInt>(I->getOperand(2)))
7699 return true;
7700 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7701 return true;
7702 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7703 if (BO->hasOneUse() &&
7704 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7705 CheapToScalarize(BO->getOperand(1), isConstant)))
7706 return true;
7707
7708 return false;
7709}
7710
Chris Lattner863bcff2006-05-25 23:48:38 +00007711/// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7712/// elements into values that are larger than the #elts in the input.
7713static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7714 unsigned NElts = SVI->getType()->getNumElements();
7715 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7716 return std::vector<unsigned>(NElts, 0);
7717 if (isa<UndefValue>(SVI->getOperand(2)))
7718 return std::vector<unsigned>(NElts, 2*NElts);
7719
7720 std::vector<unsigned> Result;
7721 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7722 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7723 if (isa<UndefValue>(CP->getOperand(i)))
7724 Result.push_back(NElts*2); // undef -> 8
7725 else
Reid Spencerb83eb642006-10-20 07:07:24 +00007726 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +00007727 return Result;
7728}
7729
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007730/// FindScalarElement - Given a vector and an element number, see if the scalar
7731/// value is already around as a register, for example if it were inserted then
7732/// extracted from the vector.
7733static Value *FindScalarElement(Value *V, unsigned EltNo) {
7734 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7735 const PackedType *PTy = cast<PackedType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +00007736 unsigned Width = PTy->getNumElements();
7737 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007738 return UndefValue::get(PTy->getElementType());
7739
7740 if (isa<UndefValue>(V))
7741 return UndefValue::get(PTy->getElementType());
7742 else if (isa<ConstantAggregateZero>(V))
7743 return Constant::getNullValue(PTy->getElementType());
7744 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7745 return CP->getOperand(EltNo);
7746 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7747 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +00007748 if (!isa<ConstantInt>(III->getOperand(2)))
7749 return 0;
7750 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007751
7752 // If this is an insert to the element we are looking for, return the
7753 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +00007754 if (EltNo == IIElt)
7755 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007756
7757 // Otherwise, the insertelement doesn't modify the value, recurse on its
7758 // vector input.
7759 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +00007760 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +00007761 unsigned InEl = getShuffleMask(SVI)[EltNo];
7762 if (InEl < Width)
7763 return FindScalarElement(SVI->getOperand(0), InEl);
7764 else if (InEl < Width*2)
7765 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7766 else
7767 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007768 }
7769
7770 // Otherwise, we don't know.
7771 return 0;
7772}
7773
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007774Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007775
Chris Lattner1f13c882006-03-31 18:25:14 +00007776 // If packed val is undef, replace extract with scalar undef.
7777 if (isa<UndefValue>(EI.getOperand(0)))
7778 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7779
7780 // If packed val is constant 0, replace extract with scalar 0.
7781 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7782 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7783
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007784 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7785 // If packed val is constant with uniform operands, replace EI
7786 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +00007787 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007788 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +00007789 if (C->getOperand(i) != op0) {
7790 op0 = 0;
7791 break;
7792 }
7793 if (op0)
7794 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007795 }
Chris Lattner220b0cf2006-03-05 00:22:33 +00007796
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007797 // If extracting a specified index from the vector, see if we can recursively
7798 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +00007799 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner867b99f2006-10-05 06:55:50 +00007800 // This instruction only demands the single element from the input vector.
7801 // If the input vector has a single use, simplify it based on this use
7802 // property.
Reid Spencerb83eb642006-10-20 07:07:24 +00007803 uint64_t IndexVal = IdxC->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00007804 if (EI.getOperand(0)->hasOneUse()) {
7805 uint64_t UndefElts;
7806 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +00007807 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +00007808 UndefElts)) {
7809 EI.setOperand(0, V);
7810 return &EI;
7811 }
7812 }
7813
Reid Spencerb83eb642006-10-20 07:07:24 +00007814 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007815 return ReplaceInstUsesWith(EI, Elt);
Chris Lattner389a6f52006-04-10 23:06:36 +00007816 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +00007817
Chris Lattner73fa49d2006-05-25 22:53:38 +00007818 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007819 if (I->hasOneUse()) {
7820 // Push extractelement into predecessor operation if legal and
7821 // profitable to do so
7822 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +00007823 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7824 if (CheapToScalarize(BO, isConstantElt)) {
7825 ExtractElementInst *newEI0 =
7826 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7827 EI.getName()+".lhs");
7828 ExtractElementInst *newEI1 =
7829 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7830 EI.getName()+".rhs");
7831 InsertNewInstBefore(newEI0, EI);
7832 InsertNewInstBefore(newEI1, EI);
7833 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7834 }
7835 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007836 Value *Ptr = InsertCastBefore(I->getOperand(0),
7837 PointerType::get(EI.getType()), EI);
7838 GetElementPtrInst *GEP =
7839 new GetElementPtrInst(Ptr, EI.getOperand(1),
7840 I->getName() + ".gep");
7841 InsertNewInstBefore(GEP, EI);
7842 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +00007843 }
7844 }
7845 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7846 // Extracting the inserted element?
7847 if (IE->getOperand(2) == EI.getOperand(1))
7848 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7849 // If the inserted and extracted elements are constants, they must not
7850 // be the same value, extract from the pre-inserted value instead.
7851 if (isa<Constant>(IE->getOperand(2)) &&
7852 isa<Constant>(EI.getOperand(1))) {
7853 AddUsesToWorkList(EI);
7854 EI.setOperand(0, IE->getOperand(0));
7855 return &EI;
7856 }
7857 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7858 // If this is extracting an element from a shufflevector, figure out where
7859 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +00007860 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
7861 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +00007862 Value *Src;
7863 if (SrcIdx < SVI->getType()->getNumElements())
7864 Src = SVI->getOperand(0);
7865 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7866 SrcIdx -= SVI->getType()->getNumElements();
7867 Src = SVI->getOperand(1);
7868 } else {
7869 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +00007870 }
Chris Lattner867b99f2006-10-05 06:55:50 +00007871 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007872 }
7873 }
Chris Lattner73fa49d2006-05-25 22:53:38 +00007874 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +00007875 return 0;
7876}
7877
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007878/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7879/// elements from either LHS or RHS, return the shuffle mask and true.
7880/// Otherwise, return false.
7881static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7882 std::vector<Constant*> &Mask) {
7883 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7884 "Invalid CollectSingleShuffleElements");
7885 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7886
7887 if (isa<UndefValue>(V)) {
7888 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7889 return true;
7890 } else if (V == LHS) {
7891 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00007892 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007893 return true;
7894 } else if (V == RHS) {
7895 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00007896 Mask.push_back(ConstantInt::get(Type::UIntTy, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007897 return true;
7898 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7899 // If this is an insert of an extract from some other vector, include it.
7900 Value *VecOp = IEI->getOperand(0);
7901 Value *ScalarOp = IEI->getOperand(1);
7902 Value *IdxOp = IEI->getOperand(2);
7903
Chris Lattnerd929f062006-04-27 21:14:21 +00007904 if (!isa<ConstantInt>(IdxOp))
7905 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +00007906 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +00007907
7908 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7909 // Okay, we can handle this if the vector we are insertinting into is
7910 // transitively ok.
7911 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7912 // If so, update the mask to reflect the inserted undef.
7913 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7914 return true;
7915 }
7916 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7917 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007918 EI->getOperand(0)->getType() == V->getType()) {
7919 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00007920 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007921
7922 // This must be extracting from either LHS or RHS.
7923 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7924 // Okay, we can handle this if the vector we are insertinting into is
7925 // transitively ok.
7926 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7927 // If so, update the mask to reflect the inserted value.
7928 if (EI->getOperand(0) == LHS) {
7929 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerb83eb642006-10-20 07:07:24 +00007930 ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007931 } else {
7932 assert(EI->getOperand(0) == RHS);
7933 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerb83eb642006-10-20 07:07:24 +00007934 ConstantInt::get(Type::UIntTy, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007935
7936 }
7937 return true;
7938 }
7939 }
7940 }
7941 }
7942 }
7943 // TODO: Handle shufflevector here!
7944
7945 return false;
7946}
7947
7948/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7949/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7950/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +00007951static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007952 Value *&RHS) {
7953 assert(isa<PackedType>(V->getType()) &&
7954 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +00007955 "Invalid shuffle!");
7956 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7957
7958 if (isa<UndefValue>(V)) {
7959 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7960 return V;
7961 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007962 Mask.assign(NumElts, ConstantInt::get(Type::UIntTy, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +00007963 return V;
7964 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7965 // If this is an insert of an extract from some other vector, include it.
7966 Value *VecOp = IEI->getOperand(0);
7967 Value *ScalarOp = IEI->getOperand(1);
7968 Value *IdxOp = IEI->getOperand(2);
7969
7970 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7971 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7972 EI->getOperand(0)->getType() == V->getType()) {
7973 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +00007974 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
7975 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00007976
7977 // Either the extracted from or inserted into vector must be RHSVec,
7978 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007979 if (EI->getOperand(0) == RHS || RHS == 0) {
7980 RHS = EI->getOperand(0);
7981 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00007982 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerb83eb642006-10-20 07:07:24 +00007983 ConstantInt::get(Type::UIntTy, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00007984 return V;
7985 }
7986
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007987 if (VecOp == RHS) {
7988 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +00007989 // Everything but the extracted element is replaced with the RHS.
7990 for (unsigned i = 0; i != NumElts; ++i) {
7991 if (i != InsertedIdx)
Reid Spencerb83eb642006-10-20 07:07:24 +00007992 Mask[i] = ConstantInt::get(Type::UIntTy, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +00007993 }
7994 return V;
7995 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00007996
7997 // If this insertelement is a chain that comes from exactly these two
7998 // vectors, return the vector and the effective shuffle.
7999 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8000 return EI->getOperand(0);
8001
Chris Lattnerefb47352006-04-15 01:39:45 +00008002 }
8003 }
8004 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008005 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +00008006
8007 // Otherwise, can't do anything fancy. Return an identity vector.
8008 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerb83eb642006-10-20 07:07:24 +00008009 Mask.push_back(ConstantInt::get(Type::UIntTy, i));
Chris Lattnerefb47352006-04-15 01:39:45 +00008010 return V;
8011}
8012
8013Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8014 Value *VecOp = IE.getOperand(0);
8015 Value *ScalarOp = IE.getOperand(1);
8016 Value *IdxOp = IE.getOperand(2);
8017
8018 // If the inserted element was extracted from some other vector, and if the
8019 // indexes are constant, try to turn this into a shufflevector operation.
8020 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8021 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8022 EI->getOperand(0)->getType() == IE.getType()) {
8023 unsigned NumVectorElts = IE.getType()->getNumElements();
Reid Spencerb83eb642006-10-20 07:07:24 +00008024 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8025 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +00008026
8027 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8028 return ReplaceInstUsesWith(IE, VecOp);
8029
8030 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8031 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8032
8033 // If we are extracting a value from a vector, then inserting it right
8034 // back into the same place, just use the input vector.
8035 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8036 return ReplaceInstUsesWith(IE, VecOp);
8037
8038 // We could theoretically do this for ANY input. However, doing so could
8039 // turn chains of insertelement instructions into a chain of shufflevector
8040 // instructions, and right now we do not merge shufflevectors. As such,
8041 // only do this in a situation where it is clear that there is benefit.
8042 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8043 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8044 // the values of VecOp, except then one read from EIOp0.
8045 // Build a new shuffle mask.
8046 std::vector<Constant*> Mask;
8047 if (isa<UndefValue>(VecOp))
8048 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8049 else {
8050 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerb83eb642006-10-20 07:07:24 +00008051 Mask.assign(NumVectorElts, ConstantInt::get(Type::UIntTy,
Chris Lattnerefb47352006-04-15 01:39:45 +00008052 NumVectorElts));
8053 }
Reid Spencerb83eb642006-10-20 07:07:24 +00008054 Mask[InsertedIdx] = ConstantInt::get(Type::UIntTy, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +00008055 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8056 ConstantPacked::get(Mask));
8057 }
8058
8059 // If this insertelement isn't used by some other insertelement, turn it
8060 // (and any insertelements it points to), into one big shuffle.
8061 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8062 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +00008063 Value *RHS = 0;
8064 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8065 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8066 // We now have a shuffle of LHS, RHS, Mask.
8067 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +00008068 }
8069 }
8070 }
8071
8072 return 0;
8073}
8074
8075
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008076Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8077 Value *LHS = SVI.getOperand(0);
8078 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +00008079 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008080
8081 bool MadeChange = false;
8082
Chris Lattner867b99f2006-10-05 06:55:50 +00008083 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +00008084 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008085 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8086
Chris Lattnerefb47352006-04-15 01:39:45 +00008087 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8088 // the undef, change them to undefs.
8089
Chris Lattner863bcff2006-05-25 23:48:38 +00008090 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8091 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8092 if (LHS == RHS || isa<UndefValue>(LHS)) {
8093 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008094 // shuffle(undef,undef,mask) -> undef.
8095 return ReplaceInstUsesWith(SVI, LHS);
8096 }
8097
Chris Lattner863bcff2006-05-25 23:48:38 +00008098 // Remap any references to RHS to use LHS.
8099 std::vector<Constant*> Elts;
8100 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +00008101 if (Mask[i] >= 2*e)
Chris Lattner863bcff2006-05-25 23:48:38 +00008102 Elts.push_back(UndefValue::get(Type::UIntTy));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008103 else {
8104 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8105 (Mask[i] < e && isa<UndefValue>(LHS)))
8106 Mask[i] = 2*e; // Turn into undef.
8107 else
8108 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerb83eb642006-10-20 07:07:24 +00008109 Elts.push_back(ConstantInt::get(Type::UIntTy, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008110 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008111 }
Chris Lattner863bcff2006-05-25 23:48:38 +00008112 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008113 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Chris Lattner863bcff2006-05-25 23:48:38 +00008114 SVI.setOperand(2, ConstantPacked::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008115 LHS = SVI.getOperand(0);
8116 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008117 MadeChange = true;
8118 }
8119
Chris Lattner7b2e27922006-05-26 00:29:06 +00008120 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +00008121 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +00008122
Chris Lattner863bcff2006-05-25 23:48:38 +00008123 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8124 if (Mask[i] >= e*2) continue; // Ignore undef values.
8125 // Is this an identity shuffle of the LHS value?
8126 isLHSID &= (Mask[i] == i);
8127
8128 // Is this an identity shuffle of the RHS value?
8129 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +00008130 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008131
Chris Lattner863bcff2006-05-25 23:48:38 +00008132 // Eliminate identity shuffles.
8133 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8134 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008135
Chris Lattner7b2e27922006-05-26 00:29:06 +00008136 // If the LHS is a shufflevector itself, see if we can combine it with this
8137 // one without producing an unusual shuffle. Here we are really conservative:
8138 // we are absolutely afraid of producing a shuffle mask not in the input
8139 // program, because the code gen may not be smart enough to turn a merged
8140 // shuffle into two specific shuffles: it may produce worse code. As such,
8141 // we only merge two shuffles if the result is one of the two input shuffle
8142 // masks. In this case, merging the shuffles just removes one instruction,
8143 // which we know is safe. This is good for things like turning:
8144 // (splat(splat)) -> splat.
8145 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8146 if (isa<UndefValue>(RHS)) {
8147 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8148
8149 std::vector<unsigned> NewMask;
8150 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8151 if (Mask[i] >= 2*e)
8152 NewMask.push_back(2*e);
8153 else
8154 NewMask.push_back(LHSMask[Mask[i]]);
8155
8156 // If the result mask is equal to the src shuffle or this shuffle mask, do
8157 // the replacement.
8158 if (NewMask == LHSMask || NewMask == Mask) {
8159 std::vector<Constant*> Elts;
8160 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8161 if (NewMask[i] >= e*2) {
8162 Elts.push_back(UndefValue::get(Type::UIntTy));
8163 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00008164 Elts.push_back(ConstantInt::get(Type::UIntTy, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +00008165 }
8166 }
8167 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8168 LHSSVI->getOperand(1),
8169 ConstantPacked::get(Elts));
8170 }
8171 }
8172 }
8173
Chris Lattnera844fc4c2006-04-10 22:45:52 +00008174 return MadeChange ? &SVI : 0;
8175}
8176
8177
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008178
Chris Lattner62b14df2002-09-02 04:59:56 +00008179void InstCombiner::removeFromWorkList(Instruction *I) {
8180 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8181 WorkList.end());
8182}
8183
Chris Lattnerea1c4542004-12-08 23:43:58 +00008184
8185/// TryToSinkInstruction - Try to move the specified instruction from its
8186/// current block into the beginning of DestBlock, which can only happen if it's
8187/// safe to move the instruction past all of the instructions between it and the
8188/// end of its block.
8189static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8190 assert(I->hasOneUse() && "Invariants didn't hold!");
8191
Chris Lattner108e9022005-10-27 17:13:11 +00008192 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8193 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +00008194
Chris Lattnerea1c4542004-12-08 23:43:58 +00008195 // Do not sink alloca instructions out of the entry block.
8196 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8197 return false;
8198
Chris Lattner96a52a62004-12-09 07:14:34 +00008199 // We can only sink load instructions if there is nothing between the load and
8200 // the end of block that could change the value.
8201 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +00008202 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8203 Scan != E; ++Scan)
8204 if (Scan->mayWriteToMemory())
8205 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +00008206 }
Chris Lattnerea1c4542004-12-08 23:43:58 +00008207
8208 BasicBlock::iterator InsertPos = DestBlock->begin();
8209 while (isa<PHINode>(InsertPos)) ++InsertPos;
8210
Chris Lattner4bc5f802005-08-08 19:11:57 +00008211 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +00008212 ++NumSunkInst;
8213 return true;
8214}
8215
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008216/// OptimizeConstantExpr - Given a constant expression and target data layout
8217/// information, symbolically evaluation the constant expr to something simpler
8218/// if possible.
8219static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8220 if (!TD) return CE;
8221
8222 Constant *Ptr = CE->getOperand(0);
8223 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8224 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8225 // If this is a constant expr gep that is effectively computing an
8226 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8227 bool isFoldableGEP = true;
8228 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8229 if (!isa<ConstantInt>(CE->getOperand(i)))
8230 isFoldableGEP = false;
8231 if (isFoldableGEP) {
8232 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8233 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
Reid Spencerb83eb642006-10-20 07:07:24 +00008234 Constant *C = ConstantInt::get(Type::ULongTy, Offset);
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008235 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8236 return ConstantExpr::getCast(C, CE->getType());
8237 }
8238 }
8239
8240 return CE;
8241}
8242
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008243
8244/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8245/// all reachable code to the worklist.
8246///
8247/// This has a couple of tricks to make the code faster and more powerful. In
8248/// particular, we constant fold and DCE instructions as we go, to avoid adding
8249/// them to the worklist (this significantly speeds up instcombine on code where
8250/// many instructions are dead or constant). Additionally, if we find a branch
8251/// whose condition is a known constant, we only visit the reachable successors.
8252///
8253static void AddReachableCodeToWorklist(BasicBlock *BB,
8254 std::set<BasicBlock*> &Visited,
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008255 std::vector<Instruction*> &WorkList,
8256 const TargetData *TD) {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008257 // We have now visited this block! If we've already been here, bail out.
8258 if (!Visited.insert(BB).second) return;
8259
8260 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8261 Instruction *Inst = BBI++;
8262
8263 // DCE instruction if trivially dead.
8264 if (isInstructionTriviallyDead(Inst)) {
8265 ++NumDeadInst;
8266 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8267 Inst->eraseFromParent();
8268 continue;
8269 }
8270
8271 // ConstantProp instruction if trivially constant.
8272 if (Constant *C = ConstantFoldInstruction(Inst)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008273 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8274 C = OptimizeConstantExpr(CE, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008275 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8276 Inst->replaceAllUsesWith(C);
8277 ++NumConstProp;
8278 Inst->eraseFromParent();
8279 continue;
8280 }
8281
8282 WorkList.push_back(Inst);
8283 }
8284
8285 // Recursively visit successors. If this is a branch or switch on a constant,
8286 // only visit the reachable successor.
8287 TerminatorInst *TI = BB->getTerminator();
8288 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8289 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8290 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008291 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8292 TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008293 return;
8294 }
8295 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8296 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8297 // See if this is an explicit destination.
8298 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8299 if (SI->getCaseValue(i) == Cond) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008300 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008301 return;
8302 }
8303
8304 // Otherwise it is the default destination.
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008305 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008306 return;
8307 }
8308 }
8309
8310 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008311 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008312}
8313
Chris Lattner7e708292002-06-25 16:13:24 +00008314bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008315 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +00008316 TD = &getAnalysis<TargetData>();
Chris Lattner8a2a3112001-12-14 16:52:21 +00008317
Chris Lattnerb3d59702005-07-07 20:40:38 +00008318 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008319 // Do a depth-first traversal of the function, populate the worklist with
8320 // the reachable instructions. Ignore blocks that are not reachable. Keep
8321 // track of which blocks we visit.
Chris Lattnerb3d59702005-07-07 20:40:38 +00008322 std::set<BasicBlock*> Visited;
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008323 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +00008324
Chris Lattnerb3d59702005-07-07 20:40:38 +00008325 // Do a quick scan over the function. If we find any blocks that are
8326 // unreachable, remove any instructions inside of them. This prevents
8327 // the instcombine code from having to deal with some bad special cases.
8328 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8329 if (!Visited.count(BB)) {
8330 Instruction *Term = BB->getTerminator();
8331 while (Term != BB->begin()) { // Remove instrs bottom-up
8332 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +00008333
Chris Lattnerb3d59702005-07-07 20:40:38 +00008334 DEBUG(std::cerr << "IC: DCE: " << *I);
8335 ++NumDeadInst;
8336
8337 if (!I->use_empty())
8338 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8339 I->eraseFromParent();
8340 }
8341 }
8342 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00008343
8344 while (!WorkList.empty()) {
8345 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8346 WorkList.pop_back();
8347
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008348 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00008349 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008350 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +00008351 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008352 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +00008353 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +00008354
Chris Lattnerad5fec12005-01-28 19:32:01 +00008355 DEBUG(std::cerr << "IC: DCE: " << *I);
8356
8357 I->eraseFromParent();
Chris Lattner4bb7c022003-10-06 17:11:01 +00008358 removeFromWorkList(I);
8359 continue;
8360 }
Chris Lattner62b14df2002-09-02 04:59:56 +00008361
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008362 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner62b14df2002-09-02 04:59:56 +00008363 if (Constant *C = ConstantFoldInstruction(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8365 C = OptimizeConstantExpr(CE, TD);
Chris Lattnerad5fec12005-01-28 19:32:01 +00008366 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8367
Chris Lattner8c8c66a2006-05-11 17:11:52 +00008368 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008369 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +00008370 ReplaceInstUsesWith(*I, C);
8371
Chris Lattner62b14df2002-09-02 04:59:56 +00008372 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +00008373 I->eraseFromParent();
Chris Lattner60610002003-10-07 15:17:02 +00008374 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008375 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +00008376 }
Chris Lattner4bb7c022003-10-06 17:11:01 +00008377
Chris Lattnerea1c4542004-12-08 23:43:58 +00008378 // See if we can trivially sink this instruction to a successor basic block.
8379 if (I->hasOneUse()) {
8380 BasicBlock *BB = I->getParent();
8381 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8382 if (UserParent != BB) {
8383 bool UserIsSuccessor = false;
8384 // See if the user is one of our successors.
8385 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8386 if (*SI == UserParent) {
8387 UserIsSuccessor = true;
8388 break;
8389 }
8390
8391 // If the user is one of our immediate successors, and if that successor
8392 // only has us as a predecessors (we'd have to split the critical edge
8393 // otherwise), we can keep going.
8394 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8395 next(pred_begin(UserParent)) == pred_end(UserParent))
8396 // Okay, the CFG is simple enough, try to sink this instruction.
8397 Changed |= TryToSinkInstruction(I, UserParent);
8398 }
8399 }
8400
Chris Lattner8a2a3112001-12-14 16:52:21 +00008401 // Now that we have an instruction, try combining it to simplify it...
Chris Lattner90ac28c2002-08-02 19:29:35 +00008402 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +00008403 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008404 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00008405 if (Result != I) {
Chris Lattner0cea42a2004-03-13 23:54:27 +00008406 DEBUG(std::cerr << "IC: Old = " << *I
8407 << " New = " << *Result);
8408
Chris Lattnerf523d062004-06-09 05:08:07 +00008409 // Everything uses the new instruction now.
8410 I->replaceAllUsesWith(Result);
8411
8412 // Push the new instruction and any users onto the worklist.
8413 WorkList.push_back(Result);
8414 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008415
8416 // Move the name to the new instruction first...
8417 std::string OldName = I->getName(); I->setName("");
Chris Lattnerd558dc32003-10-07 22:58:41 +00008418 Result->setName(OldName);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008419
8420 // Insert the new instruction into the basic block...
8421 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +00008422 BasicBlock::iterator InsertPos = I;
8423
8424 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8425 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8426 ++InsertPos;
8427
8428 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008429
Chris Lattner00d51312004-05-01 23:27:23 +00008430 // Make sure that we reprocess all operands now that we reduced their
8431 // use counts.
Chris Lattner216d4d82004-05-01 23:19:52 +00008432 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8433 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8434 WorkList.push_back(OpI);
8435
Chris Lattnerf523d062004-06-09 05:08:07 +00008436 // Instructions can end up on the worklist more than once. Make sure
8437 // we do not process an instruction that has been deleted.
8438 removeFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +00008439
8440 // Erase the old instruction.
8441 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +00008442 } else {
Chris Lattner0cea42a2004-03-13 23:54:27 +00008443 DEBUG(std::cerr << "IC: MOD = " << *I);
8444
Chris Lattner90ac28c2002-08-02 19:29:35 +00008445 // If the instruction was modified, it's possible that it is now dead.
8446 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +00008447 if (isInstructionTriviallyDead(I)) {
8448 // Make sure we process all operands now that we are reducing their
8449 // use counts.
8450 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8451 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8452 WorkList.push_back(OpI);
Misha Brukmanfd939082005-04-21 23:48:37 +00008453
Chris Lattner00d51312004-05-01 23:27:23 +00008454 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +00008455 // occurrences of this instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +00008456 removeFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +00008457 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +00008458 } else {
8459 WorkList.push_back(Result);
8460 AddUsersToWorkList(*Result);
Chris Lattner90ac28c2002-08-02 19:29:35 +00008461 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +00008462 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008463 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008464 }
8465 }
8466
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008467 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +00008468}
8469
Brian Gaeke96d4bf72004-07-27 17:43:21 +00008470FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008471 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +00008472}
Brian Gaeked0fde302003-11-11 22:41:34 +00008473