blob: 8ebd2cca6128341d146289134beabb9b3e4a5cca [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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 Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %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.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp 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 Lattner79066fa2007-01-30 23:46:24 +000042#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000043#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000046#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000048#include "llvm/Support/Debug.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000050#include "llvm/Support/InstVisitor.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000051#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000052#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000053#include "llvm/Support/Compiler.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000054#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000055#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000056#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000057#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000058#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000059#include <algorithm>
Reid Spencera9b81012007-03-26 17:44:01 +000060#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000061using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000062using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000063
Chris Lattner0e5f4992006-12-19 21:40:18 +000064STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000071 class VISIBILITY_HIDDEN InstCombiner
72 : public FunctionPass,
73 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000074 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000075 std::vector<Instruction*> Worklist;
76 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000077 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000078 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000079 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000080 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000081 InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
Chris Lattnerdbab3862007-03-02 21:28:56 +000083 /// AddToWorkList - Add the specified instruction to the worklist if it
84 /// isn't already in it.
85 void AddToWorkList(Instruction *I) {
86 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87 Worklist.push_back(I);
88 }
89
90 // RemoveFromWorkList - remove I from the worklist if it exists.
91 void RemoveFromWorkList(Instruction *I) {
92 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93 if (It == WorklistMap.end()) return; // Not in worklist.
94
95 // Don't bother moving everything down, just null out the slot.
96 Worklist[It->second] = 0;
97
98 WorklistMap.erase(It);
99 }
100
101 Instruction *RemoveOneFromWorkList() {
102 Instruction *I = Worklist.back();
103 Worklist.pop_back();
104 WorklistMap.erase(I);
105 return I;
106 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000107
Chris Lattnerdbab3862007-03-02 21:28:56 +0000108
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000109 /// AddUsersToWorkList - When an instruction is simplified, add all users of
110 /// the instruction to the work lists because they might get more simplified
111 /// now.
112 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000113 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000114 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000115 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000116 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000117 }
118
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000119 /// AddUsesToWorkList - When an instruction is simplified, add operands to
120 /// the work lists because they might get more simplified now.
121 ///
122 void AddUsesToWorkList(Instruction &I) {
123 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000125 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000126 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000127
128 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129 /// dead. Add all of its operands to the worklist, turning them into
130 /// undef's to reduce the number of uses of those instructions.
131 ///
132 /// Return the specified operand before it is turned into an undef.
133 ///
134 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135 Value *R = I.getOperand(op);
136
137 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000139 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000140 // Set the operand to undef to drop the use.
141 I.setOperand(i, UndefValue::get(Op->getType()));
142 }
143
144 return R;
145 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000146
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000147 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000148 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000149
150 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000151
Chris Lattner97e52e42002-04-28 21:27:06 +0000152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000153 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000154 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000155 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000156 }
157
Chris Lattner28977af2004-04-05 01:30:19 +0000158 TargetData &getTargetData() const { return *TD; }
159
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000160 // Visitation implementation - Implement instruction combining for different
161 // instruction types. The semantics are as follows:
162 // Return Value:
163 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000164 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000165 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000166 //
Chris Lattner7e708292002-06-25 16:13:24 +0000167 Instruction *visitAdd(BinaryOperator &I);
168 Instruction *visitSub(BinaryOperator &I);
169 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000170 Instruction *visitURem(BinaryOperator &I);
171 Instruction *visitSRem(BinaryOperator &I);
172 Instruction *visitFRem(BinaryOperator &I);
173 Instruction *commonRemTransforms(BinaryOperator &I);
174 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000175 Instruction *commonDivTransforms(BinaryOperator &I);
176 Instruction *commonIDivTransforms(BinaryOperator &I);
177 Instruction *visitUDiv(BinaryOperator &I);
178 Instruction *visitSDiv(BinaryOperator &I);
179 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000180 Instruction *visitAnd(BinaryOperator &I);
181 Instruction *visitOr (BinaryOperator &I);
182 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000183 Instruction *visitShl(BinaryOperator &I);
184 Instruction *visitAShr(BinaryOperator &I);
185 Instruction *visitLShr(BinaryOperator &I);
186 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000187 Instruction *visitFCmpInst(FCmpInst &I);
188 Instruction *visitICmpInst(ICmpInst &I);
189 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000190 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191 Instruction *LHS,
192 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000193 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000195
Reid Spencere4d87aa2006-12-23 06:05:41 +0000196 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000198 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000199 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000200 Instruction *commonCastTransforms(CastInst &CI);
201 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000202 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000203 Instruction *visitTrunc(TruncInst &CI);
204 Instruction *visitZExt(ZExtInst &CI);
205 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000206 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000207 Instruction *visitFPExt(CastInst &CI);
208 Instruction *visitFPToUI(CastInst &CI);
209 Instruction *visitFPToSI(CastInst &CI);
210 Instruction *visitUIToFP(CastInst &CI);
211 Instruction *visitSIToFP(CastInst &CI);
212 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000213 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000214 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000215 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000217 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000218 Instruction *visitCallInst(CallInst &CI);
219 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitPHINode(PHINode &PN);
221 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000222 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000223 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000224 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000225 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000226 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000227 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000228 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000229 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000230 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000231
232 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000233 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000234
Chris Lattner9fe38862003-06-19 17:00:31 +0000235 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000236 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000237 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000238 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000239 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
240 bool DoXform = true);
Chris Lattner9fe38862003-06-19 17:00:31 +0000241
Chris Lattner28977af2004-04-05 01:30:19 +0000242 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000243 // InsertNewInstBefore - insert an instruction New before instruction Old
244 // in the program. Add the new instruction to the worklist.
245 //
Chris Lattner955f3312004-09-28 21:48:02 +0000246 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000247 assert(New && New->getParent() == 0 &&
248 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000249 BasicBlock *BB = Old.getParent();
250 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000251 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000252 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000253 }
254
Chris Lattner0c967662004-09-24 15:21:34 +0000255 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
256 /// This also adds the cast to the worklist. Finally, this returns the
257 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000258 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
259 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000260 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000261
Chris Lattnere2ed0572006-04-06 19:19:17 +0000262 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000263 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000264
Reid Spencer17212df2006-12-12 09:18:51 +0000265 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000266 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000267 return C;
268 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000269
270 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
271 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
272 }
273
Chris Lattner0c967662004-09-24 15:21:34 +0000274
Chris Lattner8b170942002-08-09 23:47:40 +0000275 // ReplaceInstUsesWith - This method is to be used when an instruction is
276 // found to be dead, replacable with another preexisting expression. Here
277 // we add all uses of I to the worklist, replace all uses of I with the new
278 // value, then return I, so that the inst combiner will know that I was
279 // modified.
280 //
281 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000282 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000283 if (&I != V) {
284 I.replaceAllUsesWith(V);
285 return &I;
286 } else {
287 // If we are replacing the instruction with itself, this must be in a
288 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000289 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000290 return &I;
291 }
Chris Lattner8b170942002-08-09 23:47:40 +0000292 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000293
Chris Lattner6dce1a72006-02-07 06:56:34 +0000294 // UpdateValueUsesWith - This method is to be used when an value is
295 // found to be replacable with another preexisting expression or was
296 // updated. Here we add all uses of I to the worklist, replace all uses of
297 // I with the new value (unless the instruction was just updated), then
298 // return true, so that the inst combiner will know that I was modified.
299 //
300 bool UpdateValueUsesWith(Value *Old, Value *New) {
301 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
302 if (Old != New)
303 Old->replaceAllUsesWith(New);
304 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000305 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000306 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000307 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000308 return true;
309 }
310
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000311 // EraseInstFromFunction - When dealing with an instruction that has side
312 // effects or produces a void value, we can't rely on DCE to delete the
313 // instruction. Instead, visit methods should return the value returned by
314 // this function.
315 Instruction *EraseInstFromFunction(Instruction &I) {
316 assert(I.use_empty() && "Cannot erase instruction that is used!");
317 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000318 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000319 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000320 return 0; // Don't do anything with FI
321 }
322
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000323 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000324 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
325 /// InsertBefore instruction. This is specialized a bit to avoid inserting
326 /// casts that are known to not do anything...
327 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000328 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
329 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000330 Instruction *InsertBefore);
331
Reid Spencere4d87aa2006-12-23 06:05:41 +0000332 /// SimplifyCommutative - This performs a few simplifications for
333 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000334 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000335
Reid Spencere4d87aa2006-12-23 06:05:41 +0000336 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
337 /// most-complex to least-complex order.
338 bool SimplifyCompare(CmpInst &I);
339
Reid Spencer2ec619a2007-03-23 21:24:59 +0000340 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
341 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000342 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
343 APInt& KnownZero, APInt& KnownOne,
344 unsigned Depth = 0);
345
Chris Lattner867b99f2006-10-05 06:55:50 +0000346 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
347 uint64_t &UndefElts, unsigned Depth = 0);
348
Chris Lattner4e998b22004-09-29 05:07:12 +0000349 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
350 // PHI node as operand #0, see if we can fold the instruction into the PHI
351 // (which is only possible if all operands to the PHI are constants).
352 Instruction *FoldOpIntoPhi(Instruction &I);
353
Chris Lattnerbac32862004-11-14 19:13:23 +0000354 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
355 // operator and they all are only used by the PHI, PHI together their
356 // inputs, and do the operation once, to the result of the PHI.
357 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000358 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
359
360
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000361 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
362 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000363
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000364 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000365 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000366 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000367 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000368 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000369 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000370 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000371 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
372
Chris Lattnerafe91a52006-06-15 19:07:26 +0000373
Reid Spencerc55b2432006-12-13 18:21:21 +0000374 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000375 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000376
Devang Patel19974732007-05-03 01:11:54 +0000377 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000378 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000379}
380
Chris Lattner4f98c562003-03-10 21:43:22 +0000381// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000382// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000383static unsigned getComplexity(Value *V) {
384 if (isa<Instruction>(V)) {
385 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000386 return 3;
387 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000388 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000389 if (isa<Argument>(V)) return 3;
390 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000391}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000392
Chris Lattnerc8802d22003-03-11 00:12:48 +0000393// isOnlyUse - Return true if this instruction will be deleted if we stop using
394// it.
395static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000396 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000397}
398
Chris Lattner4cb170c2004-02-23 06:38:22 +0000399// getPromotedType - Return the specified type promoted as it would be to pass
400// though a va_arg area...
401static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000402 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
403 if (ITy->getBitWidth() < 32)
404 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000405 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000406 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000407}
408
Reid Spencer3da59db2006-11-27 01:05:10 +0000409/// getBitCastOperand - If the specified operand is a CastInst or a constant
410/// expression bitcast, return the operand value, otherwise return null.
411static Value *getBitCastOperand(Value *V) {
412 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000413 return I->getOperand(0);
414 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000415 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000416 return CE->getOperand(0);
417 return 0;
418}
419
Reid Spencer3da59db2006-11-27 01:05:10 +0000420/// This function is a wrapper around CastInst::isEliminableCastPair. It
421/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000422static Instruction::CastOps
423isEliminableCastPair(
424 const CastInst *CI, ///< The first cast instruction
425 unsigned opcode, ///< The opcode of the second cast instruction
426 const Type *DstTy, ///< The target type for the second cast instruction
427 TargetData *TD ///< The target data for pointer size
428) {
429
430 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
431 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000432
Reid Spencer3da59db2006-11-27 01:05:10 +0000433 // Get the opcodes of the two Cast instructions
434 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
435 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000436
Reid Spencer3da59db2006-11-27 01:05:10 +0000437 return Instruction::CastOps(
438 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
439 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000440}
441
442/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
443/// in any code being generated. It does not require codegen if V is simple
444/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000445static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
446 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000447 if (V->getType() == Ty || isa<Constant>(V)) return false;
448
Chris Lattner01575b72006-05-25 23:24:33 +0000449 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000450 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000451 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000452 return false;
453 return true;
454}
455
456/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
457/// InsertBefore instruction. This is specialized a bit to avoid inserting
458/// casts that are known to not do anything...
459///
Reid Spencer17212df2006-12-12 09:18:51 +0000460Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
461 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000462 Instruction *InsertBefore) {
463 if (V->getType() == DestTy) return V;
464 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000465 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000466
Reid Spencer17212df2006-12-12 09:18:51 +0000467 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000468}
469
Chris Lattner4f98c562003-03-10 21:43:22 +0000470// SimplifyCommutative - This performs a few simplifications for commutative
471// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000472//
Chris Lattner4f98c562003-03-10 21:43:22 +0000473// 1. Order operands such that they are listed from right (least complex) to
474// left (most complex). This puts constants before unary operators before
475// binary operators.
476//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000477// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
478// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000479//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000480bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000481 bool Changed = false;
482 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
483 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000484
Chris Lattner4f98c562003-03-10 21:43:22 +0000485 if (!I.isAssociative()) return Changed;
486 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000487 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
488 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
489 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000490 Constant *Folded = ConstantExpr::get(I.getOpcode(),
491 cast<Constant>(I.getOperand(1)),
492 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000493 I.setOperand(0, Op->getOperand(0));
494 I.setOperand(1, Folded);
495 return true;
496 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
497 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
498 isOnlyUse(Op) && isOnlyUse(Op1)) {
499 Constant *C1 = cast<Constant>(Op->getOperand(1));
500 Constant *C2 = cast<Constant>(Op1->getOperand(1));
501
502 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000503 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000504 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
505 Op1->getOperand(0),
506 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000507 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000508 I.setOperand(0, New);
509 I.setOperand(1, Folded);
510 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000511 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000512 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000513 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000514}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000515
Reid Spencere4d87aa2006-12-23 06:05:41 +0000516/// SimplifyCompare - For a CmpInst this function just orders the operands
517/// so that theyare listed from right (least complex) to left (most complex).
518/// This puts constants before unary operators before binary operators.
519bool InstCombiner::SimplifyCompare(CmpInst &I) {
520 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
521 return false;
522 I.swapOperands();
523 // Compare instructions are not associative so there's nothing else we can do.
524 return true;
525}
526
Chris Lattner8d969642003-03-10 23:06:50 +0000527// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
528// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000529//
Chris Lattner8d969642003-03-10 23:06:50 +0000530static inline Value *dyn_castNegVal(Value *V) {
531 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000532 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000533
Chris Lattner0ce85802004-12-14 20:08:06 +0000534 // Constants can be considered to be negated values if they can be folded.
535 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
536 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000537 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000538}
539
Chris Lattner8d969642003-03-10 23:06:50 +0000540static inline Value *dyn_castNotVal(Value *V) {
541 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000542 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000543
544 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000545 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000546 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000547 return 0;
548}
549
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550// dyn_castFoldableMul - If this value is a multiply that can be folded into
551// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000552// non-constant operand of the multiply, and set CST to point to the multiplier.
553// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000554//
Chris Lattner50af16a2004-11-13 19:50:12 +0000555static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000556 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000557 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000558 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000559 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000560 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000561 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000562 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000563 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000564 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000565 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000566 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000567 return I->getOperand(0);
568 }
569 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000570 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000571}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000572
Chris Lattner574da9b2005-01-13 20:14:25 +0000573/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
574/// expression, return it.
575static User *dyn_castGetElementPtr(Value *V) {
576 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
578 if (CE->getOpcode() == Instruction::GetElementPtr)
579 return cast<User>(V);
580 return false;
581}
582
Reid Spencer7177c3a2007-03-25 05:33:51 +0000583/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000584static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000585 APInt Val(C->getValue());
586 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000587}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000588/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000589static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000590 APInt Val(C->getValue());
591 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000592}
593/// Add - Add two ConstantInts together
594static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
595 return ConstantInt::get(C1->getValue() + C2->getValue());
596}
597/// And - Bitwise AND two ConstantInts together
598static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
599 return ConstantInt::get(C1->getValue() & C2->getValue());
600}
601/// Subtract - Subtract one ConstantInt from another
602static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
603 return ConstantInt::get(C1->getValue() - C2->getValue());
604}
605/// Multiply - Multiply two ConstantInts together
606static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
607 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000608}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000609/// MultiplyOverflows - True if the multiply can not be expressed in an int
610/// this size.
611static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
612 uint32_t W = C1->getBitWidth();
613 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
614 if (sign) {
615 LHSExt.sext(W * 2);
616 RHSExt.sext(W * 2);
617 } else {
618 LHSExt.zext(W * 2);
619 RHSExt.zext(W * 2);
620 }
621
622 APInt MulExt = LHSExt * RHSExt;
623
624 if (sign) {
625 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
626 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
627 return MulExt.slt(Min) || MulExt.sgt(Max);
628 } else
629 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
630}
Chris Lattner955f3312004-09-28 21:48:02 +0000631
Chris Lattner68d5ff22006-02-09 07:38:58 +0000632/// ComputeMaskedBits - Determine which of the bits specified in Mask are
633/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000634/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
635/// processing.
636/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
637/// we cannot optimize based on the assumption that it is zero without changing
638/// it to be an explicit zero. If we don't change it to zero, other code could
639/// optimized based on the contradictory assumption that it is non-zero.
640/// Because instcombine aggressively folds operations with undef args anyway,
641/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000642static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000643 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000644 assert(V && "No Value?");
645 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000646 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000647 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000648 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000649 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000650 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000651 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
652 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000653 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000654 KnownZero = ~KnownOne & Mask;
655 return;
656 }
657
Reid Spencer3e7594f2007-03-08 01:46:38 +0000658 if (Depth == 6 || Mask == 0)
659 return; // Limit search depth.
660
661 Instruction *I = dyn_cast<Instruction>(V);
662 if (!I) return;
663
Zhou Sheng771dbf72007-03-13 02:23:10 +0000664 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000665 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000666
667 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000668 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000669 // If either the LHS or the RHS are Zero, the result is zero.
670 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000671 APInt Mask2(Mask & ~KnownZero);
672 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
674 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
675
676 // Output known-1 bits are only known if set in both the LHS & RHS.
677 KnownOne &= KnownOne2;
678 // Output known-0 are known to be clear if zero in either the LHS | RHS.
679 KnownZero |= KnownZero2;
680 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000681 }
682 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000683 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000684 APInt Mask2(Mask & ~KnownOne);
685 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000686 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
687 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
688
689 // Output known-0 bits are only known if clear in both the LHS & RHS.
690 KnownZero &= KnownZero2;
691 // Output known-1 are known to be set if set in either the LHS | RHS.
692 KnownOne |= KnownOne2;
693 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000694 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000695 case Instruction::Xor: {
696 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
697 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
698 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
699 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
700
701 // Output known-0 bits are known if clear or set in both the LHS & RHS.
702 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
703 // Output known-1 are known to be set if set in only one of the LHS, RHS.
704 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
705 KnownZero = KnownZeroOut;
706 return;
707 }
708 case Instruction::Select:
709 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
710 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
711 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
712 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
713
714 // Only known if known in both the LHS and RHS.
715 KnownOne &= KnownOne2;
716 KnownZero &= KnownZero2;
717 return;
718 case Instruction::FPTrunc:
719 case Instruction::FPExt:
720 case Instruction::FPToUI:
721 case Instruction::FPToSI:
722 case Instruction::SIToFP:
723 case Instruction::PtrToInt:
724 case Instruction::UIToFP:
725 case Instruction::IntToPtr:
726 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000727 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000728 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000729 uint32_t SrcBitWidth =
730 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000731 APInt MaskIn(Mask);
732 MaskIn.zext(SrcBitWidth);
733 KnownZero.zext(SrcBitWidth);
734 KnownOne.zext(SrcBitWidth);
735 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000736 KnownZero.trunc(BitWidth);
737 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000738 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000739 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000740 case Instruction::BitCast: {
741 const Type *SrcTy = I->getOperand(0)->getType();
742 if (SrcTy->isInteger()) {
743 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
744 return;
745 }
746 break;
747 }
748 case Instruction::ZExt: {
749 // Compute the bits in the result that are not present in the input.
750 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000751 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000752
Zhou Shengaa305ab2007-03-28 02:19:03 +0000753 APInt MaskIn(Mask);
754 MaskIn.trunc(SrcBitWidth);
755 KnownZero.trunc(SrcBitWidth);
756 KnownOne.trunc(SrcBitWidth);
757 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
759 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000760 KnownZero.zext(BitWidth);
761 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000762 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000763 return;
764 }
765 case Instruction::SExt: {
766 // Compute the bits in the result that are not present in the input.
767 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000768 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000769
Zhou Shengaa305ab2007-03-28 02:19:03 +0000770 APInt MaskIn(Mask);
771 MaskIn.trunc(SrcBitWidth);
772 KnownZero.trunc(SrcBitWidth);
773 KnownOne.trunc(SrcBitWidth);
774 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000775 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000776 KnownZero.zext(BitWidth);
777 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000778
779 // If the sign bit of the input is known set or clear, then we know the
780 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000781 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000782 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000783 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000784 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000785 return;
786 }
787 case Instruction::Shl:
788 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
789 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000790 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000791 APInt Mask2(Mask.lshr(ShiftAmt));
792 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000793 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000794 KnownZero <<= ShiftAmt;
795 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000796 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000797 return;
798 }
799 break;
800 case Instruction::LShr:
801 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
802 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
803 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000804 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000805
806 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000807 APInt Mask2(Mask.shl(ShiftAmt));
808 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000809 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
810 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
811 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000812 // high bits known zero.
813 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000814 return;
815 }
816 break;
817 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000818 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000819 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
820 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000821 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000822
823 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000824 APInt Mask2(Mask.shl(ShiftAmt));
825 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000826 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
827 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
828 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
829
Zhou Shengaa305ab2007-03-28 02:19:03 +0000830 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
831 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000832 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000833 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000834 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000835 return;
836 }
837 break;
Duncan Sands1d57a752008-03-21 08:32:17 +0000838 case Instruction::Add: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000839 // If either the LHS or the RHS are Zero, the result is zero.
840 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
841 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
842 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
843 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
844
845 // Output known-0 bits are known if clear or set in both the low clear bits
846 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
847 // low 3 bits clear.
848 unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(),
849 KnownZero2.countTrailingOnes());
850
851 KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
852 KnownOne = APInt(BitWidth, 0);
853 return;
Duncan Sands1d57a752008-03-21 08:32:17 +0000854 }
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000855 case Instruction::Sub: {
856 ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0));
857 if (!CLHS) break;
858
859 // We know that the top bits of C-X are clear if X contains less bits
860 // than C (i.e. no wrap-around can happen). For example, 20-X is
861 // positive if we can prove that X is >= 0 and < 16.
862 if (CLHS->getValue().isNegative())
863 break;
864
865 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
866 // NLZ can't be BitWidth with no sign bit
867 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
868 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
869
870 // If all of the MaskV bits are known to be zero, then we know the output
871 // top bits are zero, because we now know that the output is from [0-C].
872 if ((KnownZero & MaskV) == MaskV) {
873 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
874 // Top bits known zero.
875 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
876 KnownOne = APInt(BitWidth, 0); // No one bits known.
877 } else {
878 KnownZero = KnownOne = APInt(BitWidth, 0); // Otherwise, nothing known.
879 }
880 return;
881 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000882 case Instruction::SRem:
883 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
884 APInt RA = Rem->getValue();
885 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
886 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
887 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
888 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
889
890 // The sign of a remainder is equal to the sign of the first
891 // operand (zero being positive).
892 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
893 KnownZero2 |= ~LowBits;
894 else if (KnownOne2[BitWidth-1])
895 KnownOne2 |= ~LowBits;
896
897 KnownZero |= KnownZero2 & Mask;
898 KnownOne |= KnownOne2 & Mask;
899
900 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
901 }
902 }
903 break;
904 case Instruction::URem:
905 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
906 APInt RA = Rem->getValue();
907 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
908 APInt LowBits = (RA - 1) | RA;
909 APInt Mask2 = LowBits & Mask;
910 KnownZero |= ~LowBits & Mask;
911 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
912 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
913 }
914 } else {
915 // Since the result is less than or equal to RHS, any leading zero bits
916 // in RHS must also exist in the result.
917 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner41dc0fc2008-03-21 05:19:58 +0000918 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
919 Depth+1);
Nick Lewyckyc1a2a612008-03-06 06:48:30 +0000920
921 uint32_t Leaders = KnownZero2.countLeadingOnes();
922 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
923 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
924 }
925 break;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000926 }
927}
928
Reid Spencere7816b52007-03-08 01:52:58 +0000929/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
930/// this predicate to simplify operations downstream. Mask is known to be zero
931/// for bits that V cannot have.
932static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000933 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000934 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
935 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
936 return (KnownZero & Mask) == Mask;
937}
938
Chris Lattner255d8912006-02-11 09:31:47 +0000939/// ShrinkDemandedConstant - Check to see if the specified operand of the
940/// specified instruction is a constant integer. If so, check to see if there
941/// are any bits set in the constant that are not demanded. If so, shrink the
942/// constant and return true.
943static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000944 APInt Demanded) {
945 assert(I && "No instruction?");
946 assert(OpNo < I->getNumOperands() && "Operand index too large");
947
948 // If the operand is not a constant integer, nothing to do.
949 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
950 if (!OpC) return false;
951
952 // If there are no bits set that aren't demanded, nothing to do.
953 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
954 if ((~Demanded & OpC->getValue()) == 0)
955 return false;
956
957 // This instruction is producing bits that are not demanded. Shrink the RHS.
958 Demanded &= OpC->getValue();
959 I->setOperand(OpNo, ConstantInt::get(Demanded));
960 return true;
961}
962
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000963// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
964// set of known zero and one bits, compute the maximum and minimum values that
965// could have the specified known zero and known one bits, returning them in
966// min/max.
967static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000968 const APInt& KnownZero,
969 const APInt& KnownOne,
970 APInt& Min, APInt& Max) {
971 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
972 assert(KnownZero.getBitWidth() == BitWidth &&
973 KnownOne.getBitWidth() == BitWidth &&
974 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
975 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000976 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000977
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000978 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
979 // bit if it is unknown.
980 Min = KnownOne;
981 Max = KnownOne|UnknownBits;
982
Zhou Sheng4acf1552007-03-28 05:15:57 +0000983 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000984 Min.set(BitWidth-1);
985 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000986 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000987}
988
989// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
990// a set of known zero and one bits, compute the maximum and minimum values that
991// could have the specified known zero and known one bits, returning them in
992// min/max.
993static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000994 const APInt &KnownZero,
995 const APInt &KnownOne,
996 APInt &Min, APInt &Max) {
997 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000998 assert(KnownZero.getBitWidth() == BitWidth &&
999 KnownOne.getBitWidth() == BitWidth &&
1000 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1001 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +00001002 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00001003
1004 // The minimum value is when the unknown bits are all zeros.
1005 Min = KnownOne;
1006 // The maximum value is when the unknown bits are all ones.
1007 Max = KnownOne|UnknownBits;
1008}
Chris Lattner255d8912006-02-11 09:31:47 +00001009
Reid Spencer8cb68342007-03-12 17:25:59 +00001010/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1011/// value based on the demanded bits. When this function is called, it is known
1012/// that only the bits set in DemandedMask of the result of V are ever used
1013/// downstream. Consequently, depending on the mask and V, it may be possible
1014/// to replace V with a constant or one of its operands. In such cases, this
1015/// function does the replacement and returns true. In all other cases, it
1016/// returns false after analyzing the expression and setting KnownOne and known
1017/// to be one in the expression. KnownZero contains all the bits that are known
1018/// to be zero in the expression. These are provided to potentially allow the
1019/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1020/// the expression. KnownOne and KnownZero always follow the invariant that
1021/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1022/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1023/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1024/// and KnownOne must all be the same.
1025bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1026 APInt& KnownZero, APInt& KnownOne,
1027 unsigned Depth) {
1028 assert(V != 0 && "Null pointer of Value???");
1029 assert(Depth <= 6 && "Limit Search Depth");
1030 uint32_t BitWidth = DemandedMask.getBitWidth();
1031 const IntegerType *VTy = cast<IntegerType>(V->getType());
1032 assert(VTy->getBitWidth() == BitWidth &&
1033 KnownZero.getBitWidth() == BitWidth &&
1034 KnownOne.getBitWidth() == BitWidth &&
1035 "Value *V, DemandedMask, KnownZero and KnownOne \
1036 must have same BitWidth");
1037 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1038 // We know all of the bits for a constant!
1039 KnownOne = CI->getValue() & DemandedMask;
1040 KnownZero = ~KnownOne & DemandedMask;
1041 return false;
1042 }
1043
Zhou Sheng96704452007-03-14 03:21:24 +00001044 KnownZero.clear();
1045 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +00001046 if (!V->hasOneUse()) { // Other users may use these bits.
1047 if (Depth != 0) { // Not at the root.
1048 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1049 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1050 return false;
1051 }
1052 // If this is the root being simplified, allow it to have multiple uses,
1053 // just set the DemandedMask to all bits.
1054 DemandedMask = APInt::getAllOnesValue(BitWidth);
1055 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1056 if (V != UndefValue::get(VTy))
1057 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1058 return false;
1059 } else if (Depth == 6) { // Limit search depth.
1060 return false;
1061 }
1062
1063 Instruction *I = dyn_cast<Instruction>(V);
1064 if (!I) return false; // Only analyze instructions.
1065
Reid Spencer8cb68342007-03-12 17:25:59 +00001066 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1067 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1068 switch (I->getOpcode()) {
1069 default: break;
1070 case Instruction::And:
1071 // If either the LHS or the RHS are Zero, the result is zero.
1072 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1073 RHSKnownZero, RHSKnownOne, Depth+1))
1074 return true;
1075 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1076 "Bits known to be one AND zero?");
1077
1078 // If something is known zero on the RHS, the bits aren't demanded on the
1079 // LHS.
1080 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1081 LHSKnownZero, LHSKnownOne, Depth+1))
1082 return true;
1083 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1084 "Bits known to be one AND zero?");
1085
1086 // If all of the demanded bits are known 1 on one side, return the other.
1087 // These bits cannot contribute to the result of the 'and'.
1088 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1089 (DemandedMask & ~LHSKnownZero))
1090 return UpdateValueUsesWith(I, I->getOperand(0));
1091 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1092 (DemandedMask & ~RHSKnownZero))
1093 return UpdateValueUsesWith(I, I->getOperand(1));
1094
1095 // If all of the demanded bits in the inputs are known zeros, return zero.
1096 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1097 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1098
1099 // If the RHS is a constant, see if we can simplify it.
1100 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1101 return UpdateValueUsesWith(I, I);
1102
1103 // Output known-1 bits are only known if set in both the LHS & RHS.
1104 RHSKnownOne &= LHSKnownOne;
1105 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1106 RHSKnownZero |= LHSKnownZero;
1107 break;
1108 case Instruction::Or:
1109 // If either the LHS or the RHS are One, the result is One.
1110 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1111 RHSKnownZero, RHSKnownOne, Depth+1))
1112 return true;
1113 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1114 "Bits known to be one AND zero?");
1115 // If something is known one on the RHS, the bits aren't demanded on the
1116 // LHS.
1117 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1118 LHSKnownZero, LHSKnownOne, Depth+1))
1119 return true;
1120 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1121 "Bits known to be one AND zero?");
1122
1123 // If all of the demanded bits are known zero on one side, return the other.
1124 // These bits cannot contribute to the result of the 'or'.
1125 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1126 (DemandedMask & ~LHSKnownOne))
1127 return UpdateValueUsesWith(I, I->getOperand(0));
1128 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1129 (DemandedMask & ~RHSKnownOne))
1130 return UpdateValueUsesWith(I, I->getOperand(1));
1131
1132 // If all of the potentially set bits on one side are known to be set on
1133 // the other side, just use the 'other' side.
1134 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1135 (DemandedMask & (~RHSKnownZero)))
1136 return UpdateValueUsesWith(I, I->getOperand(0));
1137 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1138 (DemandedMask & (~LHSKnownZero)))
1139 return UpdateValueUsesWith(I, I->getOperand(1));
1140
1141 // If the RHS is a constant, see if we can simplify it.
1142 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1143 return UpdateValueUsesWith(I, I);
1144
1145 // Output known-0 bits are only known if clear in both the LHS & RHS.
1146 RHSKnownZero &= LHSKnownZero;
1147 // Output known-1 are known to be set if set in either the LHS | RHS.
1148 RHSKnownOne |= LHSKnownOne;
1149 break;
1150 case Instruction::Xor: {
1151 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1152 RHSKnownZero, RHSKnownOne, Depth+1))
1153 return true;
1154 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1155 "Bits known to be one AND zero?");
1156 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1157 LHSKnownZero, LHSKnownOne, Depth+1))
1158 return true;
1159 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1160 "Bits known to be one AND zero?");
1161
1162 // If all of the demanded bits are known zero on one side, return the other.
1163 // These bits cannot contribute to the result of the 'xor'.
1164 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1165 return UpdateValueUsesWith(I, I->getOperand(0));
1166 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1167 return UpdateValueUsesWith(I, I->getOperand(1));
1168
1169 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1170 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1171 (RHSKnownOne & LHSKnownOne);
1172 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1173 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1174 (RHSKnownOne & LHSKnownZero);
1175
1176 // If all of the demanded bits are known to be zero on one side or the
1177 // other, turn this into an *inclusive* or.
1178 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1179 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1180 Instruction *Or =
1181 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1182 I->getName());
1183 InsertNewInstBefore(Or, *I);
1184 return UpdateValueUsesWith(I, Or);
1185 }
1186
1187 // If all of the demanded bits on one side are known, and all of the set
1188 // bits on that side are also known to be set on the other side, turn this
1189 // into an AND, as we know the bits will be cleared.
1190 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1191 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1192 // all known
1193 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1194 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1195 Instruction *And =
1196 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1197 InsertNewInstBefore(And, *I);
1198 return UpdateValueUsesWith(I, And);
1199 }
1200 }
1201
1202 // If the RHS is a constant, see if we can simplify it.
1203 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1204 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1205 return UpdateValueUsesWith(I, I);
1206
1207 RHSKnownZero = KnownZeroOut;
1208 RHSKnownOne = KnownOneOut;
1209 break;
1210 }
1211 case Instruction::Select:
1212 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1213 RHSKnownZero, RHSKnownOne, Depth+1))
1214 return true;
1215 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1216 LHSKnownZero, LHSKnownOne, Depth+1))
1217 return true;
1218 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1219 "Bits known to be one AND zero?");
1220 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1221 "Bits known to be one AND zero?");
1222
1223 // If the operands are constants, see if we can simplify them.
1224 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1225 return UpdateValueUsesWith(I, I);
1226 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1227 return UpdateValueUsesWith(I, I);
1228
1229 // Only known if known in both the LHS and RHS.
1230 RHSKnownOne &= LHSKnownOne;
1231 RHSKnownZero &= LHSKnownZero;
1232 break;
1233 case Instruction::Trunc: {
1234 uint32_t truncBf =
1235 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001236 DemandedMask.zext(truncBf);
1237 RHSKnownZero.zext(truncBf);
1238 RHSKnownOne.zext(truncBf);
1239 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1240 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 return true;
1242 DemandedMask.trunc(BitWidth);
1243 RHSKnownZero.trunc(BitWidth);
1244 RHSKnownOne.trunc(BitWidth);
1245 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1246 "Bits known to be one AND zero?");
1247 break;
1248 }
1249 case Instruction::BitCast:
1250 if (!I->getOperand(0)->getType()->isInteger())
1251 return false;
1252
1253 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1254 RHSKnownZero, RHSKnownOne, Depth+1))
1255 return true;
1256 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1257 "Bits known to be one AND zero?");
1258 break;
1259 case Instruction::ZExt: {
1260 // Compute the bits in the result that are not present in the input.
1261 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001262 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001263
Zhou Shengd48653a2007-03-29 04:45:55 +00001264 DemandedMask.trunc(SrcBitWidth);
1265 RHSKnownZero.trunc(SrcBitWidth);
1266 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001267 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1268 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 return true;
1270 DemandedMask.zext(BitWidth);
1271 RHSKnownZero.zext(BitWidth);
1272 RHSKnownOne.zext(BitWidth);
1273 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1274 "Bits known to be one AND zero?");
1275 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001276 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001277 break;
1278 }
1279 case Instruction::SExt: {
1280 // Compute the bits in the result that are not present in the input.
1281 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001282 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001283
Reid Spencer8cb68342007-03-12 17:25:59 +00001284 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001285 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001286
Zhou Sheng01542f32007-03-29 02:26:30 +00001287 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 // If any of the sign extended bits are demanded, we know that the sign
1289 // bit is demanded.
1290 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001291 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001292
Zhou Shengd48653a2007-03-29 04:45:55 +00001293 InputDemandedBits.trunc(SrcBitWidth);
1294 RHSKnownZero.trunc(SrcBitWidth);
1295 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001296 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1297 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 return true;
1299 InputDemandedBits.zext(BitWidth);
1300 RHSKnownZero.zext(BitWidth);
1301 RHSKnownOne.zext(BitWidth);
1302 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1303 "Bits known to be one AND zero?");
1304
1305 // If the sign bit of the input is known set or clear, then we know the
1306 // top bits of the result.
1307
1308 // If the input sign bit is known zero, or if the NewBits are not demanded
1309 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001310 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 {
1312 // Convert to ZExt cast
1313 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1314 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001315 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001316 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 }
1318 break;
1319 }
1320 case Instruction::Add: {
1321 // Figure out what the input bits are. If the top bits of the and result
1322 // are not demanded, then the add doesn't demand them from its input
1323 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001324 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001325
1326 // If there is a constant on the RHS, there are a variety of xformations
1327 // we can do.
1328 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1329 // If null, this should be simplified elsewhere. Some of the xforms here
1330 // won't work if the RHS is zero.
1331 if (RHS->isZero())
1332 break;
1333
1334 // If the top bit of the output is demanded, demand everything from the
1335 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001336 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001337
1338 // Find information about known zero/one bits in the input.
1339 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1340 LHSKnownZero, LHSKnownOne, Depth+1))
1341 return true;
1342
1343 // If the RHS of the add has bits set that can't affect the input, reduce
1344 // the constant.
1345 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1346 return UpdateValueUsesWith(I, I);
1347
1348 // Avoid excess work.
1349 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1350 break;
1351
1352 // Turn it into OR if input bits are zero.
1353 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1354 Instruction *Or =
1355 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1356 I->getName());
1357 InsertNewInstBefore(Or, *I);
1358 return UpdateValueUsesWith(I, Or);
1359 }
1360
1361 // We can say something about the output known-zero and known-one bits,
1362 // depending on potential carries from the input constant and the
1363 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1364 // bits set and the RHS constant is 0x01001, then we know we have a known
1365 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1366
1367 // To compute this, we first compute the potential carry bits. These are
1368 // the bits which may be modified. I'm not aware of a better way to do
1369 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001370 const APInt& RHSVal = RHS->getValue();
1371 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001372
1373 // Now that we know which bits have carries, compute the known-1/0 sets.
1374
1375 // Bits are known one if they are known zero in one operand and one in the
1376 // other, and there is no input carry.
1377 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1378 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1379
1380 // Bits are known zero if they are known zero in both operands and there
1381 // is no input carry.
1382 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1383 } else {
1384 // If the high-bits of this ADD are not demanded, then it does not demand
1385 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001386 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001387 // Right fill the mask of bits for this ADD to demand the most
1388 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001389 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001390 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1391 LHSKnownZero, LHSKnownOne, Depth+1))
1392 return true;
1393 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1394 LHSKnownZero, LHSKnownOne, Depth+1))
1395 return true;
1396 }
1397 }
1398 break;
1399 }
1400 case Instruction::Sub:
1401 // If the high-bits of this SUB are not demanded, then it does not demand
1402 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001403 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001404 // Right fill the mask of bits for this SUB to demand the most
1405 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001406 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001407 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001408 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1409 LHSKnownZero, LHSKnownOne, Depth+1))
1410 return true;
1411 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1412 LHSKnownZero, LHSKnownOne, Depth+1))
1413 return true;
1414 }
1415 break;
1416 case Instruction::Shl:
1417 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001418 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001419 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1420 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001421 RHSKnownZero, RHSKnownOne, Depth+1))
1422 return true;
1423 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1424 "Bits known to be one AND zero?");
1425 RHSKnownZero <<= ShiftAmt;
1426 RHSKnownOne <<= ShiftAmt;
1427 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001428 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001429 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001430 }
1431 break;
1432 case Instruction::LShr:
1433 // For a logical shift right
1434 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001435 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001436
Reid Spencer8cb68342007-03-12 17:25:59 +00001437 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001438 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1439 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001440 RHSKnownZero, RHSKnownOne, Depth+1))
1441 return true;
1442 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1443 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001444 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1445 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001446 if (ShiftAmt) {
1447 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001448 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001449 RHSKnownZero |= HighBits; // high bits known zero.
1450 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001451 }
1452 break;
1453 case Instruction::AShr:
1454 // If this is an arithmetic shift right and only the low-bit is set, we can
1455 // always convert this into a logical shr, even if the shift amount is
1456 // variable. The low bit of the shift cannot be an input sign bit unless
1457 // the shift amount is >= the size of the datatype, which is undefined.
1458 if (DemandedMask == 1) {
1459 // Perform the logical shift right.
1460 Value *NewVal = BinaryOperator::createLShr(
1461 I->getOperand(0), I->getOperand(1), I->getName());
1462 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1463 return UpdateValueUsesWith(I, NewVal);
1464 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001465
1466 // If the sign bit is the only bit demanded by this ashr, then there is no
1467 // need to do it, the shift doesn't change the high bit.
1468 if (DemandedMask.isSignBit())
1469 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001470
1471 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001472 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001473
Reid Spencer8cb68342007-03-12 17:25:59 +00001474 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001475 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001476 // If any of the "high bits" are demanded, we should set the sign bit as
1477 // demanded.
1478 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1479 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001480 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001481 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001482 RHSKnownZero, RHSKnownOne, Depth+1))
1483 return true;
1484 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1485 "Bits known to be one AND zero?");
1486 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001487 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001488 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1489 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1490
1491 // Handle the sign bits.
1492 APInt SignBit(APInt::getSignBit(BitWidth));
1493 // Adjust to where it is now in the mask.
1494 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1495
1496 // If the input sign bit is known to be zero, or if none of the top bits
1497 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001498 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001499 (HighBits & ~DemandedMask) == HighBits) {
1500 // Perform the logical shift right.
1501 Value *NewVal = BinaryOperator::createLShr(
1502 I->getOperand(0), SA, I->getName());
1503 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1504 return UpdateValueUsesWith(I, NewVal);
1505 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1506 RHSKnownOne |= HighBits;
1507 }
1508 }
1509 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001510 case Instruction::SRem:
1511 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1512 APInt RA = Rem->getValue();
1513 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1514 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1515 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1516 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1517 LHSKnownZero, LHSKnownOne, Depth+1))
1518 return true;
1519
1520 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1521 LHSKnownZero |= ~LowBits;
1522 else if (LHSKnownOne[BitWidth-1])
1523 LHSKnownOne |= ~LowBits;
1524
1525 KnownZero |= LHSKnownZero & DemandedMask;
1526 KnownOne |= LHSKnownOne & DemandedMask;
1527
1528 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1529 }
1530 }
1531 break;
1532 case Instruction::URem:
1533 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1534 APInt RA = Rem->getValue();
1535 if (RA.isPowerOf2()) {
1536 APInt LowBits = (RA - 1) | RA;
1537 APInt Mask2 = LowBits & DemandedMask;
1538 KnownZero |= ~LowBits & DemandedMask;
1539 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1540 KnownZero, KnownOne, Depth+1))
1541 return true;
1542
1543 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1544 }
1545 } else {
1546 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1547 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1548 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1549 KnownZero2, KnownOne2, Depth+1))
1550 return true;
1551
1552 uint32_t Leaders = KnownZero2.countLeadingOnes();
1553 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1554 }
1555 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001556 }
1557
1558 // If the client is only demanding bits that we know, return the known
1559 // constant.
1560 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1561 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1562 return false;
1563}
1564
Chris Lattner867b99f2006-10-05 06:55:50 +00001565
1566/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1567/// 64 or fewer elements. DemandedElts contains the set of elements that are
1568/// actually used by the caller. This method analyzes which elements of the
1569/// operand are undef and returns that information in UndefElts.
1570///
1571/// If the information about demanded elements can be used to simplify the
1572/// operation, the operation is simplified, then the resultant value is
1573/// returned. This returns null if no change was made.
1574Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1575 uint64_t &UndefElts,
1576 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001577 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001578 assert(VWidth <= 64 && "Vector too wide to analyze!");
1579 uint64_t EltMask = ~0ULL >> (64-VWidth);
1580 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1581 "Invalid DemandedElts!");
1582
1583 if (isa<UndefValue>(V)) {
1584 // If the entire vector is undefined, just return this info.
1585 UndefElts = EltMask;
1586 return 0;
1587 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1588 UndefElts = EltMask;
1589 return UndefValue::get(V->getType());
1590 }
1591
1592 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001593 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1594 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001595 Constant *Undef = UndefValue::get(EltTy);
1596
1597 std::vector<Constant*> Elts;
1598 for (unsigned i = 0; i != VWidth; ++i)
1599 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1600 Elts.push_back(Undef);
1601 UndefElts |= (1ULL << i);
1602 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1603 Elts.push_back(Undef);
1604 UndefElts |= (1ULL << i);
1605 } else { // Otherwise, defined.
1606 Elts.push_back(CP->getOperand(i));
1607 }
1608
1609 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001610 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001611 return NewCP != CP ? NewCP : 0;
1612 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001613 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001614 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001615 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001616 Constant *Zero = Constant::getNullValue(EltTy);
1617 Constant *Undef = UndefValue::get(EltTy);
1618 std::vector<Constant*> Elts;
1619 for (unsigned i = 0; i != VWidth; ++i)
1620 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1621 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001622 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001623 }
1624
1625 if (!V->hasOneUse()) { // Other users may use these bits.
1626 if (Depth != 0) { // Not at the root.
1627 // TODO: Just compute the UndefElts information recursively.
1628 return false;
1629 }
1630 return false;
1631 } else if (Depth == 10) { // Limit search depth.
1632 return false;
1633 }
1634
1635 Instruction *I = dyn_cast<Instruction>(V);
1636 if (!I) return false; // Only analyze instructions.
1637
1638 bool MadeChange = false;
1639 uint64_t UndefElts2;
1640 Value *TmpV;
1641 switch (I->getOpcode()) {
1642 default: break;
1643
1644 case Instruction::InsertElement: {
1645 // If this is a variable index, we don't know which element it overwrites.
1646 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001647 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001648 if (Idx == 0) {
1649 // Note that we can't propagate undef elt info, because we don't know
1650 // which elt is getting updated.
1651 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1652 UndefElts2, Depth+1);
1653 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1654 break;
1655 }
1656
1657 // If this is inserting an element that isn't demanded, remove this
1658 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001659 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001660 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1661 return AddSoonDeadInstToWorklist(*I, 0);
1662
1663 // Otherwise, the element inserted overwrites whatever was there, so the
1664 // input demanded set is simpler than the output set.
1665 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1666 DemandedElts & ~(1ULL << IdxNo),
1667 UndefElts, Depth+1);
1668 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1669
1670 // The inserted element is defined.
1671 UndefElts |= 1ULL << IdxNo;
1672 break;
1673 }
Chris Lattner69878332007-04-14 22:29:23 +00001674 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001675 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001676 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1677 if (!VTy) break;
1678 unsigned InVWidth = VTy->getNumElements();
1679 uint64_t InputDemandedElts = 0;
1680 unsigned Ratio;
1681
1682 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001683 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001684 // elements as are demanded of us.
1685 Ratio = 1;
1686 InputDemandedElts = DemandedElts;
1687 } else if (VWidth > InVWidth) {
1688 // Untested so far.
1689 break;
1690
1691 // If there are more elements in the result than there are in the source,
1692 // then an input element is live if any of the corresponding output
1693 // elements are live.
1694 Ratio = VWidth/InVWidth;
1695 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1696 if (DemandedElts & (1ULL << OutIdx))
1697 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1698 }
1699 } else {
1700 // Untested so far.
1701 break;
1702
1703 // If there are more elements in the source than there are in the result,
1704 // then an input element is live if the corresponding output element is
1705 // live.
1706 Ratio = InVWidth/VWidth;
1707 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1708 if (DemandedElts & (1ULL << InIdx/Ratio))
1709 InputDemandedElts |= 1ULL << InIdx;
1710 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001711
Chris Lattner69878332007-04-14 22:29:23 +00001712 // div/rem demand all inputs, because they don't want divide by zero.
1713 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1714 UndefElts2, Depth+1);
1715 if (TmpV) {
1716 I->setOperand(0, TmpV);
1717 MadeChange = true;
1718 }
1719
1720 UndefElts = UndefElts2;
1721 if (VWidth > InVWidth) {
1722 assert(0 && "Unimp");
1723 // If there are more elements in the result than there are in the source,
1724 // then an output element is undef if the corresponding input element is
1725 // undef.
1726 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1727 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1728 UndefElts |= 1ULL << OutIdx;
1729 } else if (VWidth < InVWidth) {
1730 assert(0 && "Unimp");
1731 // If there are more elements in the source than there are in the result,
1732 // then a result element is undef if all of the corresponding input
1733 // elements are undef.
1734 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1735 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1736 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1737 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1738 }
1739 break;
1740 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001741 case Instruction::And:
1742 case Instruction::Or:
1743 case Instruction::Xor:
1744 case Instruction::Add:
1745 case Instruction::Sub:
1746 case Instruction::Mul:
1747 // div/rem demand all inputs, because they don't want divide by zero.
1748 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1749 UndefElts, Depth+1);
1750 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1751 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1752 UndefElts2, Depth+1);
1753 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1754
1755 // Output elements are undefined if both are undefined. Consider things
1756 // like undef&0. The result is known zero, not undef.
1757 UndefElts &= UndefElts2;
1758 break;
1759
1760 case Instruction::Call: {
1761 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1762 if (!II) break;
1763 switch (II->getIntrinsicID()) {
1764 default: break;
1765
1766 // Binary vector operations that work column-wise. A dest element is a
1767 // function of the corresponding input elements from the two inputs.
1768 case Intrinsic::x86_sse_sub_ss:
1769 case Intrinsic::x86_sse_mul_ss:
1770 case Intrinsic::x86_sse_min_ss:
1771 case Intrinsic::x86_sse_max_ss:
1772 case Intrinsic::x86_sse2_sub_sd:
1773 case Intrinsic::x86_sse2_mul_sd:
1774 case Intrinsic::x86_sse2_min_sd:
1775 case Intrinsic::x86_sse2_max_sd:
1776 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1777 UndefElts, Depth+1);
1778 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1779 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1780 UndefElts2, Depth+1);
1781 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1782
1783 // If only the low elt is demanded and this is a scalarizable intrinsic,
1784 // scalarize it now.
1785 if (DemandedElts == 1) {
1786 switch (II->getIntrinsicID()) {
1787 default: break;
1788 case Intrinsic::x86_sse_sub_ss:
1789 case Intrinsic::x86_sse_mul_ss:
1790 case Intrinsic::x86_sse2_sub_sd:
1791 case Intrinsic::x86_sse2_mul_sd:
1792 // TODO: Lower MIN/MAX/ABS/etc
1793 Value *LHS = II->getOperand(1);
1794 Value *RHS = II->getOperand(2);
1795 // Extract the element as scalars.
1796 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1797 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1798
1799 switch (II->getIntrinsicID()) {
1800 default: assert(0 && "Case stmts out of sync!");
1801 case Intrinsic::x86_sse_sub_ss:
1802 case Intrinsic::x86_sse2_sub_sd:
1803 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1804 II->getName()), *II);
1805 break;
1806 case Intrinsic::x86_sse_mul_ss:
1807 case Intrinsic::x86_sse2_mul_sd:
1808 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1809 II->getName()), *II);
1810 break;
1811 }
1812
1813 Instruction *New =
1814 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1815 II->getName());
1816 InsertNewInstBefore(New, *II);
1817 AddSoonDeadInstToWorklist(*II, 0);
1818 return New;
1819 }
1820 }
1821
1822 // Output elements are undefined if both are undefined. Consider things
1823 // like undef&0. The result is known zero, not undef.
1824 UndefElts &= UndefElts2;
1825 break;
1826 }
1827 break;
1828 }
1829 }
1830 return MadeChange ? I : 0;
1831}
1832
Nick Lewycky455e1762007-09-06 02:40:25 +00001833/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001834/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001835/// @brief Determine if the icmp Predicate is true when both operands are equal
1836static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001837 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1838 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1839 pred == ICmpInst::ICMP_SLE;
1840}
1841
Nick Lewycky455e1762007-09-06 02:40:25 +00001842/// @returns true if the specified compare instruction is
1843/// true when both operands are equal...
1844/// @brief Determine if the ICmpInst returns true when both operands are equal
1845static bool isTrueWhenEqual(ICmpInst &ICI) {
1846 return isTrueWhenEqual(ICI.getPredicate());
1847}
1848
Chris Lattner564a7272003-08-13 19:01:45 +00001849/// AssociativeOpt - Perform an optimization on an associative operator. This
1850/// function is designed to check a chain of associative operators for a
1851/// potential to apply a certain optimization. Since the optimization may be
1852/// applicable if the expression was reassociated, this checks the chain, then
1853/// reassociates the expression as necessary to expose the optimization
1854/// opportunity. This makes use of a special Functor, which must define
1855/// 'shouldApply' and 'apply' methods.
1856///
1857template<typename Functor>
1858Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1859 unsigned Opcode = Root.getOpcode();
1860 Value *LHS = Root.getOperand(0);
1861
1862 // Quick check, see if the immediate LHS matches...
1863 if (F.shouldApply(LHS))
1864 return F.apply(Root);
1865
1866 // Otherwise, if the LHS is not of the same opcode as the root, return.
1867 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001868 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001869 // Should we apply this transform to the RHS?
1870 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1871
1872 // If not to the RHS, check to see if we should apply to the LHS...
1873 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1874 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1875 ShouldApply = true;
1876 }
1877
1878 // If the functor wants to apply the optimization to the RHS of LHSI,
1879 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1880 if (ShouldApply) {
1881 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001882
Chris Lattner564a7272003-08-13 19:01:45 +00001883 // Now all of the instructions are in the current basic block, go ahead
1884 // and perform the reassociation.
1885 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1886
1887 // First move the selected RHS to the LHS of the root...
1888 Root.setOperand(0, LHSI->getOperand(1));
1889
1890 // Make what used to be the LHS of the root be the user of the root...
1891 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001892 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001893 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1894 return 0;
1895 }
Chris Lattner65725312004-04-16 18:08:07 +00001896 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001897 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001898 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1899 BasicBlock::iterator ARI = &Root; ++ARI;
1900 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1901 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001902
1903 // Now propagate the ExtraOperand down the chain of instructions until we
1904 // get to LHSI.
1905 while (TmpLHSI != LHSI) {
1906 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001907 // Move the instruction to immediately before the chain we are
1908 // constructing to avoid breaking dominance properties.
1909 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1910 BB->getInstList().insert(ARI, NextLHSI);
1911 ARI = NextLHSI;
1912
Chris Lattner564a7272003-08-13 19:01:45 +00001913 Value *NextOp = NextLHSI->getOperand(1);
1914 NextLHSI->setOperand(1, ExtraOperand);
1915 TmpLHSI = NextLHSI;
1916 ExtraOperand = NextOp;
1917 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001918
Chris Lattner564a7272003-08-13 19:01:45 +00001919 // Now that the instructions are reassociated, have the functor perform
1920 // the transformation...
1921 return F.apply(Root);
1922 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001923
Chris Lattner564a7272003-08-13 19:01:45 +00001924 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1925 }
1926 return 0;
1927}
1928
1929
1930// AddRHS - Implements: X + X --> X << 1
1931struct AddRHS {
1932 Value *RHS;
1933 AddRHS(Value *rhs) : RHS(rhs) {}
1934 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1935 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001936 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001937 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001938 }
1939};
1940
1941// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1942// iff C1&C2 == 0
1943struct AddMaskingAnd {
1944 Constant *C2;
1945 AddMaskingAnd(Constant *c) : C2(c) {}
1946 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001947 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001948 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001949 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001950 }
1951 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001952 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001953 }
1954};
1955
Chris Lattner6e7ba452005-01-01 16:22:27 +00001956static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001957 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001958 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001959 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001960 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001961
Reid Spencer3da59db2006-11-27 01:05:10 +00001962 return IC->InsertNewInstBefore(CastInst::create(
1963 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001964 }
1965
Chris Lattner2eefe512004-04-09 19:05:30 +00001966 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001967 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1968 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001969
Chris Lattner2eefe512004-04-09 19:05:30 +00001970 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1971 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001972 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1973 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001974 }
1975
1976 Value *Op0 = SO, *Op1 = ConstOperand;
1977 if (!ConstIsRHS)
1978 std::swap(Op0, Op1);
1979 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1981 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001982 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1983 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1984 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001985 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001986 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001987 abort();
1988 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001989 return IC->InsertNewInstBefore(New, I);
1990}
1991
1992// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1993// constant as the other operand, try to fold the binary operator into the
1994// select arguments. This also works for Cast instructions, which obviously do
1995// not have a second operand.
1996static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1997 InstCombiner *IC) {
1998 // Don't modify shared select instructions
1999 if (!SI->hasOneUse()) return 0;
2000 Value *TV = SI->getOperand(1);
2001 Value *FV = SI->getOperand(2);
2002
2003 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002004 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00002005 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002006
Chris Lattner6e7ba452005-01-01 16:22:27 +00002007 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2008 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2009
2010 return new SelectInst(SI->getCondition(), SelectTrueVal,
2011 SelectFalseVal);
2012 }
2013 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002014}
2015
Chris Lattner4e998b22004-09-29 05:07:12 +00002016
2017/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2018/// node as operand #0, see if we can fold the instruction into the PHI (which
2019/// is only possible if all operands to the PHI are constants).
2020Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2021 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002022 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002023 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00002024
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002025 // Check to see if all of the operands of the PHI are constants. If there is
2026 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00002027 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 BasicBlock *NonConstBB = 0;
2029 for (unsigned i = 0; i != NumPHIValues; ++i)
2030 if (!isa<Constant>(PN->getIncomingValue(i))) {
2031 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002032 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002033 NonConstBB = PN->getIncomingBlock(i);
2034
2035 // If the incoming non-constant value is in I's block, we have an infinite
2036 // loop.
2037 if (NonConstBB == I.getParent())
2038 return 0;
2039 }
2040
2041 // If there is exactly one non-constant value, we can insert a copy of the
2042 // operation in that block. However, if this is a critical edge, we would be
2043 // inserting the computation one some other paths (e.g. inside a loop). Only
2044 // do this if the pred block is unconditionally branching into the phi block.
2045 if (NonConstBB) {
2046 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2047 if (!BI || !BI->isUnconditional()) return 0;
2048 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002049
2050 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00002051 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002052 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00002053 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00002054 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002055
2056 // Next, add all of the operands to the PHI.
2057 if (I.getNumOperands() == 2) {
2058 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002059 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002060 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002061 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002062 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2063 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2064 else
2065 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002066 } else {
2067 assert(PN->getIncomingBlock(i) == NonConstBB);
2068 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2069 InV = BinaryOperator::create(BO->getOpcode(),
2070 PN->getIncomingValue(i), C, "phitmp",
2071 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002072 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2073 InV = CmpInst::create(CI->getOpcode(),
2074 CI->getPredicate(),
2075 PN->getIncomingValue(i), C, "phitmp",
2076 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002077 else
2078 assert(0 && "Unknown binop!");
2079
Chris Lattnerdbab3862007-03-02 21:28:56 +00002080 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002081 }
2082 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002083 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002084 } else {
2085 CastInst *CI = cast<CastInst>(&I);
2086 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002087 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002088 Value *InV;
2089 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00002090 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002091 } else {
2092 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00002093 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2094 I.getType(), "phitmp",
2095 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00002096 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002097 }
2098 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002099 }
2100 }
2101 return ReplaceInstUsesWith(I, NewPN);
2102}
2103
Chris Lattner2454a2e2008-01-29 06:52:45 +00002104
2105/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2106/// value is never equal to -0.0.
2107///
2108/// Note that this function will need to be revisited when we support nondefault
2109/// rounding modes!
2110///
2111static bool CannotBeNegativeZero(const Value *V) {
2112 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2113 return !CFP->getValueAPF().isNegZero();
2114
2115 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2116 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2117 if (I->getOpcode() == Instruction::Add &&
2118 isa<ConstantFP>(I->getOperand(1)) &&
2119 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2120 return true;
2121
2122 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2123 if (II->getIntrinsicID() == Intrinsic::sqrt)
2124 return CannotBeNegativeZero(II->getOperand(1));
2125
2126 if (const CallInst *CI = dyn_cast<CallInst>(I))
2127 if (const Function *F = CI->getCalledFunction()) {
2128 if (F->isDeclaration()) {
2129 switch (F->getNameLen()) {
2130 case 3: // abs(x) != -0.0
2131 if (!strcmp(F->getNameStart(), "abs")) return true;
2132 break;
2133 case 4: // abs[lf](x) != -0.0
2134 if (!strcmp(F->getNameStart(), "absf")) return true;
2135 if (!strcmp(F->getNameStart(), "absl")) return true;
2136 break;
2137 }
2138 }
2139 }
2140 }
2141
2142 return false;
2143}
2144
2145
Chris Lattner7e708292002-06-25 16:13:24 +00002146Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002147 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002148 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002149
Chris Lattner66331a42004-04-10 22:01:55 +00002150 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002151 // X + undef -> undef
2152 if (isa<UndefValue>(RHS))
2153 return ReplaceInstUsesWith(I, RHS);
2154
Chris Lattner66331a42004-04-10 22:01:55 +00002155 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002156 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002157 if (RHSC->isNullValue())
2158 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002159 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002160 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2161 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002162 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002163 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002164
Chris Lattner66331a42004-04-10 22:01:55 +00002165 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002166 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002167 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002168 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002169 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002170 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002171
2172 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2173 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002174 if (!isa<VectorType>(I.getType())) {
2175 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2176 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2177 KnownZero, KnownOne))
2178 return &I;
2179 }
Chris Lattner66331a42004-04-10 22:01:55 +00002180 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002181
2182 if (isa<PHINode>(LHS))
2183 if (Instruction *NV = FoldOpIntoPhi(I))
2184 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002185
Chris Lattner4f637d42006-01-06 17:59:59 +00002186 ConstantInt *XorRHS = 0;
2187 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002188 if (isa<ConstantInt>(RHSC) &&
2189 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002190 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002191 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002192
Zhou Sheng4351c642007-04-02 08:20:41 +00002193 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002194 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2195 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002196 do {
2197 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002198 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2199 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002200 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2201 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002202 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002203 if (!MaskedValueIsZero(XorLHS,
2204 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002205 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002206 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002207 }
2208 }
2209 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002210 C0080Val = APIntOps::lshr(C0080Val, Size);
2211 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2212 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002213
Reid Spencer35c38852007-03-28 01:36:16 +00002214 // FIXME: This shouldn't be necessary. When the backends can handle types
2215 // with funny bit widths then this whole cascade of if statements should
2216 // be removed. It is just here to get the size of the "middle" type back
2217 // up to something that the back ends can handle.
2218 const Type *MiddleType = 0;
2219 switch (Size) {
2220 default: break;
2221 case 32: MiddleType = Type::Int32Ty; break;
2222 case 16: MiddleType = Type::Int16Ty; break;
2223 case 8: MiddleType = Type::Int8Ty; break;
2224 }
2225 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002226 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002227 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002228 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002229 }
2230 }
Chris Lattner66331a42004-04-10 22:01:55 +00002231 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002232
Chris Lattner564a7272003-08-13 19:01:45 +00002233 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002234 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002235 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002236
2237 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2238 if (RHSI->getOpcode() == Instruction::Sub)
2239 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2240 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2241 }
2242 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2243 if (LHSI->getOpcode() == Instruction::Sub)
2244 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2245 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2246 }
Robert Bocchino71698282004-07-27 21:02:21 +00002247 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002248
Chris Lattner5c4afb92002-05-08 22:46:53 +00002249 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002250 // -A + -B --> -(A + B)
2251 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002252 if (LHS->getType()->isIntOrIntVector()) {
2253 if (Value *RHSV = dyn_castNegVal(RHS)) {
2254 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2255 InsertNewInstBefore(NewAdd, I);
2256 return BinaryOperator::createNeg(NewAdd);
2257 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002258 }
2259
2260 return BinaryOperator::createSub(RHS, LHSV);
2261 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002262
2263 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002264 if (!isa<Constant>(RHS))
2265 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002266 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002267
Misha Brukmanfd939082005-04-21 23:48:37 +00002268
Chris Lattner50af16a2004-11-13 19:50:12 +00002269 ConstantInt *C2;
2270 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2271 if (X == RHS) // X*C + X --> X * (C+1)
2272 return BinaryOperator::createMul(RHS, AddOne(C2));
2273
2274 // X*C1 + X*C2 --> X * (C1+C2)
2275 ConstantInt *C1;
2276 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002277 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002278 }
2279
2280 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002281 if (dyn_castFoldableMul(RHS, C2) == LHS)
2282 return BinaryOperator::createMul(LHS, AddOne(C2));
2283
Chris Lattnere617c9e2007-01-05 02:17:46 +00002284 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002285 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2286 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002287
Chris Lattnerad3448c2003-02-18 19:57:07 +00002288
Chris Lattner564a7272003-08-13 19:01:45 +00002289 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002290 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002291 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2292 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002293
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002294 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002295 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002296 Value *W, *X, *Y, *Z;
2297 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2298 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2299 if (W != Y) {
2300 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002301 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002302 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002303 std::swap(W, X);
2304 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002305 std::swap(Y, Z);
2306 std::swap(W, X);
2307 }
2308 }
2309
2310 if (W == Y) {
2311 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2312 LHS->getName()), I);
2313 return BinaryOperator::createMul(W, NewAdd);
2314 }
2315 }
2316 }
2317
Chris Lattner6b032052003-10-02 15:11:26 +00002318 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002319 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002320 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2321 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002322
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002323 // (X & FF00) + xx00 -> (X+xx00) & FF00
2324 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002325 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002326 if (Anded == CRHS) {
2327 // See if all bits from the first bit set in the Add RHS up are included
2328 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002329 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002330
2331 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002332 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002333
2334 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002335 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002336
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002337 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2338 // Okay, the xform is safe. Insert the new add pronto.
2339 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2340 LHS->getName()), I);
2341 return BinaryOperator::createAnd(NewAdd, C2);
2342 }
2343 }
2344 }
2345
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002346 // Try to fold constant add into select arguments.
2347 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002348 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002349 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002350 }
2351
Reid Spencer1628cec2006-10-26 06:15:43 +00002352 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002353 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002354 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002355 CastInst *CI = dyn_cast<CastInst>(LHS);
2356 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002357 if (!CI) {
2358 CI = dyn_cast<CastInst>(RHS);
2359 Other = LHS;
2360 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002361 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002362 (CI->getType()->getPrimitiveSizeInBits() ==
2363 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002364 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002365 unsigned AS =
2366 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002367 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2368 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002369 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002370 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002371 }
2372 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002373
Chris Lattner42790482007-12-20 01:56:58 +00002374 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002375 {
2376 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2377 Value *Other = RHS;
2378 if (!SI) {
2379 SI = dyn_cast<SelectInst>(RHS);
2380 Other = LHS;
2381 }
Chris Lattner42790482007-12-20 01:56:58 +00002382 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002383 Value *TV = SI->getTrueValue();
2384 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002385 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002386
2387 // Can we fold the add into the argument of the select?
2388 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002389 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2390 A == Other) // Fold the add into the true select value.
2391 return new SelectInst(SI->getCondition(), N, A);
2392 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2393 A == Other) // Fold the add into the false select value.
2394 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002395 }
2396 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002397
2398 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2399 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2400 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2401 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002402
Chris Lattner7e708292002-06-25 16:13:24 +00002403 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002404}
2405
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002406// isSignBit - Return true if the value represented by the constant only has the
2407// highest order bit set.
2408static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002409 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002410 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002411}
2412
Chris Lattner7e708292002-06-25 16:13:24 +00002413Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002414 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002415
Chris Lattner233f7dc2002-08-12 21:17:25 +00002416 if (Op0 == Op1) // sub X, X -> 0
2417 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002418
Chris Lattner233f7dc2002-08-12 21:17:25 +00002419 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002420 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002421 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002422
Chris Lattnere87597f2004-10-16 18:11:37 +00002423 if (isa<UndefValue>(Op0))
2424 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2425 if (isa<UndefValue>(Op1))
2426 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2427
Chris Lattnerd65460f2003-11-05 01:06:05 +00002428 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2429 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002430 if (C->isAllOnesValue())
2431 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002432
Chris Lattnerd65460f2003-11-05 01:06:05 +00002433 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002434 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002435 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002436 return BinaryOperator::createAdd(X, AddOne(C));
2437
Chris Lattner76b7a062007-01-15 07:02:54 +00002438 // -(X >>u 31) -> (X >>s 31)
2439 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002440 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002441 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002442 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002443 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002444 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002445 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002446 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002447 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002448 return BinaryOperator::create(Instruction::AShr,
2449 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002450 }
2451 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002452 }
2453 else if (SI->getOpcode() == Instruction::AShr) {
2454 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2455 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002456 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002457 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002458 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002459 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002460 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002461 }
2462 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002463 }
2464 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002465 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002466
2467 // Try to fold constant sub into select arguments.
2468 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002469 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002470 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002471
2472 if (isa<PHINode>(Op0))
2473 if (Instruction *NV = FoldOpIntoPhi(I))
2474 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002475 }
2476
Chris Lattner43d84d62005-04-07 16:15:25 +00002477 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2478 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002479 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002480 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002481 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002482 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002483 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002484 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002487 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002488 Op1I->getOperand(0));
2489 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002490 }
2491
Chris Lattnerfd059242003-10-15 16:48:29 +00002492 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002493 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494 // is not used by anyone else...
2495 //
Chris Lattner0517e722004-02-02 20:09:56 +00002496 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002497 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002498 // Swap the two operands of the subexpr...
2499 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2500 Op1I->setOperand(0, IIOp1);
2501 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002502
Chris Lattnera2881962003-02-18 19:28:33 +00002503 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002504 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002505 }
2506
2507 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2508 //
2509 if (Op1I->getOpcode() == Instruction::And &&
2510 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2511 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2512
Chris Lattnerf523d062004-06-09 05:08:07 +00002513 Value *NewNot =
2514 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002515 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002516 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002517
Reid Spencerac5209e2006-10-16 23:08:08 +00002518 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002519 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002520 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002521 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002522 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002523 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002524 ConstantExpr::getNeg(DivRHS));
2525
Chris Lattnerad3448c2003-02-18 19:57:07 +00002526 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002527 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002528 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002529 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002530 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002531 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002532
2533 // X - ((X / Y) * Y) --> X % Y
2534 if (Op1I->getOpcode() == Instruction::Mul)
2535 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2536 if (Op0 == I->getOperand(0) &&
2537 Op1I->getOperand(1) == I->getOperand(1)) {
2538 if (I->getOpcode() == Instruction::SDiv)
2539 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2540 if (I->getOpcode() == Instruction::UDiv)
2541 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2542 }
Chris Lattner40371712002-05-09 01:29:19 +00002543 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002544 }
Chris Lattnera2881962003-02-18 19:28:33 +00002545
Chris Lattner9919e3d2006-12-02 00:13:08 +00002546 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002547 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002548 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002549 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2550 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2551 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2552 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002553 } else if (Op0I->getOpcode() == Instruction::Sub) {
2554 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2555 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002556 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002557 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002558
Chris Lattner50af16a2004-11-13 19:50:12 +00002559 ConstantInt *C1;
2560 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002561 if (X == Op1) // X*C - X --> X * (C-1)
2562 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002563
Chris Lattner50af16a2004-11-13 19:50:12 +00002564 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2565 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002566 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002567 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002568 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002569}
2570
Chris Lattnera0141b92007-07-15 20:42:37 +00002571/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2572/// comparison only checks the sign bit. If it only checks the sign bit, set
2573/// TrueIfSigned if the result of the comparison is true when the input value is
2574/// signed.
2575static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2576 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002577 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002578 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2579 TrueIfSigned = true;
2580 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002581 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2582 TrueIfSigned = true;
2583 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002584 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2585 TrueIfSigned = false;
2586 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002587 case ICmpInst::ICMP_UGT:
2588 // True if LHS u> RHS and RHS == high-bit-mask - 1
2589 TrueIfSigned = true;
2590 return RHS->getValue() ==
2591 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2592 case ICmpInst::ICMP_UGE:
2593 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2594 TrueIfSigned = true;
2595 return RHS->getValue() ==
2596 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002597 default:
2598 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002599 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002600}
2601
Chris Lattner7e708292002-06-25 16:13:24 +00002602Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002603 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002604 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002605
Chris Lattnere87597f2004-10-16 18:11:37 +00002606 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2607 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2608
Chris Lattner233f7dc2002-08-12 21:17:25 +00002609 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002610 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2611 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002612
2613 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002614 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002615 if (SI->getOpcode() == Instruction::Shl)
2616 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002617 return BinaryOperator::createMul(SI->getOperand(0),
2618 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002619
Zhou Sheng843f07672007-04-19 05:39:12 +00002620 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002621 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2622 if (CI->equalsInt(1)) // X * 1 == X
2623 return ReplaceInstUsesWith(I, Op0);
2624 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002625 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002626
Zhou Sheng97b52c22007-03-29 01:57:21 +00002627 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002628 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002629 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002630 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002631 }
Robert Bocchino71698282004-07-27 21:02:21 +00002632 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002633 if (Op1F->isNullValue())
2634 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002635
Chris Lattnera2881962003-02-18 19:28:33 +00002636 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2637 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002638 // We need a better interface for long double here.
2639 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2640 if (Op1F->isExactlyValue(1.0))
2641 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002642 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002643
2644 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2645 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2646 isa<ConstantInt>(Op0I->getOperand(1))) {
2647 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2648 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2649 Op1, "tmp");
2650 InsertNewInstBefore(Add, I);
2651 Value *C1C2 = ConstantExpr::getMul(Op1,
2652 cast<Constant>(Op0I->getOperand(1)));
2653 return BinaryOperator::createAdd(Add, C1C2);
2654
2655 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002656
2657 // Try to fold constant mul into select arguments.
2658 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002659 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002660 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002661
2662 if (isa<PHINode>(Op0))
2663 if (Instruction *NV = FoldOpIntoPhi(I))
2664 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002665 }
2666
Chris Lattnera4f445b2003-03-10 23:23:04 +00002667 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2668 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002669 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002670
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002671 // If one of the operands of the multiply is a cast from a boolean value, then
2672 // we know the bool is either zero or one, so this is a 'masking' multiply.
2673 // See if we can simplify things based on how the boolean was originally
2674 // formed.
2675 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002676 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002677 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002678 BoolCast = CI;
2679 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002680 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002681 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002682 BoolCast = CI;
2683 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002684 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002685 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2686 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002687 bool TIS = false;
2688
Reid Spencere4d87aa2006-12-23 06:05:41 +00002689 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002690 // multiply into a shift/and combination.
2691 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002692 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2693 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002694 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002695 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002696 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002697 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002698 InsertNewInstBefore(
2699 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002700 BoolCast->getOperand(0)->getName()+
2701 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002702
2703 // If the multiply type is not the same as the source type, sign extend
2704 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002705 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002706 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2707 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002708 Instruction::CastOps opcode =
2709 (SrcBits == DstBits ? Instruction::BitCast :
2710 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2711 V = InsertCastBefore(opcode, V, I.getType(), I);
2712 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002713
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002714 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002715 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002716 }
2717 }
2718 }
2719
Chris Lattner7e708292002-06-25 16:13:24 +00002720 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002721}
2722
Reid Spencer1628cec2006-10-26 06:15:43 +00002723/// This function implements the transforms on div instructions that work
2724/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2725/// used by the visitors to those instructions.
2726/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002727Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002728 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002729
Chris Lattner50b2ca42008-02-19 06:12:18 +00002730 // undef / X -> 0 for integer.
2731 // undef / X -> undef for FP (the undef could be a snan).
2732 if (isa<UndefValue>(Op0)) {
2733 if (Op0->getType()->isFPOrFPVector())
2734 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002735 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002736 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002737
2738 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002739 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002740 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002741
Chris Lattner25feae52008-01-28 00:58:18 +00002742 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2743 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002744 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002745 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2746 // the same basic block, then we replace the select with Y, and the
2747 // condition of the select with false (if the cond value is in the same BB).
2748 // If the select has uses other than the div, this allows them to be
2749 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2750 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002751 if (ST->isNullValue()) {
2752 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2753 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002754 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002755 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2756 I.setOperand(1, SI->getOperand(2));
2757 else
2758 UpdateValueUsesWith(SI, SI->getOperand(2));
2759 return &I;
2760 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002761
Chris Lattner25feae52008-01-28 00:58:18 +00002762 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2763 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002764 if (ST->isNullValue()) {
2765 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2766 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002767 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002768 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2769 I.setOperand(1, SI->getOperand(1));
2770 else
2771 UpdateValueUsesWith(SI, SI->getOperand(1));
2772 return &I;
2773 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002774 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002775
Reid Spencer1628cec2006-10-26 06:15:43 +00002776 return 0;
2777}
Misha Brukmanfd939082005-04-21 23:48:37 +00002778
Reid Spencer1628cec2006-10-26 06:15:43 +00002779/// This function implements the transforms common to both integer division
2780/// instructions (udiv and sdiv). It is called by the visitors to those integer
2781/// division instructions.
2782/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002783Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2785
2786 if (Instruction *Common = commonDivTransforms(I))
2787 return Common;
2788
2789 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2790 // div X, 1 == X
2791 if (RHS->equalsInt(1))
2792 return ReplaceInstUsesWith(I, Op0);
2793
2794 // (X / C1) / C2 -> X / (C1*C2)
2795 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2796 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2797 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002798 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2799 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2800 else
2801 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2802 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002803 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002804
Reid Spencerbca0e382007-03-23 20:05:17 +00002805 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002806 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2807 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2808 return R;
2809 if (isa<PHINode>(Op0))
2810 if (Instruction *NV = FoldOpIntoPhi(I))
2811 return NV;
2812 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002813 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002814
Chris Lattnera2881962003-02-18 19:28:33 +00002815 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002816 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002817 if (LHS->equalsInt(0))
2818 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2819
Reid Spencer1628cec2006-10-26 06:15:43 +00002820 return 0;
2821}
2822
2823Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2824 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2825
2826 // Handle the integer div common cases
2827 if (Instruction *Common = commonIDivTransforms(I))
2828 return Common;
2829
2830 // X udiv C^2 -> X >> C
2831 // Check to see if this is an unsigned division with an exact power of 2,
2832 // if so, convert to a right shift.
2833 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002834 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002835 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002836 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002837 }
2838
2839 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002840 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002841 if (RHSI->getOpcode() == Instruction::Shl &&
2842 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002843 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002844 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002845 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002846 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002847 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002848 Constant *C2V = ConstantInt::get(NTy, C2);
2849 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002850 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002851 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002852 }
2853 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002854 }
2855
Reid Spencer1628cec2006-10-26 06:15:43 +00002856 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2857 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002858 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002859 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002860 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002861 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002862 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002863 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002864 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002865 // Construct the "on true" case of the select
2866 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2867 Instruction *TSI = BinaryOperator::createLShr(
2868 Op0, TC, SI->getName()+".t");
2869 TSI = InsertNewInstBefore(TSI, I);
2870
2871 // Construct the "on false" case of the select
2872 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2873 Instruction *FSI = BinaryOperator::createLShr(
2874 Op0, FC, SI->getName()+".f");
2875 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002876
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002877 // construct the select instruction and return it.
2878 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002879 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002880 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002881 return 0;
2882}
2883
Reid Spencer1628cec2006-10-26 06:15:43 +00002884Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2885 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2886
2887 // Handle the integer div common cases
2888 if (Instruction *Common = commonIDivTransforms(I))
2889 return Common;
2890
2891 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2892 // sdiv X, -1 == -X
2893 if (RHS->isAllOnesValue())
2894 return BinaryOperator::createNeg(Op0);
2895
2896 // -X/C -> X/-C
2897 if (Value *LHSNeg = dyn_castNegVal(Op0))
2898 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2899 }
2900
2901 // If the sign bits of both operands are zero (i.e. we can prove they are
2902 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002903 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002904 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002905 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002906 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002907 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2908 }
2909 }
2910
2911 return 0;
2912}
2913
2914Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2915 return commonDivTransforms(I);
2916}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002917
Reid Spencer0a783f72006-11-02 01:53:59 +00002918/// This function implements the transforms on rem instructions that work
2919/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2920/// is used by the visitors to those instructions.
2921/// @brief Transforms common to all three rem instructions
2922Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002924
Chris Lattner50b2ca42008-02-19 06:12:18 +00002925 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002926 if (Constant *LHS = dyn_cast<Constant>(Op0))
2927 if (LHS->isNullValue())
2928 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2929
Chris Lattner50b2ca42008-02-19 06:12:18 +00002930 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2931 if (I.getType()->isFPOrFPVector())
2932 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002933 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002934 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002935 if (isa<UndefValue>(Op1))
2936 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002937
2938 // Handle cases involving: rem X, (select Cond, Y, Z)
2939 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2940 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2941 // the same basic block, then we replace the select with Y, and the
2942 // condition of the select with false (if the cond value is in the same
2943 // BB). If the select has uses other than the div, this allows them to be
2944 // simplified also.
2945 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2946 if (ST->isNullValue()) {
2947 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2948 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002949 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002950 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2951 I.setOperand(1, SI->getOperand(2));
2952 else
2953 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002954 return &I;
2955 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002956 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2957 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2958 if (ST->isNullValue()) {
2959 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2960 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002961 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002962 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2963 I.setOperand(1, SI->getOperand(1));
2964 else
2965 UpdateValueUsesWith(SI, SI->getOperand(1));
2966 return &I;
2967 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002968 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002969
Reid Spencer0a783f72006-11-02 01:53:59 +00002970 return 0;
2971}
2972
2973/// This function implements the transforms common to both integer remainder
2974/// instructions (urem and srem). It is called by the visitors to those integer
2975/// remainder instructions.
2976/// @brief Common integer remainder transforms
2977Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2978 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2979
2980 if (Instruction *common = commonRemTransforms(I))
2981 return common;
2982
Chris Lattner857e8cd2004-12-12 21:48:58 +00002983 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002984 // X % 0 == undef, we don't need to preserve faults!
2985 if (RHS->equalsInt(0))
2986 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2987
Chris Lattnera2881962003-02-18 19:28:33 +00002988 if (RHS->equalsInt(1)) // X % 1 == 0
2989 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2990
Chris Lattner97943922006-02-28 05:49:21 +00002991 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2992 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2993 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2994 return R;
2995 } else if (isa<PHINode>(Op0I)) {
2996 if (Instruction *NV = FoldOpIntoPhi(I))
2997 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002998 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00002999
3000 // See if we can fold away this rem instruction.
3001 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3002 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3003 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3004 KnownZero, KnownOne))
3005 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003006 }
Chris Lattnera2881962003-02-18 19:28:33 +00003007 }
3008
Reid Spencer0a783f72006-11-02 01:53:59 +00003009 return 0;
3010}
3011
3012Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3014
3015 if (Instruction *common = commonIRemTransforms(I))
3016 return common;
3017
3018 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3019 // X urem C^2 -> X and C
3020 // Check to see if this is an unsigned remainder with an exact power of 2,
3021 // if so, convert to a bitwise and.
3022 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003023 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00003024 return BinaryOperator::createAnd(Op0, SubOne(C));
3025 }
3026
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003027 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003028 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3029 if (RHSI->getOpcode() == Instruction::Shl &&
3030 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003031 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003032 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3033 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3034 "tmp"), I);
3035 return BinaryOperator::createAnd(Op0, Add);
3036 }
3037 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003038 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003039
Reid Spencer0a783f72006-11-02 01:53:59 +00003040 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3041 // where C1&C2 are powers of two.
3042 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3043 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3044 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3045 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003046 if ((STO->getValue().isPowerOf2()) &&
3047 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003048 Value *TrueAnd = InsertNewInstBefore(
3049 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3050 Value *FalseAnd = InsertNewInstBefore(
3051 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3052 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3053 }
3054 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003055 }
3056
Chris Lattner3f5b8772002-05-06 16:14:14 +00003057 return 0;
3058}
3059
Reid Spencer0a783f72006-11-02 01:53:59 +00003060Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3061 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3062
Dan Gohmancff55092007-11-05 23:16:33 +00003063 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00003064 if (Instruction *common = commonIRemTransforms(I))
3065 return common;
3066
3067 if (Value *RHSNeg = dyn_castNegVal(Op1))
3068 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00003069 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003070 // X % -Y -> X % Y
3071 AddUsesToWorkList(I);
3072 I.setOperand(1, RHSNeg);
3073 return &I;
3074 }
3075
Dan Gohmancff55092007-11-05 23:16:33 +00003076 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003077 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003078 if (I.getType()->isInteger()) {
3079 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3080 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3081 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3082 return BinaryOperator::createURem(Op0, Op1, I.getName());
3083 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003084 }
3085
3086 return 0;
3087}
3088
3089Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003090 return commonRemTransforms(I);
3091}
3092
Chris Lattner8b170942002-08-09 23:47:40 +00003093// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003094static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00003095 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00003096 if (!isSigned)
3097 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3098 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003099}
3100
3101// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003102static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003103 if (!isSigned)
3104 return C->getValue() == 1; // unsigned
3105
3106 // Calculate 1111111111000000000000
3107 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3108 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003109}
3110
Chris Lattner457dd822004-06-09 07:59:58 +00003111// isOneBitSet - Return true if there is exactly one bit set in the specified
3112// constant.
3113static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003114 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003115}
3116
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003117// isHighOnes - Return true if the constant is of the form 1+0+.
3118// This is the same as lowones(~X).
3119static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003120 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003121}
3122
Reid Spencere4d87aa2006-12-23 06:05:41 +00003123/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003124/// are carefully arranged to allow folding of expressions such as:
3125///
3126/// (A < B) | (A > B) --> (A != B)
3127///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003128/// Note that this is only valid if the first and second predicates have the
3129/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003130///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003131/// Three bits are used to represent the condition, as follows:
3132/// 0 A > B
3133/// 1 A == B
3134/// 2 A < B
3135///
3136/// <=> Value Definition
3137/// 000 0 Always false
3138/// 001 1 A > B
3139/// 010 2 A == B
3140/// 011 3 A >= B
3141/// 100 4 A < B
3142/// 101 5 A != B
3143/// 110 6 A <= B
3144/// 111 7 Always true
3145///
3146static unsigned getICmpCode(const ICmpInst *ICI) {
3147 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003148 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003149 case ICmpInst::ICMP_UGT: return 1; // 001
3150 case ICmpInst::ICMP_SGT: return 1; // 001
3151 case ICmpInst::ICMP_EQ: return 2; // 010
3152 case ICmpInst::ICMP_UGE: return 3; // 011
3153 case ICmpInst::ICMP_SGE: return 3; // 011
3154 case ICmpInst::ICMP_ULT: return 4; // 100
3155 case ICmpInst::ICMP_SLT: return 4; // 100
3156 case ICmpInst::ICMP_NE: return 5; // 101
3157 case ICmpInst::ICMP_ULE: return 6; // 110
3158 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003159 // True -> 7
3160 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003161 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003162 return 0;
3163 }
3164}
3165
Reid Spencere4d87aa2006-12-23 06:05:41 +00003166/// getICmpValue - This is the complement of getICmpCode, which turns an
3167/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003168/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003169/// of predicate to use in new icmp instructions.
3170static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3171 switch (code) {
3172 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003173 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003174 case 1:
3175 if (sign)
3176 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3177 else
3178 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3179 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3180 case 3:
3181 if (sign)
3182 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3183 else
3184 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3185 case 4:
3186 if (sign)
3187 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3188 else
3189 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3190 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3191 case 6:
3192 if (sign)
3193 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3194 else
3195 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003196 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003197 }
3198}
3199
Reid Spencere4d87aa2006-12-23 06:05:41 +00003200static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3201 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3202 (ICmpInst::isSignedPredicate(p1) &&
3203 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3204 (ICmpInst::isSignedPredicate(p2) &&
3205 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3206}
3207
3208namespace {
3209// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3210struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003211 InstCombiner &IC;
3212 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003213 ICmpInst::Predicate pred;
3214 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3215 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3216 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003217 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003218 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3219 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003220 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3221 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003222 return false;
3223 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003224 Instruction *apply(Instruction &Log) const {
3225 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3226 if (ICI->getOperand(0) != LHS) {
3227 assert(ICI->getOperand(1) == LHS);
3228 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003229 }
3230
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003231 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003232 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003233 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003234 unsigned Code;
3235 switch (Log.getOpcode()) {
3236 case Instruction::And: Code = LHSCode & RHSCode; break;
3237 case Instruction::Or: Code = LHSCode | RHSCode; break;
3238 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003239 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003240 }
3241
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003242 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3243 ICmpInst::isSignedPredicate(ICI->getPredicate());
3244
3245 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003246 if (Instruction *I = dyn_cast<Instruction>(RV))
3247 return I;
3248 // Otherwise, it's a constant boolean value...
3249 return IC.ReplaceInstUsesWith(Log, RV);
3250 }
3251};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003252} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003253
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003254// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3255// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003256// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003257Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003258 ConstantInt *OpRHS,
3259 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003260 BinaryOperator &TheAnd) {
3261 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003262 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003263 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003264 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003265
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003266 switch (Op->getOpcode()) {
3267 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003268 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003269 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003270 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003271 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003272 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003273 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003274 }
3275 break;
3276 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003277 if (Together == AndRHS) // (X | C) & C --> C
3278 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003279
Chris Lattner6e7ba452005-01-01 16:22:27 +00003280 if (Op->hasOneUse() && Together != OpRHS) {
3281 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003282 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003283 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003284 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003285 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003286 }
3287 break;
3288 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003289 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003290 // Adding a one to a single bit bit-field should be turned into an XOR
3291 // of the bit. First thing to check is to see if this AND is with a
3292 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003293 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003294
3295 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003296 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003297 // Ok, at this point, we know that we are masking the result of the
3298 // ADD down to exactly one bit. If the constant we are adding has
3299 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003300 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003301
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003302 // Check to see if any bits below the one bit set in AndRHSV are set.
3303 if ((AddRHS & (AndRHSV-1)) == 0) {
3304 // If not, the only thing that can effect the output of the AND is
3305 // the bit specified by AndRHSV. If that bit is set, the effect of
3306 // the XOR is to toggle the bit. If it is clear, then the ADD has
3307 // no effect.
3308 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3309 TheAnd.setOperand(0, X);
3310 return &TheAnd;
3311 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003312 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003313 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003314 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003315 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003316 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003317 }
3318 }
3319 }
3320 }
3321 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003322
3323 case Instruction::Shl: {
3324 // We know that the AND will not produce any of the bits shifted in, so if
3325 // the anded constant includes them, clear them now!
3326 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003327 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003328 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003329 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3330 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003331
Zhou Sheng290bec52007-03-29 08:15:12 +00003332 if (CI->getValue() == ShlMask) {
3333 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003334 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3335 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003336 TheAnd.setOperand(1, CI);
3337 return &TheAnd;
3338 }
3339 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003340 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003341 case Instruction::LShr:
3342 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003343 // We know that the AND will not produce any of the bits shifted in, so if
3344 // the anded constant includes them, clear them now! This only applies to
3345 // unsigned shifts, because a signed shr may bring in set bits!
3346 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003347 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003348 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003349 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3350 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003351
Zhou Sheng290bec52007-03-29 08:15:12 +00003352 if (CI->getValue() == ShrMask) {
3353 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003354 return ReplaceInstUsesWith(TheAnd, Op);
3355 } else if (CI != AndRHS) {
3356 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3357 return &TheAnd;
3358 }
3359 break;
3360 }
3361 case Instruction::AShr:
3362 // Signed shr.
3363 // See if this is shifting in some sign extension, then masking it out
3364 // with an and.
3365 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003366 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003367 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003368 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3369 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003370 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003371 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003372 // Make the argument unsigned.
3373 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003374 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003375 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003376 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003377 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003378 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003379 }
3380 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003381 }
3382 return 0;
3383}
3384
Chris Lattner8b170942002-08-09 23:47:40 +00003385
Chris Lattnera96879a2004-09-29 17:40:11 +00003386/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3387/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003388/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3389/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003390/// insert new instructions.
3391Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003392 bool isSigned, bool Inside,
3393 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003394 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003395 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003396 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397
Chris Lattnera96879a2004-09-29 17:40:11 +00003398 if (Inside) {
3399 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003401
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003403 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003404 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003405 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3406 return new ICmpInst(pred, V, Hi);
3407 }
3408
3409 // Emit V-Lo <u Hi-Lo
3410 Constant *NegLo = ConstantExpr::getNeg(Lo);
3411 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003412 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003413 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3414 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003415 }
3416
3417 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003418 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003419
Reid Spencere4e40032007-03-21 23:19:50 +00003420 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003421 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003422 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003423 ICmpInst::Predicate pred = (isSigned ?
3424 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3425 return new ICmpInst(pred, V, Hi);
3426 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003427
Reid Spencere4e40032007-03-21 23:19:50 +00003428 // Emit V-Lo >u Hi-1-Lo
3429 // Note that Hi has already had one subtracted from it, above.
3430 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003431 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003432 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003433 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3434 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003435}
3436
Chris Lattner7203e152005-09-18 07:22:02 +00003437// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3438// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3439// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3440// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003441static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003442 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003443 uint32_t BitWidth = Val->getType()->getBitWidth();
3444 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003445
3446 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003447 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003448 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003449 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003450 return true;
3451}
3452
Chris Lattner7203e152005-09-18 07:22:02 +00003453/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3454/// where isSub determines whether the operator is a sub. If we can fold one of
3455/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003456///
3457/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3458/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3459/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3460///
3461/// return (A +/- B).
3462///
3463Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003464 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003465 Instruction &I) {
3466 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3467 if (!LHSI || LHSI->getNumOperands() != 2 ||
3468 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3469
3470 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3471
3472 switch (LHSI->getOpcode()) {
3473 default: return 0;
3474 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003475 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003476 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003477 if ((Mask->getValue().countLeadingZeros() +
3478 Mask->getValue().countPopulation()) ==
3479 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003480 break;
3481
3482 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3483 // part, we don't need any explicit masks to take them out of A. If that
3484 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003485 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003486 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003487 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003488 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003489 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003490 break;
3491 }
3492 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003493 return 0;
3494 case Instruction::Or:
3495 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003496 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003497 if ((Mask->getValue().countLeadingZeros() +
3498 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003499 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003500 break;
3501 return 0;
3502 }
3503
3504 Instruction *New;
3505 if (isSub)
3506 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3507 else
3508 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3509 return InsertNewInstBefore(New, I);
3510}
3511
Chris Lattner7e708292002-06-25 16:13:24 +00003512Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003513 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003514 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003515
Chris Lattnere87597f2004-10-16 18:11:37 +00003516 if (isa<UndefValue>(Op1)) // X & undef -> 0
3517 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3518
Chris Lattner6e7ba452005-01-01 16:22:27 +00003519 // and X, X = X
3520 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003521 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003522
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003523 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003524 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003525 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003526 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3527 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3528 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003529 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003530 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003531 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003532 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003533 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003534 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003535 } else if (isa<ConstantAggregateZero>(Op1)) {
3536 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003537 }
3538 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003539
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003540 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003541 const APInt& AndRHSMask = AndRHS->getValue();
3542 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003543
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003544 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003545 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003547 Value *Op0LHS = Op0I->getOperand(0);
3548 Value *Op0RHS = Op0I->getOperand(1);
3549 switch (Op0I->getOpcode()) {
3550 case Instruction::Xor:
3551 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003552 // If the mask is only needed on one incoming arm, push it up.
3553 if (Op0I->hasOneUse()) {
3554 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3555 // Not masking anything out for the LHS, move to RHS.
3556 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3557 Op0RHS->getName()+".masked");
3558 InsertNewInstBefore(NewRHS, I);
3559 return BinaryOperator::create(
3560 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003561 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003562 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003563 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3564 // Not masking anything out for the RHS, move to LHS.
3565 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3566 Op0LHS->getName()+".masked");
3567 InsertNewInstBefore(NewLHS, I);
3568 return BinaryOperator::create(
3569 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3570 }
3571 }
3572
Chris Lattner6e7ba452005-01-01 16:22:27 +00003573 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003574 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003575 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3576 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3577 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3578 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3579 return BinaryOperator::createAnd(V, AndRHS);
3580 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3581 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003582 break;
3583
3584 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003585 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3586 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3587 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3588 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3589 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003590 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003591 }
3592
Chris Lattner58403262003-07-23 19:25:52 +00003593 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003594 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003595 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003596 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003597 // If this is an integer truncation or change from signed-to-unsigned, and
3598 // if the source is an and/or with immediate, transform it. This
3599 // frequently occurs for bitfield accesses.
3600 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003601 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003602 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003603 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003604 if (CastOp->getOpcode() == Instruction::And) {
3605 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003606 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3607 // This will fold the two constants together, which may allow
3608 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003609 Instruction *NewCast = CastInst::createTruncOrBitCast(
3610 CastOp->getOperand(0), I.getType(),
3611 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003612 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003613 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003614 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003615 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003616 return BinaryOperator::createAnd(NewCast, C3);
3617 } else if (CastOp->getOpcode() == Instruction::Or) {
3618 // Change: and (cast (or X, C1) to T), C2
3619 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003620 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003621 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3622 return ReplaceInstUsesWith(I, AndRHS);
3623 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003624 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003625 }
Chris Lattner06782f82003-07-23 19:36:21 +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 Lattnerc6a8aff2003-07-23 17:57:01 +00003635 }
3636
Chris Lattner8d969642003-03-10 23:06:50 +00003637 Value *Op0NotVal = dyn_castNotVal(Op0);
3638 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003639
Chris Lattner5b62aa72004-06-18 06:07:51 +00003640 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3641 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3642
Misha Brukmancb6267b2004-07-30 12:50:08 +00003643 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003644 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003645 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3646 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003647 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003648 return BinaryOperator::createNot(Or);
3649 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003650
3651 {
Chris Lattner003b6202007-06-15 05:58:24 +00003652 Value *A = 0, *B = 0, *C = 0, *D = 0;
3653 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003654 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3655 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003656
3657 // (A|B) & ~(A&B) -> A^B
3658 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3659 if ((A == C && B == D) || (A == D && B == C))
3660 return BinaryOperator::createXor(A, B);
3661 }
3662 }
3663
3664 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003665 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3666 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003667
3668 // ~(A&B) & (A|B) -> A^B
3669 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3670 if ((A == C && B == D) || (A == D && B == C))
3671 return BinaryOperator::createXor(A, B);
3672 }
3673 }
Chris Lattner64daab52006-04-01 08:03:55 +00003674
3675 if (Op0->hasOneUse() &&
3676 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3677 if (A == Op1) { // (A^B)&A -> A&(A^B)
3678 I.swapOperands(); // Simplify below
3679 std::swap(Op0, Op1);
3680 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3681 cast<BinaryOperator>(Op0)->swapOperands();
3682 I.swapOperands(); // Simplify below
3683 std::swap(Op0, Op1);
3684 }
3685 }
3686 if (Op1->hasOneUse() &&
3687 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3688 if (B == Op0) { // B&(A^B) -> B&(B^A)
3689 cast<BinaryOperator>(Op1)->swapOperands();
3690 std::swap(A, B);
3691 }
3692 if (A == Op0) { // A&(A^B) -> A & ~B
3693 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3694 InsertNewInstBefore(NotB, I);
3695 return BinaryOperator::createAnd(A, NotB);
3696 }
3697 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003698 }
3699
Reid Spencere4d87aa2006-12-23 06:05:41 +00003700 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3701 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3702 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003703 return R;
3704
Chris Lattner955f3312004-09-28 21:48:02 +00003705 Value *LHSVal, *RHSVal;
3706 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707 ICmpInst::Predicate LHSCC, RHSCC;
3708 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3709 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3710 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3711 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3712 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3713 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3714 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003715 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3716
3717 // Don't try to fold ICMP_SLT + ICMP_ULT.
3718 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3719 ICmpInst::isSignedPredicate(LHSCC) ==
3720 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003721 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003722 ICmpInst::Predicate GT;
3723 if (ICmpInst::isSignedPredicate(LHSCC) ||
3724 (ICmpInst::isEquality(LHSCC) &&
3725 ICmpInst::isSignedPredicate(RHSCC)))
3726 GT = ICmpInst::ICMP_SGT;
3727 else
3728 GT = ICmpInst::ICMP_UGT;
3729
Reid Spencere4d87aa2006-12-23 06:05:41 +00003730 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3731 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003732 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003733 std::swap(LHS, RHS);
3734 std::swap(LHSCst, RHSCst);
3735 std::swap(LHSCC, RHSCC);
3736 }
3737
Reid Spencere4d87aa2006-12-23 06:05:41 +00003738 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003739 // comparing a value against two constants and and'ing the result
3740 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003741 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3742 // (from the FoldICmpLogical check above), that the two constants
3743 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003744 assert(LHSCst != RHSCst && "Compares not folded above?");
3745
3746 switch (LHSCC) {
3747 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003748 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003749 switch (RHSCC) {
3750 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003751 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3752 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3753 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003754 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003755 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3756 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3757 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003758 return ReplaceInstUsesWith(I, LHS);
3759 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003760 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003761 switch (RHSCC) {
3762 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003763 case ICmpInst::ICMP_ULT:
3764 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3765 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3766 break; // (X != 13 & X u< 15) -> no change
3767 case ICmpInst::ICMP_SLT:
3768 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3769 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3770 break; // (X != 13 & X s< 15) -> no change
3771 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3772 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3773 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003774 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003775 case ICmpInst::ICMP_NE:
3776 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003777 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3778 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3779 LHSVal->getName()+".off");
3780 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003781 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3782 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003783 }
3784 break; // (X != 13 & X != 15) -> no change
3785 }
3786 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003787 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003788 switch (RHSCC) {
3789 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3791 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003792 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003793 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3794 break;
3795 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3796 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003797 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003798 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3799 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003800 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003801 break;
3802 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003803 switch (RHSCC) {
3804 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003805 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3806 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003807 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003808 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3809 break;
3810 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3811 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003812 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003813 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3814 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003815 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003816 break;
3817 case ICmpInst::ICMP_UGT:
3818 switch (RHSCC) {
3819 default: assert(0 && "Unknown integer condition code!");
3820 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3821 return ReplaceInstUsesWith(I, LHS);
3822 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3823 return ReplaceInstUsesWith(I, RHS);
3824 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3825 break;
3826 case ICmpInst::ICMP_NE:
3827 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3828 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3829 break; // (X u> 13 & X != 15) -> no change
3830 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3831 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3832 true, I);
3833 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3834 break;
3835 }
3836 break;
3837 case ICmpInst::ICMP_SGT:
3838 switch (RHSCC) {
3839 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003840 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003841 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3842 return ReplaceInstUsesWith(I, RHS);
3843 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3844 break;
3845 case ICmpInst::ICMP_NE:
3846 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3847 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3848 break; // (X s> 13 & X != 15) -> no change
3849 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3850 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3851 true, I);
3852 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3853 break;
3854 }
3855 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003856 }
3857 }
3858 }
3859
Chris Lattner6fc205f2006-05-05 06:39:07 +00003860 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003861 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3862 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3863 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3864 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003865 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003866 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003867 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3868 I.getType(), TD) &&
3869 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3870 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003871 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3872 Op1C->getOperand(0),
3873 I.getName());
3874 InsertNewInstBefore(NewOp, I);
3875 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3876 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003877 }
Chris Lattnere511b742006-11-14 07:46:50 +00003878
3879 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003880 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3881 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3882 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003883 SI0->getOperand(1) == SI1->getOperand(1) &&
3884 (SI0->hasOneUse() || SI1->hasOneUse())) {
3885 Instruction *NewOp =
3886 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3887 SI1->getOperand(0),
3888 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003889 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3890 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003891 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003892 }
3893
Chris Lattner99c65742007-10-24 05:38:08 +00003894 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3895 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3896 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3897 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3898 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3899 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3900 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3901 // If either of the constants are nans, then the whole thing returns
3902 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003903 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003904 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3905 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3906 RHS->getOperand(0));
3907 }
3908 }
3909 }
3910
Chris Lattner7e708292002-06-25 16:13:24 +00003911 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003912}
3913
Chris Lattnerafe91a52006-06-15 19:07:26 +00003914/// CollectBSwapParts - Look to see if the specified value defines a single byte
3915/// in the result. If it does, and if the specified byte hasn't been filled in
3916/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003917static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003918 Instruction *I = dyn_cast<Instruction>(V);
3919 if (I == 0) return true;
3920
3921 // If this is an or instruction, it is an inner node of the bswap.
3922 if (I->getOpcode() == Instruction::Or)
3923 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3924 CollectBSwapParts(I->getOperand(1), ByteValues);
3925
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003926 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003927 // If this is a shift by a constant int, and it is "24", then its operand
3928 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003929 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003930 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003931 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003932 8*(ByteValues.size()-1))
3933 return true;
3934
3935 unsigned DestNo;
3936 if (I->getOpcode() == Instruction::Shl) {
3937 // X << 24 defines the top byte with the lowest of the input bytes.
3938 DestNo = ByteValues.size()-1;
3939 } else {
3940 // X >>u 24 defines the low byte with the highest of the input bytes.
3941 DestNo = 0;
3942 }
3943
3944 // If the destination byte value is already defined, the values are or'd
3945 // together, which isn't a bswap (unless it's an or of the same bits).
3946 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3947 return true;
3948 ByteValues[DestNo] = I->getOperand(0);
3949 return false;
3950 }
3951
3952 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3953 // don't have this.
3954 Value *Shift = 0, *ShiftLHS = 0;
3955 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3956 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3957 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3958 return true;
3959 Instruction *SI = cast<Instruction>(Shift);
3960
3961 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003962 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3963 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003964 return true;
3965
3966 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3967 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003968 if (AndAmt->getValue().getActiveBits() > 64)
3969 return true;
3970 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003971 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003972 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003973 break;
3974 // Unknown mask for bswap.
3975 if (DestByte == ByteValues.size()) return true;
3976
Reid Spencerb83eb642006-10-20 07:07:24 +00003977 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003978 unsigned SrcByte;
3979 if (SI->getOpcode() == Instruction::Shl)
3980 SrcByte = DestByte - ShiftBytes;
3981 else
3982 SrcByte = DestByte + ShiftBytes;
3983
3984 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3985 if (SrcByte != ByteValues.size()-DestByte-1)
3986 return true;
3987
3988 // If the destination byte value is already defined, the values are or'd
3989 // together, which isn't a bswap (unless it's an or of the same bits).
3990 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3991 return true;
3992 ByteValues[DestByte] = SI->getOperand(0);
3993 return false;
3994}
3995
3996/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3997/// If so, insert the new bswap intrinsic and return it.
3998Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003999 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4000 if (!ITy || ITy->getBitWidth() % 16)
4001 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004002
4003 /// ByteValues - For each byte of the result, we keep track of which value
4004 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004005 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004006 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004007
4008 // Try to find all the pieces corresponding to the bswap.
4009 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4010 CollectBSwapParts(I.getOperand(1), ByteValues))
4011 return 0;
4012
4013 // Check to see if all of the bytes come from the same value.
4014 Value *V = ByteValues[0];
4015 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4016
4017 // Check to make sure that all of the bytes come from the same value.
4018 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4019 if (ByteValues[i] != V)
4020 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004021 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004022 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004023 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004024 return new CallInst(F, V);
4025}
4026
4027
Chris Lattner7e708292002-06-25 16:13:24 +00004028Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004029 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004030 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004031
Chris Lattner42593e62007-03-24 23:56:43 +00004032 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004033 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004034
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004035 // or X, X = X
4036 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004037 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004038
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004039 // See if we can simplify any instructions used by the instruction whose sole
4040 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00004041 if (!isa<VectorType>(I.getType())) {
4042 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4043 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4044 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4045 KnownZero, KnownOne))
4046 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004047 } else if (isa<ConstantAggregateZero>(Op1)) {
4048 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4049 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4050 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4051 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00004052 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004053
4054
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004055
Chris Lattner3f5b8772002-05-06 16:14:14 +00004056 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004057 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004058 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004059 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4060 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004061 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004062 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004063 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004064 return BinaryOperator::createAnd(Or,
4065 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004066 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004067
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004068 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4069 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00004070 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004071 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00004072 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004073 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004074 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004075 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004076
4077 // Try to fold constant and into select arguments.
4078 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004079 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004080 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004081 if (isa<PHINode>(Op0))
4082 if (Instruction *NV = FoldOpIntoPhi(I))
4083 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004084 }
4085
Chris Lattner4f637d42006-01-06 17:59:59 +00004086 Value *A = 0, *B = 0;
4087 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004088
4089 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4090 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4091 return ReplaceInstUsesWith(I, Op1);
4092 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4093 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4094 return ReplaceInstUsesWith(I, Op0);
4095
Chris Lattner6423d4c2006-07-10 20:25:24 +00004096 // (A | B) | C and A | (B | C) -> bswap if possible.
4097 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004098 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004099 match(Op1, m_Or(m_Value(), m_Value())) ||
4100 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4101 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004102 if (Instruction *BSwap = MatchBSwap(I))
4103 return BSwap;
4104 }
4105
Chris Lattner6e4c6492005-05-09 04:58:36 +00004106 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4107 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004108 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004109 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4110 InsertNewInstBefore(NOr, I);
4111 NOr->takeName(Op0);
4112 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004113 }
4114
4115 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4116 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004117 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004118 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4119 InsertNewInstBefore(NOr, I);
4120 NOr->takeName(Op0);
4121 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004122 }
4123
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004124 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004125 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004126 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4127 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004128 Value *V1 = 0, *V2 = 0, *V3 = 0;
4129 C1 = dyn_cast<ConstantInt>(C);
4130 C2 = dyn_cast<ConstantInt>(D);
4131 if (C1 && C2) { // (A & C1)|(B & C2)
4132 // If we have: ((V + N) & C1) | (V & C2)
4133 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4134 // replace with V+N.
4135 if (C1->getValue() == ~C2->getValue()) {
4136 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4137 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4138 // Add commutes, try both ways.
4139 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4140 return ReplaceInstUsesWith(I, A);
4141 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4142 return ReplaceInstUsesWith(I, A);
4143 }
4144 // Or commutes, try both ways.
4145 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4146 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4147 // Add commutes, try both ways.
4148 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4149 return ReplaceInstUsesWith(I, B);
4150 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4151 return ReplaceInstUsesWith(I, B);
4152 }
4153 }
Chris Lattner044e5332007-04-08 08:01:49 +00004154 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004155 }
4156
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004157 // Check to see if we have any common things being and'ed. If so, find the
4158 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004159 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4160 if (A == B) // (A & C)|(A & D) == A & (C|D)
4161 V1 = A, V2 = C, V3 = D;
4162 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4163 V1 = A, V2 = B, V3 = C;
4164 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4165 V1 = C, V2 = A, V3 = D;
4166 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4167 V1 = C, V2 = A, V3 = B;
4168
4169 if (V1) {
4170 Value *Or =
4171 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4172 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004173 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004174 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004175 }
Chris Lattnere511b742006-11-14 07:46:50 +00004176
4177 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004178 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4179 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4180 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004181 SI0->getOperand(1) == SI1->getOperand(1) &&
4182 (SI0->hasOneUse() || SI1->hasOneUse())) {
4183 Instruction *NewOp =
4184 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4185 SI1->getOperand(0),
4186 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004187 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4188 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004189 }
4190 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004191
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004192 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4193 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004194 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004195 } else {
4196 A = 0;
4197 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004198 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004199 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4200 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004201 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004202
Misha Brukmancb6267b2004-07-30 12:50:08 +00004203 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004204 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4205 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4206 I.getName()+".demorgan"), I);
4207 return BinaryOperator::createNot(And);
4208 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004209 }
Chris Lattnera2881962003-02-18 19:28:33 +00004210
Reid Spencere4d87aa2006-12-23 06:05:41 +00004211 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4212 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4213 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004214 return R;
4215
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004216 Value *LHSVal, *RHSVal;
4217 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004218 ICmpInst::Predicate LHSCC, RHSCC;
4219 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4220 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4221 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4222 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4223 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4224 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4225 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004226 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4227 // We can't fold (ugt x, C) | (sgt x, C2).
4228 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004229 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004230 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004231 bool NeedsSwap;
4232 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004233 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004234 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004235 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004236
4237 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004238 std::swap(LHS, RHS);
4239 std::swap(LHSCst, RHSCst);
4240 std::swap(LHSCC, RHSCC);
4241 }
4242
Reid Spencere4d87aa2006-12-23 06:05:41 +00004243 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004244 // comparing a value against two constants and or'ing the result
4245 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004246 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4247 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004248 // equal.
4249 assert(LHSCst != RHSCst && "Compares not folded above?");
4250
4251 switch (LHSCC) {
4252 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004253 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004254 switch (RHSCC) {
4255 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004256 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004257 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4258 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4259 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4260 LHSVal->getName()+".off");
4261 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004262 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004263 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004264 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004265 break; // (X == 13 | X == 15) -> no change
4266 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4267 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004268 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004269 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4270 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4271 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004272 return ReplaceInstUsesWith(I, RHS);
4273 }
4274 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004275 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004276 switch (RHSCC) {
4277 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004278 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4279 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4280 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004281 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004282 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4283 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4284 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004285 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004286 }
4287 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004288 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004289 switch (RHSCC) {
4290 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004291 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004292 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004293 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004294 // If RHSCst is [us]MAXINT, it is always false. Not handling
4295 // this can cause overflow.
4296 if (RHSCst->isMaxValue(false))
4297 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004298 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4299 false, I);
4300 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4301 break;
4302 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4303 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004304 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004305 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4306 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004307 }
4308 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004309 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004310 switch (RHSCC) {
4311 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004312 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4313 break;
4314 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004315 // If RHSCst is [us]MAXINT, it is always false. Not handling
4316 // this can cause overflow.
4317 if (RHSCst->isMaxValue(true))
4318 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004319 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4320 false, I);
4321 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4322 break;
4323 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4324 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4325 return ReplaceInstUsesWith(I, RHS);
4326 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4327 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004328 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004329 break;
4330 case ICmpInst::ICMP_UGT:
4331 switch (RHSCC) {
4332 default: assert(0 && "Unknown integer condition code!");
4333 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4334 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4335 return ReplaceInstUsesWith(I, LHS);
4336 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4337 break;
4338 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4339 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004340 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004341 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4342 break;
4343 }
4344 break;
4345 case ICmpInst::ICMP_SGT:
4346 switch (RHSCC) {
4347 default: assert(0 && "Unknown integer condition code!");
4348 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4349 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4350 return ReplaceInstUsesWith(I, LHS);
4351 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4352 break;
4353 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4354 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004355 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004356 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4357 break;
4358 }
4359 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004360 }
4361 }
4362 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004363
4364 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004365 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004366 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004367 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004368 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4369 !isa<ICmpInst>(Op1C->getOperand(0))) {
4370 const Type *SrcTy = Op0C->getOperand(0)->getType();
4371 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4372 // Only do this if the casts both really cause code to be
4373 // generated.
4374 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4375 I.getType(), TD) &&
4376 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4377 I.getType(), TD)) {
4378 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4379 Op1C->getOperand(0),
4380 I.getName());
4381 InsertNewInstBefore(NewOp, I);
4382 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4383 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004384 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004385 }
Chris Lattner99c65742007-10-24 05:38:08 +00004386 }
4387
4388
4389 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4390 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4391 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4392 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004393 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4394 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004395 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4396 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4397 // If either of the constants are nans, then the whole thing returns
4398 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004399 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004400 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4401
4402 // Otherwise, no need to compare the two constants, compare the
4403 // rest.
4404 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4405 RHS->getOperand(0));
4406 }
4407 }
4408 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004409
Chris Lattner7e708292002-06-25 16:13:24 +00004410 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004411}
4412
Chris Lattnerc317d392004-02-16 01:20:27 +00004413// XorSelf - Implements: X ^ X --> 0
4414struct XorSelf {
4415 Value *RHS;
4416 XorSelf(Value *rhs) : RHS(rhs) {}
4417 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4418 Instruction *apply(BinaryOperator &Xor) const {
4419 return &Xor;
4420 }
4421};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004422
4423
Chris Lattner7e708292002-06-25 16:13:24 +00004424Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004425 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004426 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004427
Chris Lattnere87597f2004-10-16 18:11:37 +00004428 if (isa<UndefValue>(Op1))
4429 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4430
Chris Lattnerc317d392004-02-16 01:20:27 +00004431 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4432 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004433 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004434 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004435 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004436
4437 // See if we can simplify any instructions used by the instruction whose sole
4438 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004439 if (!isa<VectorType>(I.getType())) {
4440 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4441 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4442 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4443 KnownZero, KnownOne))
4444 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004445 } else if (isa<ConstantAggregateZero>(Op1)) {
4446 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004447 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004448
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004449 // Is this a ~ operation?
4450 if (Value *NotOp = dyn_castNotVal(&I)) {
4451 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4452 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4453 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4454 if (Op0I->getOpcode() == Instruction::And ||
4455 Op0I->getOpcode() == Instruction::Or) {
4456 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4457 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4458 Instruction *NotY =
4459 BinaryOperator::createNot(Op0I->getOperand(1),
4460 Op0I->getOperand(1)->getName()+".not");
4461 InsertNewInstBefore(NotY, I);
4462 if (Op0I->getOpcode() == Instruction::And)
4463 return BinaryOperator::createOr(Op0NotVal, NotY);
4464 else
4465 return BinaryOperator::createAnd(Op0NotVal, NotY);
4466 }
4467 }
4468 }
4469 }
4470
4471
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004472 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004473 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4474 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4475 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004476 return new ICmpInst(ICI->getInversePredicate(),
4477 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004478
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004479 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4480 return new FCmpInst(FCI->getInversePredicate(),
4481 FCI->getOperand(0), FCI->getOperand(1));
4482 }
4483
Reid Spencere4d87aa2006-12-23 06:05:41 +00004484 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004485 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004486 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4487 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004488 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4489 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004490 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004491 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004492 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004493
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004494 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004495 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004496 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004497 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004498 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4499 return BinaryOperator::createSub(
4500 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004501 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004502 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004503 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004504 // (X + C) ^ signbit -> (X + C + signbit)
4505 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4506 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004507
Chris Lattner7c4049c2004-01-12 19:35:11 +00004508 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004509 } else if (Op0I->getOpcode() == Instruction::Or) {
4510 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004511 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004512 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4513 // Anything in both C1 and C2 is known to be zero, remove it from
4514 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004515 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004516 NewRHS = ConstantExpr::getAnd(NewRHS,
4517 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004518 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004519 I.setOperand(0, Op0I->getOperand(0));
4520 I.setOperand(1, NewRHS);
4521 return &I;
4522 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004523 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004524 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004525 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004526
4527 // Try to fold constant and into select arguments.
4528 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004529 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004530 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004531 if (isa<PHINode>(Op0))
4532 if (Instruction *NV = FoldOpIntoPhi(I))
4533 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004534 }
4535
Chris Lattner8d969642003-03-10 23:06:50 +00004536 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004537 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004538 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004539
Chris Lattner8d969642003-03-10 23:06:50 +00004540 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004541 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004542 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004543
Chris Lattner318bf792007-03-18 22:51:34 +00004544
4545 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4546 if (Op1I) {
4547 Value *A, *B;
4548 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4549 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004550 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004551 I.swapOperands();
4552 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004553 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004554 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004555 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004556 }
Chris Lattner318bf792007-03-18 22:51:34 +00004557 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4558 if (Op0 == A) // A^(A^B) == B
4559 return ReplaceInstUsesWith(I, B);
4560 else if (Op0 == B) // A^(B^A) == B
4561 return ReplaceInstUsesWith(I, A);
4562 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004563 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004564 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004565 std::swap(A, B);
4566 }
Chris Lattner318bf792007-03-18 22:51:34 +00004567 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004568 I.swapOperands(); // Simplified below.
4569 std::swap(Op0, Op1);
4570 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004571 }
Chris Lattner318bf792007-03-18 22:51:34 +00004572 }
4573
4574 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4575 if (Op0I) {
4576 Value *A, *B;
4577 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4578 if (A == Op1) // (B|A)^B == (A|B)^B
4579 std::swap(A, B);
4580 if (B == Op1) { // (A|B)^B == A & ~B
4581 Instruction *NotB =
4582 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4583 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004584 }
Chris Lattner318bf792007-03-18 22:51:34 +00004585 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4586 if (Op1 == A) // (A^B)^A == B
4587 return ReplaceInstUsesWith(I, B);
4588 else if (Op1 == B) // (B^A)^A == B
4589 return ReplaceInstUsesWith(I, A);
4590 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4591 if (A == Op1) // (A&B)^A -> (B&A)^A
4592 std::swap(A, B);
4593 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004594 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004595 Instruction *N =
4596 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004597 return BinaryOperator::createAnd(N, Op1);
4598 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004599 }
Chris Lattner318bf792007-03-18 22:51:34 +00004600 }
4601
4602 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4603 if (Op0I && Op1I && Op0I->isShift() &&
4604 Op0I->getOpcode() == Op1I->getOpcode() &&
4605 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4606 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4607 Instruction *NewOp =
4608 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4609 Op1I->getOperand(0),
4610 Op0I->getName()), I);
4611 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4612 Op1I->getOperand(1));
4613 }
4614
4615 if (Op0I && Op1I) {
4616 Value *A, *B, *C, *D;
4617 // (A & B)^(A | B) -> A ^ B
4618 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4619 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4620 if ((A == C && B == D) || (A == D && B == C))
4621 return BinaryOperator::createXor(A, B);
4622 }
4623 // (A | B)^(A & B) -> A ^ B
4624 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4625 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4626 if ((A == C && B == D) || (A == D && B == C))
4627 return BinaryOperator::createXor(A, B);
4628 }
4629
4630 // (A & B)^(C & D)
4631 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4632 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4633 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4634 // (X & Y)^(X & Y) -> (Y^Z) & X
4635 Value *X = 0, *Y = 0, *Z = 0;
4636 if (A == C)
4637 X = A, Y = B, Z = D;
4638 else if (A == D)
4639 X = A, Y = B, Z = C;
4640 else if (B == C)
4641 X = B, Y = A, Z = D;
4642 else if (B == D)
4643 X = B, Y = A, Z = C;
4644
4645 if (X) {
4646 Instruction *NewOp =
4647 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4648 return BinaryOperator::createAnd(NewOp, X);
4649 }
4650 }
4651 }
4652
Reid Spencere4d87aa2006-12-23 06:05:41 +00004653 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4654 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4655 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004656 return R;
4657
Chris Lattner6fc205f2006-05-05 06:39:07 +00004658 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004659 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004660 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004661 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4662 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004663 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004664 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004665 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4666 I.getType(), TD) &&
4667 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4668 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004669 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4670 Op1C->getOperand(0),
4671 I.getName());
4672 InsertNewInstBefore(NewOp, I);
4673 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4674 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004675 }
Chris Lattner99c65742007-10-24 05:38:08 +00004676 }
Chris Lattner7e708292002-06-25 16:13:24 +00004677 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004678}
4679
Chris Lattnera96879a2004-09-29 17:40:11 +00004680/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4681/// overflowed for this type.
4682static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004683 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004684 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004685
Reid Spencere4e40032007-03-21 23:19:50 +00004686 if (IsSigned)
4687 if (In2->getValue().isNegative())
4688 return Result->getValue().sgt(In1->getValue());
4689 else
4690 return Result->getValue().slt(In1->getValue());
4691 else
4692 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004693}
4694
Chris Lattner574da9b2005-01-13 20:14:25 +00004695/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4696/// code necessary to compute the offset from the base pointer (without adding
4697/// in the base pointer). Return the result as a signed integer of intptr size.
4698static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4699 TargetData &TD = IC.getTargetData();
4700 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004701 const Type *IntPtrTy = TD.getIntPtrType();
4702 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004703
4704 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004705 unsigned IntPtrWidth = TD.getPointerSize()*8;
4706 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004707
Chris Lattner574da9b2005-01-13 20:14:25 +00004708 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4709 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004710 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004711 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4712 if (OpC->isZero()) continue;
4713
4714 // Handle a struct index, which adds its field offset to the pointer.
4715 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4716 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4717
4718 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4719 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004720 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004721 Result = IC.InsertNewInstBefore(
4722 BinaryOperator::createAdd(Result,
4723 ConstantInt::get(IntPtrTy, Size),
4724 GEP->getName()+".offs"), I);
4725 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004726 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004727
4728 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4729 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4730 Scale = ConstantExpr::getMul(OC, Scale);
4731 if (Constant *RC = dyn_cast<Constant>(Result))
4732 Result = ConstantExpr::getAdd(RC, Scale);
4733 else {
4734 // Emit an add instruction.
4735 Result = IC.InsertNewInstBefore(
4736 BinaryOperator::createAdd(Result, Scale,
4737 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004738 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004739 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004740 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004741 // Convert to correct type.
4742 if (Op->getType() != IntPtrTy) {
4743 if (Constant *OpC = dyn_cast<Constant>(Op))
4744 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4745 else
4746 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4747 Op->getName()+".c"), I);
4748 }
4749 if (Size != 1) {
4750 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4751 if (Constant *OpC = dyn_cast<Constant>(Op))
4752 Op = ConstantExpr::getMul(OpC, Scale);
4753 else // We'll let instcombine(mul) convert this to a shl if possible.
4754 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4755 GEP->getName()+".idx"), I);
4756 }
4757
4758 // Emit an add instruction.
4759 if (isa<Constant>(Op) && isa<Constant>(Result))
4760 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4761 cast<Constant>(Result));
4762 else
4763 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4764 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004765 }
4766 return Result;
4767}
4768
Reid Spencere4d87aa2006-12-23 06:05:41 +00004769/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004770/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004771Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4772 ICmpInst::Predicate Cond,
4773 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004774 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004775
4776 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4777 if (isa<PointerType>(CI->getOperand(0)->getType()))
4778 RHS = CI->getOperand(0);
4779
Chris Lattner574da9b2005-01-13 20:14:25 +00004780 Value *PtrBase = GEPLHS->getOperand(0);
4781 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004782 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4783 // This transformation is valid because we know pointers can't overflow.
4784 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4785 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4786 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004787 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004788 // If the base pointers are different, but the indices are the same, just
4789 // compare the base pointer.
4790 if (PtrBase != GEPRHS->getOperand(0)) {
4791 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004792 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004793 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004794 if (IndicesTheSame)
4795 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4796 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4797 IndicesTheSame = false;
4798 break;
4799 }
4800
4801 // If all indices are the same, just compare the base pointers.
4802 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004803 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4804 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004805
4806 // Otherwise, the base pointers are different and the indices are
4807 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004808 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004809 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004810
Chris Lattnere9d782b2005-01-13 22:25:21 +00004811 // If one of the GEPs has all zero indices, recurse.
4812 bool AllZeros = true;
4813 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4814 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4815 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4816 AllZeros = false;
4817 break;
4818 }
4819 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004820 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4821 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004822
4823 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004824 AllZeros = true;
4825 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4826 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4827 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4828 AllZeros = false;
4829 break;
4830 }
4831 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004832 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004833
Chris Lattner4401c9c2005-01-14 00:20:05 +00004834 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4835 // If the GEPs only differ by one index, compare it.
4836 unsigned NumDifferences = 0; // Keep track of # differences.
4837 unsigned DiffOperand = 0; // The operand that differs.
4838 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4839 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004840 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4841 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004842 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004843 NumDifferences = 2;
4844 break;
4845 } else {
4846 if (NumDifferences++) break;
4847 DiffOperand = i;
4848 }
4849 }
4850
4851 if (NumDifferences == 0) // SAME GEP?
4852 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004853 ConstantInt::get(Type::Int1Ty,
4854 isTrueWhenEqual(Cond)));
4855
Chris Lattner4401c9c2005-01-14 00:20:05 +00004856 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004857 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4858 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004859 // Make sure we do a signed comparison here.
4860 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004861 }
4862 }
4863
Reid Spencere4d87aa2006-12-23 06:05:41 +00004864 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004865 // the result to fold to a constant!
4866 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4867 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4868 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4869 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4870 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004871 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004872 }
4873 }
4874 return 0;
4875}
4876
Reid Spencere4d87aa2006-12-23 06:05:41 +00004877Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4878 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004879 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004880
Chris Lattner58e97462007-01-14 19:42:17 +00004881 // Fold trivial predicates.
4882 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4883 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4884 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4885 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4886
4887 // Simplify 'fcmp pred X, X'
4888 if (Op0 == Op1) {
4889 switch (I.getPredicate()) {
4890 default: assert(0 && "Unknown predicate!");
4891 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4892 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4893 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4894 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4895 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4896 case FCmpInst::FCMP_OLT: // True if ordered and less than
4897 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4898 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4899
4900 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4901 case FCmpInst::FCMP_ULT: // True if unordered or less than
4902 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4903 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4904 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4905 I.setPredicate(FCmpInst::FCMP_UNO);
4906 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4907 return &I;
4908
4909 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4910 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4911 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4912 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4913 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4914 I.setPredicate(FCmpInst::FCMP_ORD);
4915 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4916 return &I;
4917 }
4918 }
4919
Reid Spencere4d87aa2006-12-23 06:05:41 +00004920 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004921 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004922
Reid Spencere4d87aa2006-12-23 06:05:41 +00004923 // Handle fcmp with constant RHS
4924 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4925 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4926 switch (LHSI->getOpcode()) {
4927 case Instruction::PHI:
4928 if (Instruction *NV = FoldOpIntoPhi(I))
4929 return NV;
4930 break;
4931 case Instruction::Select:
4932 // If either operand of the select is a constant, we can fold the
4933 // comparison into the select arms, which will cause one to be
4934 // constant folded and the select turned into a bitwise or.
4935 Value *Op1 = 0, *Op2 = 0;
4936 if (LHSI->hasOneUse()) {
4937 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4938 // Fold the known value into the constant operand.
4939 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4940 // Insert a new FCmp of the other select operand.
4941 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4942 LHSI->getOperand(2), RHSC,
4943 I.getName()), I);
4944 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4945 // Fold the known value into the constant operand.
4946 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4947 // Insert a new FCmp of the other select operand.
4948 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4949 LHSI->getOperand(1), RHSC,
4950 I.getName()), I);
4951 }
4952 }
4953
4954 if (Op1)
4955 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4956 break;
4957 }
4958 }
4959
4960 return Changed ? &I : 0;
4961}
4962
4963Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4964 bool Changed = SimplifyCompare(I);
4965 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4966 const Type *Ty = Op0->getType();
4967
4968 // icmp X, X
4969 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004970 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4971 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004972
4973 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004974 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004975
Reid Spencere4d87aa2006-12-23 06:05:41 +00004976 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004977 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004978 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4979 isa<ConstantPointerNull>(Op0)) &&
4980 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004981 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004982 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4983 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004984
Reid Spencere4d87aa2006-12-23 06:05:41 +00004985 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004986 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004987 switch (I.getPredicate()) {
4988 default: assert(0 && "Invalid icmp instruction!");
4989 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004990 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004991 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004992 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004993 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004994 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004995 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004996
Reid Spencere4d87aa2006-12-23 06:05:41 +00004997 case ICmpInst::ICMP_UGT:
4998 case ICmpInst::ICMP_SGT:
4999 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00005000 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005001 case ICmpInst::ICMP_ULT:
5002 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00005003 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5004 InsertNewInstBefore(Not, I);
5005 return BinaryOperator::createAnd(Not, Op1);
5006 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005007 case ICmpInst::ICMP_UGE:
5008 case ICmpInst::ICMP_SGE:
5009 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00005010 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00005011 case ICmpInst::ICMP_ULE:
5012 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00005013 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5014 InsertNewInstBefore(Not, I);
5015 return BinaryOperator::createOr(Not, Op1);
5016 }
5017 }
Chris Lattner8b170942002-08-09 23:47:40 +00005018 }
5019
Chris Lattner2be51ae2004-06-09 04:24:29 +00005020 // See if we are doing a comparison between a constant and an instruction that
5021 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00005022 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00005023 Value *A, *B;
5024
Chris Lattnerb6566012008-01-05 01:18:20 +00005025 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5026 if (I.isEquality() && CI->isNullValue() &&
5027 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5028 // (icmp cond A B) if cond is equality
5029 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005030 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005031
Reid Spencere4d87aa2006-12-23 06:05:41 +00005032 switch (I.getPredicate()) {
5033 default: break;
5034 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5035 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005036 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005037 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5038 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5039 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5040 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005041 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5042 if (CI->isMinValue(true))
5043 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5044 ConstantInt::getAllOnesValue(Op0->getType()));
5045
Reid Spencere4d87aa2006-12-23 06:05:41 +00005046 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005047
Reid Spencere4d87aa2006-12-23 06:05:41 +00005048 case ICmpInst::ICMP_SLT:
5049 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005050 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005051 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5052 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5053 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5054 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5055 break;
5056
5057 case ICmpInst::ICMP_UGT:
5058 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005059 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005060 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5061 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5062 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5063 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00005064
5065 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5066 if (CI->isMaxValue(true))
5067 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5068 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005069 break;
5070
5071 case ICmpInst::ICMP_SGT:
5072 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005073 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005074 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5075 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5076 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5077 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5078 break;
5079
5080 case ICmpInst::ICMP_ULE:
5081 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005082 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005083 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5084 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5085 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5086 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5087 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005088
Reid Spencere4d87aa2006-12-23 06:05:41 +00005089 case ICmpInst::ICMP_SLE:
5090 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005091 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005092 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5093 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5094 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5095 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5096 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005097
Reid Spencere4d87aa2006-12-23 06:05:41 +00005098 case ICmpInst::ICMP_UGE:
5099 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005100 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005101 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5102 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5103 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5104 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5105 break;
5106
5107 case ICmpInst::ICMP_SGE:
5108 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005109 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005110 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5111 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5112 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5113 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5114 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005115 }
5116
Reid Spencere4d87aa2006-12-23 06:05:41 +00005117 // If we still have a icmp le or icmp ge instruction, turn it into the
5118 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005119 // already been handled above, this requires little checking.
5120 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005121 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005122 default: break;
5123 case ICmpInst::ICMP_ULE:
5124 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5125 case ICmpInst::ICMP_SLE:
5126 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5127 case ICmpInst::ICMP_UGE:
5128 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5129 case ICmpInst::ICMP_SGE:
5130 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005131 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005132
5133 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005134 // in the input. If this comparison is a normal comparison, it demands all
5135 // bits, if it is a sign bit comparison, it only demands the sign bit.
5136
5137 bool UnusedBit;
5138 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5139
Reid Spencer0460fb32007-03-22 20:36:03 +00005140 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5141 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005142 if (SimplifyDemandedBits(Op0,
5143 isSignBit ? APInt::getSignBit(BitWidth)
5144 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005145 KnownZero, KnownOne, 0))
5146 return &I;
5147
5148 // Given the known and unknown bits, compute a range that the LHS could be
5149 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005150 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005151 // Compute the Min, Max and RHS values based on the known bits. For the
5152 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005153 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5154 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005155 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005156 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5157 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005158 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005159 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5160 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005161 }
5162 switch (I.getPredicate()) { // LE/GE have been folded already.
5163 default: assert(0 && "Unknown icmp opcode!");
5164 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005165 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005166 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005167 break;
5168 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005169 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005170 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005171 break;
5172 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005173 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005174 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005175 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005176 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005177 break;
5178 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005179 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005180 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005181 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005182 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005183 break;
5184 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005185 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005186 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005187 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005188 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005189 break;
5190 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005191 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005192 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005193 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005194 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005195 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005196 }
5197 }
5198
Reid Spencere4d87aa2006-12-23 06:05:41 +00005199 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005200 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005201 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005202 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005203 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5204 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005205 }
5206
Chris Lattner01deb9d2007-04-03 17:43:25 +00005207 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005208 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5209 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5210 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005211 case Instruction::GetElementPtr:
5212 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005213 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005214 bool isAllZeros = true;
5215 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5216 if (!isa<Constant>(LHSI->getOperand(i)) ||
5217 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5218 isAllZeros = false;
5219 break;
5220 }
5221 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005222 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005223 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5224 }
5225 break;
5226
Chris Lattner6970b662005-04-23 15:31:55 +00005227 case Instruction::PHI:
5228 if (Instruction *NV = FoldOpIntoPhi(I))
5229 return NV;
5230 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005231 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005232 // If either operand of the select is a constant, we can fold the
5233 // comparison into the select arms, which will cause one to be
5234 // constant folded and the select turned into a bitwise or.
5235 Value *Op1 = 0, *Op2 = 0;
5236 if (LHSI->hasOneUse()) {
5237 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5238 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005239 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5240 // Insert a new ICmp of the other select operand.
5241 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5242 LHSI->getOperand(2), RHSC,
5243 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005244 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5245 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005246 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5247 // Insert a new ICmp of the other select operand.
5248 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5249 LHSI->getOperand(1), RHSC,
5250 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005251 }
5252 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005253
Chris Lattner6970b662005-04-23 15:31:55 +00005254 if (Op1)
5255 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5256 break;
5257 }
Chris Lattner4802d902007-04-06 18:57:34 +00005258 case Instruction::Malloc:
5259 // If we have (malloc != null), and if the malloc has a single use, we
5260 // can assume it is successful and remove the malloc.
5261 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5262 AddToWorkList(LHSI);
5263 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5264 !isTrueWhenEqual(I)));
5265 }
5266 break;
5267 }
Chris Lattner6970b662005-04-23 15:31:55 +00005268 }
5269
Reid Spencere4d87aa2006-12-23 06:05:41 +00005270 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005271 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005272 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005273 return NI;
5274 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005275 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5276 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005277 return NI;
5278
Reid Spencere4d87aa2006-12-23 06:05:41 +00005279 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005280 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5281 // now.
5282 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5283 if (isa<PointerType>(Op0->getType()) &&
5284 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005285 // We keep moving the cast from the left operand over to the right
5286 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005287 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005288
Chris Lattner57d86372007-01-06 01:45:59 +00005289 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5290 // so eliminate it as well.
5291 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5292 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005293
Chris Lattnerde90b762003-11-03 04:25:02 +00005294 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005295 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005296 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005297 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005298 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005299 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005300 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005301 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005302 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005303 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005304 }
Chris Lattner57d86372007-01-06 01:45:59 +00005305 }
5306
5307 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005308 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005309 // This comes up when you have code like
5310 // int X = A < B;
5311 // if (X) ...
5312 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005313 // with a constant or another cast from the same type.
5314 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005315 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005316 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005317 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005318
Chris Lattner65b72ba2006-09-18 04:22:48 +00005319 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005320 Value *A, *B, *C, *D;
5321 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5322 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5323 Value *OtherVal = A == Op1 ? B : A;
5324 return new ICmpInst(I.getPredicate(), OtherVal,
5325 Constant::getNullValue(A->getType()));
5326 }
5327
5328 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5329 // A^c1 == C^c2 --> A == C^(c1^c2)
5330 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5331 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5332 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005333 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005334 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5335 return new ICmpInst(I.getPredicate(), A,
5336 InsertNewInstBefore(Xor, I));
5337 }
5338
5339 // A^B == A^D -> B == D
5340 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5341 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5342 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5343 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5344 }
5345 }
5346
5347 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5348 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005349 // A == (A^B) -> B == 0
5350 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005351 return new ICmpInst(I.getPredicate(), OtherVal,
5352 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005353 }
5354 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005355 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005356 return new ICmpInst(I.getPredicate(), B,
5357 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005358 }
5359 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005360 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005361 return new ICmpInst(I.getPredicate(), B,
5362 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005363 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005364
Chris Lattner9c2328e2006-11-14 06:06:06 +00005365 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5366 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5367 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5368 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5369 Value *X = 0, *Y = 0, *Z = 0;
5370
5371 if (A == C) {
5372 X = B; Y = D; Z = A;
5373 } else if (A == D) {
5374 X = B; Y = C; Z = A;
5375 } else if (B == C) {
5376 X = A; Y = D; Z = B;
5377 } else if (B == D) {
5378 X = A; Y = C; Z = B;
5379 }
5380
5381 if (X) { // Build (X^Y) & Z
5382 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5383 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5384 I.setOperand(0, Op1);
5385 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5386 return &I;
5387 }
5388 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005389 }
Chris Lattner7e708292002-06-25 16:13:24 +00005390 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005391}
5392
Chris Lattner562ef782007-06-20 23:46:26 +00005393
5394/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5395/// and CmpRHS are both known to be integer constants.
5396Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5397 ConstantInt *DivRHS) {
5398 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5399 const APInt &CmpRHSV = CmpRHS->getValue();
5400
5401 // FIXME: If the operand types don't match the type of the divide
5402 // then don't attempt this transform. The code below doesn't have the
5403 // logic to deal with a signed divide and an unsigned compare (and
5404 // vice versa). This is because (x /s C1) <s C2 produces different
5405 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5406 // (x /u C1) <u C2. Simply casting the operands and result won't
5407 // work. :( The if statement below tests that condition and bails
5408 // if it finds it.
5409 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5410 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5411 return 0;
5412 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005413 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005414
5415 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5416 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5417 // C2 (CI). By solving for X we can turn this into a range check
5418 // instead of computing a divide.
5419 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5420
5421 // Determine if the product overflows by seeing if the product is
5422 // not equal to the divide. Make sure we do the same kind of divide
5423 // as in the LHS instruction that we're folding.
5424 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5425 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5426
5427 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005428 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005429
Chris Lattner1dbfd482007-06-21 18:11:19 +00005430 // Figure out the interval that is being checked. For example, a comparison
5431 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5432 // Compute this interval based on the constants involved and the signedness of
5433 // the compare/divide. This computes a half-open interval, keeping track of
5434 // whether either value in the interval overflows. After analysis each
5435 // overflow variable is set to 0 if it's corresponding bound variable is valid
5436 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5437 int LoOverflow = 0, HiOverflow = 0;
5438 ConstantInt *LoBound = 0, *HiBound = 0;
5439
5440
Chris Lattner562ef782007-06-20 23:46:26 +00005441 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005442 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005443 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005444 HiOverflow = LoOverflow = ProdOV;
5445 if (!HiOverflow)
5446 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005447 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005448 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005449 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005450 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5451 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005452 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005453 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5454 HiOverflow = LoOverflow = ProdOV;
5455 if (!HiOverflow)
5456 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005457 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005458 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005459 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5460 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005461 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005462 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005463 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005464 }
Dan Gohman76491272008-02-13 22:09:18 +00005465 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005466 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005467 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005468 LoBound = AddOne(DivRHS);
5469 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005470 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5471 HiOverflow = 1; // [INTMIN+1, overflow)
5472 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5473 }
Dan Gohman76491272008-02-13 22:09:18 +00005474 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005475 // e.g. X/-5 op 3 --> [-19, -14)
5476 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005477 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005478 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005479 HiBound = AddOne(Prod);
5480 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005481 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005482 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005483 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005484 HiBound = Subtract(Prod, DivRHS);
5485 }
5486
Chris Lattner1dbfd482007-06-21 18:11:19 +00005487 // Dividing by a negative swaps the condition. LT <-> GT
5488 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005489 }
5490
5491 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005492 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005493 default: assert(0 && "Unhandled icmp opcode!");
5494 case ICmpInst::ICMP_EQ:
5495 if (LoOverflow && HiOverflow)
5496 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5497 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005498 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005499 ICmpInst::ICMP_UGE, X, LoBound);
5500 else if (LoOverflow)
5501 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5502 ICmpInst::ICMP_ULT, X, HiBound);
5503 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005504 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005505 case ICmpInst::ICMP_NE:
5506 if (LoOverflow && HiOverflow)
5507 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5508 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005509 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005510 ICmpInst::ICMP_ULT, X, LoBound);
5511 else if (LoOverflow)
5512 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5513 ICmpInst::ICMP_UGE, X, HiBound);
5514 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005515 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005516 case ICmpInst::ICMP_ULT:
5517 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005518 if (LoOverflow == +1) // Low bound is greater than input range.
5519 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5520 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005521 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005522 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005523 case ICmpInst::ICMP_UGT:
5524 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005525 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005526 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005527 else if (HiOverflow == -1) // High bound less than input range.
5528 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5529 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005530 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5531 else
5532 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5533 }
5534}
5535
5536
Chris Lattner01deb9d2007-04-03 17:43:25 +00005537/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5538///
5539Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5540 Instruction *LHSI,
5541 ConstantInt *RHS) {
5542 const APInt &RHSV = RHS->getValue();
5543
5544 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005545 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005546 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5547 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5548 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005549 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5550 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005551 Value *CompareVal = LHSI->getOperand(0);
5552
5553 // If the sign bit of the XorCST is not set, there is no change to
5554 // the operation, just stop using the Xor.
5555 if (!XorCST->getValue().isNegative()) {
5556 ICI.setOperand(0, CompareVal);
5557 AddToWorkList(LHSI);
5558 return &ICI;
5559 }
5560
5561 // Was the old condition true if the operand is positive?
5562 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5563
5564 // If so, the new one isn't.
5565 isTrueIfPositive ^= true;
5566
5567 if (isTrueIfPositive)
5568 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5569 else
5570 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5571 }
5572 }
5573 break;
5574 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5575 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5576 LHSI->getOperand(0)->hasOneUse()) {
5577 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5578
5579 // If the LHS is an AND of a truncating cast, we can widen the
5580 // and/compare to be the input width without changing the value
5581 // produced, eliminating a cast.
5582 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5583 // We can do this transformation if either the AND constant does not
5584 // have its sign bit set or if it is an equality comparison.
5585 // Extending a relational comparison when we're checking the sign
5586 // bit would not work.
5587 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005588 (ICI.isEquality() ||
5589 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005590 uint32_t BitWidth =
5591 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5592 APInt NewCST = AndCST->getValue();
5593 NewCST.zext(BitWidth);
5594 APInt NewCI = RHSV;
5595 NewCI.zext(BitWidth);
5596 Instruction *NewAnd =
5597 BinaryOperator::createAnd(Cast->getOperand(0),
5598 ConstantInt::get(NewCST),LHSI->getName());
5599 InsertNewInstBefore(NewAnd, ICI);
5600 return new ICmpInst(ICI.getPredicate(), NewAnd,
5601 ConstantInt::get(NewCI));
5602 }
5603 }
5604
5605 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5606 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5607 // happens a LOT in code produced by the C front-end, for bitfield
5608 // access.
5609 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5610 if (Shift && !Shift->isShift())
5611 Shift = 0;
5612
5613 ConstantInt *ShAmt;
5614 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5615 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5616 const Type *AndTy = AndCST->getType(); // Type of the and.
5617
5618 // We can fold this as long as we can't shift unknown bits
5619 // into the mask. This can only happen with signed shift
5620 // rights, as they sign-extend.
5621 if (ShAmt) {
5622 bool CanFold = Shift->isLogicalShift();
5623 if (!CanFold) {
5624 // To test for the bad case of the signed shr, see if any
5625 // of the bits shifted in could be tested after the mask.
5626 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5627 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5628
5629 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5630 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5631 AndCST->getValue()) == 0)
5632 CanFold = true;
5633 }
5634
5635 if (CanFold) {
5636 Constant *NewCst;
5637 if (Shift->getOpcode() == Instruction::Shl)
5638 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5639 else
5640 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5641
5642 // Check to see if we are shifting out any of the bits being
5643 // compared.
5644 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5645 // If we shifted bits out, the fold is not going to work out.
5646 // As a special case, check to see if this means that the
5647 // result is always true or false now.
5648 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5649 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5650 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5651 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5652 } else {
5653 ICI.setOperand(1, NewCst);
5654 Constant *NewAndCST;
5655 if (Shift->getOpcode() == Instruction::Shl)
5656 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5657 else
5658 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5659 LHSI->setOperand(1, NewAndCST);
5660 LHSI->setOperand(0, Shift->getOperand(0));
5661 AddToWorkList(Shift); // Shift is dead.
5662 AddUsesToWorkList(ICI);
5663 return &ICI;
5664 }
5665 }
5666 }
5667
5668 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5669 // preferable because it allows the C<<Y expression to be hoisted out
5670 // of a loop if Y is invariant and X is not.
5671 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5672 ICI.isEquality() && !Shift->isArithmeticShift() &&
5673 isa<Instruction>(Shift->getOperand(0))) {
5674 // Compute C << Y.
5675 Value *NS;
5676 if (Shift->getOpcode() == Instruction::LShr) {
5677 NS = BinaryOperator::createShl(AndCST,
5678 Shift->getOperand(1), "tmp");
5679 } else {
5680 // Insert a logical shift.
5681 NS = BinaryOperator::createLShr(AndCST,
5682 Shift->getOperand(1), "tmp");
5683 }
5684 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5685
5686 // Compute X & (C << Y).
5687 Instruction *NewAnd =
5688 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5689 InsertNewInstBefore(NewAnd, ICI);
5690
5691 ICI.setOperand(0, NewAnd);
5692 return &ICI;
5693 }
5694 }
5695 break;
5696
Chris Lattnera0141b92007-07-15 20:42:37 +00005697 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5698 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5699 if (!ShAmt) break;
5700
5701 uint32_t TypeBits = RHSV.getBitWidth();
5702
5703 // Check that the shift amount is in range. If not, don't perform
5704 // undefined shifts. When the shift is visited it will be
5705 // simplified.
5706 if (ShAmt->uge(TypeBits))
5707 break;
5708
5709 if (ICI.isEquality()) {
5710 // If we are comparing against bits always shifted out, the
5711 // comparison cannot succeed.
5712 Constant *Comp =
5713 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5714 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5715 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5716 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5717 return ReplaceInstUsesWith(ICI, Cst);
5718 }
5719
5720 if (LHSI->hasOneUse()) {
5721 // Otherwise strength reduce the shift into an and.
5722 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5723 Constant *Mask =
5724 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005725
Chris Lattnera0141b92007-07-15 20:42:37 +00005726 Instruction *AndI =
5727 BinaryOperator::createAnd(LHSI->getOperand(0),
5728 Mask, LHSI->getName()+".mask");
5729 Value *And = InsertNewInstBefore(AndI, ICI);
5730 return new ICmpInst(ICI.getPredicate(), And,
5731 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005732 }
5733 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005734
5735 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5736 bool TrueIfSigned = false;
5737 if (LHSI->hasOneUse() &&
5738 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5739 // (X << 31) <s 0 --> (X&1) != 0
5740 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5741 (TypeBits-ShAmt->getZExtValue()-1));
5742 Instruction *AndI =
5743 BinaryOperator::createAnd(LHSI->getOperand(0),
5744 Mask, LHSI->getName()+".mask");
5745 Value *And = InsertNewInstBefore(AndI, ICI);
5746
5747 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5748 And, Constant::getNullValue(And->getType()));
5749 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005750 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005751 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005752
5753 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005754 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005755 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00005756 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005757 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005758
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005759 // Check that the shift amount is in range. If not, don't perform
5760 // undefined shifts. When the shift is visited it will be
5761 // simplified.
5762 uint32_t TypeBits = RHSV.getBitWidth();
5763 if (ShAmt->uge(TypeBits))
5764 break;
5765
5766 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00005767
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005768 // If we are comparing against bits always shifted out, the
5769 // comparison cannot succeed.
5770 APInt Comp = RHSV << ShAmtVal;
5771 if (LHSI->getOpcode() == Instruction::LShr)
5772 Comp = Comp.lshr(ShAmtVal);
5773 else
5774 Comp = Comp.ashr(ShAmtVal);
5775
5776 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5777 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5778 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5779 return ReplaceInstUsesWith(ICI, Cst);
5780 }
5781
5782 // Otherwise, check to see if the bits shifted out are known to be zero.
5783 // If so, we can compare against the unshifted value:
5784 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
5785 if (MaskedValueIsZero(LHSI->getOperand(0),
5786 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5787 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5788 ConstantExpr::getShl(RHS, ShAmt));
5789 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005790
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005791 if (LHSI->hasOneUse() || RHSV == 0) {
5792 // Otherwise strength reduce the shift into an and.
5793 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5794 Constant *Mask = ConstantInt::get(Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00005795
Chris Lattner41dc0fc2008-03-21 05:19:58 +00005796 Instruction *AndI =
5797 BinaryOperator::createAnd(LHSI->getOperand(0),
5798 Mask, LHSI->getName()+".mask");
5799 Value *And = InsertNewInstBefore(AndI, ICI);
5800 return new ICmpInst(ICI.getPredicate(), And,
5801 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005802 }
5803 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005804 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005805
5806 case Instruction::SDiv:
5807 case Instruction::UDiv:
5808 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5809 // Fold this div into the comparison, producing a range check.
5810 // Determine, based on the divide type, what the range is being
5811 // checked. If there is an overflow on the low or high side, remember
5812 // it, otherwise compute the range [low, hi) bounding the new value.
5813 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005814 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5815 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5816 DivRHS))
5817 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005818 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005819
5820 case Instruction::Add:
5821 // Fold: icmp pred (add, X, C1), C2
5822
5823 if (!ICI.isEquality()) {
5824 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5825 if (!LHSC) break;
5826 const APInt &LHSV = LHSC->getValue();
5827
5828 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5829 .subtract(LHSV);
5830
5831 if (ICI.isSignedPredicate()) {
5832 if (CR.getLower().isSignBit()) {
5833 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5834 ConstantInt::get(CR.getUpper()));
5835 } else if (CR.getUpper().isSignBit()) {
5836 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5837 ConstantInt::get(CR.getLower()));
5838 }
5839 } else {
5840 if (CR.getLower().isMinValue()) {
5841 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5842 ConstantInt::get(CR.getUpper()));
5843 } else if (CR.getUpper().isMinValue()) {
5844 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5845 ConstantInt::get(CR.getLower()));
5846 }
5847 }
5848 }
5849 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005850 }
5851
5852 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5853 if (ICI.isEquality()) {
5854 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5855
5856 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5857 // the second operand is a constant, simplify a bit.
5858 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5859 switch (BO->getOpcode()) {
5860 case Instruction::SRem:
5861 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5862 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5863 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5864 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5865 Instruction *NewRem =
5866 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5867 BO->getName());
5868 InsertNewInstBefore(NewRem, ICI);
5869 return new ICmpInst(ICI.getPredicate(), NewRem,
5870 Constant::getNullValue(BO->getType()));
5871 }
5872 }
5873 break;
5874 case Instruction::Add:
5875 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5876 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5877 if (BO->hasOneUse())
5878 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5879 Subtract(RHS, BOp1C));
5880 } else if (RHSV == 0) {
5881 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5882 // efficiently invertible, or if the add has just this one use.
5883 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5884
5885 if (Value *NegVal = dyn_castNegVal(BOp1))
5886 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5887 else if (Value *NegVal = dyn_castNegVal(BOp0))
5888 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5889 else if (BO->hasOneUse()) {
5890 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5891 InsertNewInstBefore(Neg, ICI);
5892 Neg->takeName(BO);
5893 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5894 }
5895 }
5896 break;
5897 case Instruction::Xor:
5898 // For the xor case, we can xor two constants together, eliminating
5899 // the explicit xor.
5900 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5901 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5902 ConstantExpr::getXor(RHS, BOC));
5903
5904 // FALLTHROUGH
5905 case Instruction::Sub:
5906 // Replace (([sub|xor] A, B) != 0) with (A != B)
5907 if (RHSV == 0)
5908 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5909 BO->getOperand(1));
5910 break;
5911
5912 case Instruction::Or:
5913 // If bits are being or'd in that are not present in the constant we
5914 // are comparing against, then the comparison could never succeed!
5915 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5916 Constant *NotCI = ConstantExpr::getNot(RHS);
5917 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5918 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5919 isICMP_NE));
5920 }
5921 break;
5922
5923 case Instruction::And:
5924 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5925 // If bits are being compared against that are and'd out, then the
5926 // comparison can never succeed!
5927 if ((RHSV & ~BOC->getValue()) != 0)
5928 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5929 isICMP_NE));
5930
5931 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5932 if (RHS == BOC && RHSV.isPowerOf2())
5933 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5934 ICmpInst::ICMP_NE, LHSI,
5935 Constant::getNullValue(RHS->getType()));
5936
5937 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5938 if (isSignBit(BOC)) {
5939 Value *X = BO->getOperand(0);
5940 Constant *Zero = Constant::getNullValue(X->getType());
5941 ICmpInst::Predicate pred = isICMP_NE ?
5942 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5943 return new ICmpInst(pred, X, Zero);
5944 }
5945
5946 // ((X & ~7) == 0) --> X < 8
5947 if (RHSV == 0 && isHighOnes(BOC)) {
5948 Value *X = BO->getOperand(0);
5949 Constant *NegX = ConstantExpr::getNeg(BOC);
5950 ICmpInst::Predicate pred = isICMP_NE ?
5951 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5952 return new ICmpInst(pred, X, NegX);
5953 }
5954 }
5955 default: break;
5956 }
5957 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5958 // Handle icmp {eq|ne} <intrinsic>, intcst.
5959 if (II->getIntrinsicID() == Intrinsic::bswap) {
5960 AddToWorkList(II);
5961 ICI.setOperand(0, II->getOperand(1));
5962 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5963 return &ICI;
5964 }
5965 }
5966 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005967 // If the LHS is a cast from an integral value of the same size,
5968 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005969 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5970 Value *CastOp = Cast->getOperand(0);
5971 const Type *SrcTy = CastOp->getType();
5972 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5973 if (SrcTy->isInteger() &&
5974 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5975 // If this is an unsigned comparison, try to make the comparison use
5976 // smaller constant values.
5977 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5978 // X u< 128 => X s> -1
5979 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5980 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5981 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5982 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5983 // X u> 127 => X s< 0
5984 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5985 Constant::getNullValue(SrcTy));
5986 }
5987 }
5988 }
5989 }
5990 return 0;
5991}
5992
5993/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5994/// We only handle extending casts so far.
5995///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005996Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5997 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005998 Value *LHSCIOp = LHSCI->getOperand(0);
5999 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006000 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006001 Value *RHSCIOp;
6002
Chris Lattner8c756c12007-05-05 22:41:33 +00006003 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6004 // integer type is the same size as the pointer type.
6005 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6006 getTargetData().getPointerSizeInBits() ==
6007 cast<IntegerType>(DestTy)->getBitWidth()) {
6008 Value *RHSOp = 0;
6009 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00006010 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00006011 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6012 RHSOp = RHSC->getOperand(0);
6013 // If the pointer types don't match, insert a bitcast.
6014 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00006015 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00006016 }
6017
6018 if (RHSOp)
6019 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6020 }
6021
6022 // The code below only handles extension cast instructions, so far.
6023 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006024 if (LHSCI->getOpcode() != Instruction::ZExt &&
6025 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00006026 return 0;
6027
Reid Spencere4d87aa2006-12-23 06:05:41 +00006028 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6029 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00006030
Reid Spencere4d87aa2006-12-23 06:05:41 +00006031 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00006032 // Not an extension from the same type?
6033 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006034 if (RHSCIOp->getType() != LHSCIOp->getType())
6035 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00006036
Nick Lewycky4189a532008-01-28 03:48:02 +00006037 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00006038 // and the other is a zext), then we can't handle this.
6039 if (CI->getOpcode() != LHSCI->getOpcode())
6040 return 0;
6041
Nick Lewycky4189a532008-01-28 03:48:02 +00006042 // Deal with equality cases early.
6043 if (ICI.isEquality())
6044 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6045
6046 // A signed comparison of sign extended values simplifies into a
6047 // signed comparison.
6048 if (isSignedCmp && isSignedExt)
6049 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6050
6051 // The other three cases all fold into an unsigned comparison.
6052 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00006053 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006054
Reid Spencere4d87aa2006-12-23 06:05:41 +00006055 // If we aren't dealing with a constant on the RHS, exit early
6056 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6057 if (!CI)
6058 return 0;
6059
6060 // Compute the constant that would happen if we truncated to SrcTy then
6061 // reextended to DestTy.
6062 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6063 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6064
6065 // If the re-extended constant didn't change...
6066 if (Res2 == CI) {
6067 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6068 // For example, we might have:
6069 // %A = sext short %X to uint
6070 // %B = icmp ugt uint %A, 1330
6071 // It is incorrect to transform this into
6072 // %B = icmp ugt short %X, 1330
6073 // because %A may have negative value.
6074 //
6075 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6076 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00006077 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00006078 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6079 else
6080 return 0;
6081 }
6082
6083 // The re-extended constant changed so the constant cannot be represented
6084 // in the shorter type. Consequently, we cannot emit a simple comparison.
6085
6086 // First, handle some easy cases. We know the result cannot be equal at this
6087 // point so handle the ICI.isEquality() cases
6088 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006089 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006090 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006091 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006092
6093 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6094 // should have been folded away previously and not enter in here.
6095 Value *Result;
6096 if (isSignedCmp) {
6097 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00006098 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006099 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00006100 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006101 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00006102 } else {
6103 // We're performing an unsigned comparison.
6104 if (isSignedExt) {
6105 // We're performing an unsigned comp with a sign extended value.
6106 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006107 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006108 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6109 NegOne, ICI.getName()), ICI);
6110 } else {
6111 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006112 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006113 }
6114 }
6115
6116 // Finally, return the value computed.
6117 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6118 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6119 return ReplaceInstUsesWith(ICI, Result);
6120 } else {
6121 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6122 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6123 "ICmp should be folded!");
6124 if (Constant *CI = dyn_cast<Constant>(Result))
6125 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6126 else
6127 return BinaryOperator::createNot(Result);
6128 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006129}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006130
Reid Spencer832254e2007-02-02 02:16:23 +00006131Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6132 return commonShiftTransforms(I);
6133}
6134
6135Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6136 return commonShiftTransforms(I);
6137}
6138
6139Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006140 if (Instruction *R = commonShiftTransforms(I))
6141 return R;
6142
6143 Value *Op0 = I.getOperand(0);
6144
6145 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6146 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6147 if (CSI->isAllOnesValue())
6148 return ReplaceInstUsesWith(I, CSI);
6149
6150 // See if we can turn a signed shr into an unsigned shr.
6151 if (MaskedValueIsZero(Op0,
6152 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6153 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6154
6155 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006156}
6157
6158Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6159 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006160 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006161
6162 // shl X, 0 == X and shr X, 0 == X
6163 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006164 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006165 Op0 == Constant::getNullValue(Op0->getType()))
6166 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006167
Reid Spencere4d87aa2006-12-23 06:05:41 +00006168 if (isa<UndefValue>(Op0)) {
6169 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006170 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006171 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006172 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6173 }
6174 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006175 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6176 return ReplaceInstUsesWith(I, Op0);
6177 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006178 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006179 }
6180
Chris Lattner2eefe512004-04-09 19:05:30 +00006181 // Try to fold constant and into select arguments.
6182 if (isa<Constant>(Op0))
6183 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006184 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006185 return R;
6186
Reid Spencerb83eb642006-10-20 07:07:24 +00006187 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006188 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6189 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006190 return 0;
6191}
6192
Reid Spencerb83eb642006-10-20 07:07:24 +00006193Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006194 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006195 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006196
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006197 // See if we can simplify any instructions used by the instruction whose sole
6198 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006199 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6200 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6201 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006202 KnownZero, KnownOne))
6203 return &I;
6204
Chris Lattner4d5542c2006-01-06 07:12:35 +00006205 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6206 // of a signed value.
6207 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006208 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006209 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006210 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6211 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006212 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006213 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006214 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006215 }
6216
6217 // ((X*C1) << C2) == (X * (C1 << C2))
6218 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6219 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6220 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6221 return BinaryOperator::createMul(BO->getOperand(0),
6222 ConstantExpr::getShl(BOOp, Op1));
6223
6224 // Try to fold constant and into select arguments.
6225 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6226 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6227 return R;
6228 if (isa<PHINode>(Op0))
6229 if (Instruction *NV = FoldOpIntoPhi(I))
6230 return NV;
6231
Chris Lattner8999dd32007-12-22 09:07:47 +00006232 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6233 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6234 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6235 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6236 // place. Don't try to do this transformation in this case. Also, we
6237 // require that the input operand is a shift-by-constant so that we have
6238 // confidence that the shifts will get folded together. We could do this
6239 // xform in more cases, but it is unlikely to be profitable.
6240 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6241 isa<ConstantInt>(TrOp->getOperand(1))) {
6242 // Okay, we'll do this xform. Make the shift of shift.
6243 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6244 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6245 I.getName());
6246 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6247
6248 // For logical shifts, the truncation has the effect of making the high
6249 // part of the register be zeros. Emulate this by inserting an AND to
6250 // clear the top bits as needed. This 'and' will usually be zapped by
6251 // other xforms later if dead.
6252 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6253 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6254 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6255
6256 // The mask we constructed says what the trunc would do if occurring
6257 // between the shifts. We want to know the effect *after* the second
6258 // shift. We know that it is a logical shift by a constant, so adjust the
6259 // mask as appropriate.
6260 if (I.getOpcode() == Instruction::Shl)
6261 MaskV <<= Op1->getZExtValue();
6262 else {
6263 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6264 MaskV = MaskV.lshr(Op1->getZExtValue());
6265 }
6266
6267 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6268 TI->getName());
6269 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6270
6271 // Return the value truncated to the interesting size.
6272 return new TruncInst(And, I.getType());
6273 }
6274 }
6275
Chris Lattner4d5542c2006-01-06 07:12:35 +00006276 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006277 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6278 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6279 Value *V1, *V2;
6280 ConstantInt *CC;
6281 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006282 default: break;
6283 case Instruction::Add:
6284 case Instruction::And:
6285 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006286 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006287 // These operators commute.
6288 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006289 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6290 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006291 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006292 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006293 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006294 Op0BO->getName());
6295 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006296 Instruction *X =
6297 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6298 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006299 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006300 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006301 return BinaryOperator::createAnd(X, ConstantInt::get(
6302 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006303 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006304
Chris Lattner150f12a2005-09-18 06:30:59 +00006305 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006306 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006307 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006308 match(Op0BOOp1,
6309 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006310 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6311 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006312 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006313 Op0BO->getOperand(0), Op1,
6314 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006315 InsertNewInstBefore(YS, I); // (Y << C)
6316 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006317 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006318 V1->getName()+".mask");
6319 InsertNewInstBefore(XM, I); // X & (CC << C)
6320
6321 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6322 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006323 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006324
Reid Spencera07cb7d2007-02-02 14:41:37 +00006325 // FALL THROUGH.
6326 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006327 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006328 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6329 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006330 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006331 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006332 Op0BO->getOperand(1), Op1,
6333 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006334 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006335 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006336 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006337 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006338 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006339 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006340 return BinaryOperator::createAnd(X, ConstantInt::get(
6341 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006342 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006343
Chris Lattner13d4ab42006-05-31 21:14:00 +00006344 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006345 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6346 match(Op0BO->getOperand(0),
6347 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006348 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006349 cast<BinaryOperator>(Op0BO->getOperand(0))
6350 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006351 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006352 Op0BO->getOperand(1), Op1,
6353 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006354 InsertNewInstBefore(YS, I); // (Y << C)
6355 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006356 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006357 V1->getName()+".mask");
6358 InsertNewInstBefore(XM, I); // X & (CC << C)
6359
Chris Lattner13d4ab42006-05-31 21:14:00 +00006360 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006361 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006362
Chris Lattner11021cb2005-09-18 05:12:10 +00006363 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006364 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006365 }
6366
6367
6368 // If the operand is an bitwise operator with a constant RHS, and the
6369 // shift is the only use, we can pull it out of the shift.
6370 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6371 bool isValid = true; // Valid only for And, Or, Xor
6372 bool highBitSet = false; // Transform if high bit of constant set?
6373
6374 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006375 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006376 case Instruction::Add:
6377 isValid = isLeftShift;
6378 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006379 case Instruction::Or:
6380 case Instruction::Xor:
6381 highBitSet = false;
6382 break;
6383 case Instruction::And:
6384 highBitSet = true;
6385 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006386 }
6387
6388 // If this is a signed shift right, and the high bit is modified
6389 // by the logical operation, do not perform the transformation.
6390 // The highBitSet boolean indicates the value of the high bit of
6391 // the constant which would cause it to be modified for this
6392 // operation.
6393 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006394 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006395 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006396
6397 if (isValid) {
6398 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6399
6400 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006401 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006402 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006403 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006404
6405 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6406 NewRHS);
6407 }
6408 }
6409 }
6410 }
6411
Chris Lattnerad0124c2006-01-06 07:52:12 +00006412 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006413 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6414 if (ShiftOp && !ShiftOp->isShift())
6415 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006416
Reid Spencerb83eb642006-10-20 07:07:24 +00006417 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006418 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006419 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6420 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006421 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6422 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6423 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006424
Zhou Sheng4351c642007-04-02 08:20:41 +00006425 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006426 if (AmtSum > TypeBits)
6427 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006428
6429 const IntegerType *Ty = cast<IntegerType>(I.getType());
6430
6431 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006432 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006433 return BinaryOperator::create(I.getOpcode(), X,
6434 ConstantInt::get(Ty, AmtSum));
6435 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6436 I.getOpcode() == Instruction::AShr) {
6437 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6438 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6439 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6440 I.getOpcode() == Instruction::LShr) {
6441 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6442 Instruction *Shift =
6443 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6444 InsertNewInstBefore(Shift, I);
6445
Zhou Shenge9e03f62007-03-28 15:02:20 +00006446 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006447 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006448 }
6449
Chris Lattnerb87056f2007-02-05 00:57:54 +00006450 // Okay, if we get here, one shift must be left, and the other shift must be
6451 // right. See if the amounts are equal.
6452 if (ShiftAmt1 == ShiftAmt2) {
6453 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6454 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006455 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006456 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006457 }
6458 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6459 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006460 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006461 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006462 }
6463 // We can simplify ((X << C) >>s C) into a trunc + sext.
6464 // NOTE: we could do this for any C, but that would make 'unusual' integer
6465 // types. For now, just stick to ones well-supported by the code
6466 // generators.
6467 const Type *SExtType = 0;
6468 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006469 case 1 :
6470 case 8 :
6471 case 16 :
6472 case 32 :
6473 case 64 :
6474 case 128:
6475 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6476 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006477 default: break;
6478 }
6479 if (SExtType) {
6480 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6481 InsertNewInstBefore(NewTrunc, I);
6482 return new SExtInst(NewTrunc, Ty);
6483 }
6484 // Otherwise, we can't handle it yet.
6485 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006486 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006487
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006488 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006489 if (I.getOpcode() == Instruction::Shl) {
6490 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6491 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006492 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006493 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006494 InsertNewInstBefore(Shift, I);
6495
Reid Spencer55702aa2007-03-25 21:11:44 +00006496 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6497 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006498 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006499
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006500 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006501 if (I.getOpcode() == Instruction::LShr) {
6502 assert(ShiftOp->getOpcode() == Instruction::Shl);
6503 Instruction *Shift =
6504 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6505 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006506
Reid Spencerd5e30f02007-03-26 17:18:58 +00006507 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006508 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006509 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006510
6511 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6512 } else {
6513 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006514 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006515
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006516 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006517 if (I.getOpcode() == Instruction::Shl) {
6518 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6519 ShiftOp->getOpcode() == Instruction::AShr);
6520 Instruction *Shift =
6521 BinaryOperator::create(ShiftOp->getOpcode(), X,
6522 ConstantInt::get(Ty, ShiftDiff));
6523 InsertNewInstBefore(Shift, I);
6524
Reid Spencer55702aa2007-03-25 21:11:44 +00006525 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006526 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006527 }
6528
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006529 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006530 if (I.getOpcode() == Instruction::LShr) {
6531 assert(ShiftOp->getOpcode() == Instruction::Shl);
6532 Instruction *Shift =
6533 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6534 InsertNewInstBefore(Shift, I);
6535
Reid Spencer68d27cf2007-03-26 23:45:51 +00006536 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006537 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006538 }
6539
6540 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006541 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006542 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006543 return 0;
6544}
6545
Chris Lattnera1be5662002-05-02 17:06:02 +00006546
Chris Lattnercfd65102005-10-29 04:36:15 +00006547/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6548/// expression. If so, decompose it, returning some value X, such that Val is
6549/// X*Scale+Offset.
6550///
6551static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006552 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006553 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006554 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006555 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006556 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006557 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006558 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6559 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6560 if (I->getOpcode() == Instruction::Shl) {
6561 // This is a value scaled by '1 << the shift amt'.
6562 Scale = 1U << RHS->getZExtValue();
6563 Offset = 0;
6564 return I->getOperand(0);
6565 } else if (I->getOpcode() == Instruction::Mul) {
6566 // This value is scaled by 'RHS'.
6567 Scale = RHS->getZExtValue();
6568 Offset = 0;
6569 return I->getOperand(0);
6570 } else if (I->getOpcode() == Instruction::Add) {
6571 // We have X+C. Check to see if we really have (X*C2)+C1,
6572 // where C1 is divisible by C2.
6573 unsigned SubScale;
6574 Value *SubVal =
6575 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6576 Offset += RHS->getZExtValue();
6577 Scale = SubScale;
6578 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006579 }
6580 }
6581 }
6582
6583 // Otherwise, we can't look past this.
6584 Scale = 1;
6585 Offset = 0;
6586 return Val;
6587}
6588
6589
Chris Lattnerb3f83972005-10-24 06:03:58 +00006590/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6591/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006592Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006593 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006594 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006595
Chris Lattnerb53c2382005-10-24 06:22:12 +00006596 // Remove any uses of AI that are dead.
6597 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006598
Chris Lattnerb53c2382005-10-24 06:22:12 +00006599 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6600 Instruction *User = cast<Instruction>(*UI++);
6601 if (isInstructionTriviallyDead(User)) {
6602 while (UI != E && *UI == User)
6603 ++UI; // If this instruction uses AI more than once, don't break UI.
6604
Chris Lattnerb53c2382005-10-24 06:22:12 +00006605 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006606 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006607 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006608 }
6609 }
6610
Chris Lattnerb3f83972005-10-24 06:03:58 +00006611 // Get the type really allocated and the type casted to.
6612 const Type *AllocElTy = AI.getAllocatedType();
6613 const Type *CastElTy = PTy->getElementType();
6614 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006615
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006616 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6617 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006618 if (CastElTyAlign < AllocElTyAlign) return 0;
6619
Chris Lattner39387a52005-10-24 06:35:18 +00006620 // If the allocation has multiple uses, only promote it if we are strictly
6621 // increasing the alignment of the resultant allocation. If we keep it the
6622 // same, we open the door to infinite loops of various kinds.
6623 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6624
Duncan Sands514ab342007-11-01 20:53:16 +00006625 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6626 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006627 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006628
Chris Lattner455fcc82005-10-29 03:19:53 +00006629 // See if we can satisfy the modulus by pulling a scale out of the array
6630 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006631 unsigned ArraySizeScale;
6632 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006633 Value *NumElements = // See if the array size is a decomposable linear expr.
6634 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6635
Chris Lattner455fcc82005-10-29 03:19:53 +00006636 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6637 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006638 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6639 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006640
Chris Lattner455fcc82005-10-29 03:19:53 +00006641 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6642 Value *Amt = 0;
6643 if (Scale == 1) {
6644 Amt = NumElements;
6645 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006646 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006647 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6648 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006649 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006650 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006651 else if (Scale != 1) {
6652 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6653 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006654 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006655 }
6656
Jeff Cohen86796be2007-04-04 16:58:57 +00006657 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6658 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006659 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6660 Amt = InsertNewInstBefore(Tmp, AI);
6661 }
6662
Chris Lattnerb3f83972005-10-24 06:03:58 +00006663 AllocationInst *New;
6664 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006665 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006666 else
Chris Lattner6934a042007-02-11 01:23:03 +00006667 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006668 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006669 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006670
6671 // If the allocation has multiple uses, insert a cast and change all things
6672 // that used it to use the new cast. This will also hack on CI, but it will
6673 // die soon.
6674 if (!AI.hasOneUse()) {
6675 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006676 // New is the allocation instruction, pointer typed. AI is the original
6677 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6678 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006679 InsertNewInstBefore(NewCast, AI);
6680 AI.replaceAllUsesWith(NewCast);
6681 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006682 return ReplaceInstUsesWith(CI, New);
6683}
6684
Chris Lattner70074e02006-05-13 02:06:03 +00006685/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006686/// and return it as type Ty without inserting any new casts and without
6687/// changing the computed value. This is used by code that tries to decide
6688/// whether promoting or shrinking integer operations to wider or smaller types
6689/// will allow us to eliminate a truncate or extend.
6690///
6691/// This is a truncation operation if Ty is smaller than V->getType(), or an
6692/// extension operation if Ty is larger.
6693static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006694 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006695 // We can always evaluate constants in another type.
6696 if (isa<ConstantInt>(V))
6697 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006698
6699 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006700 if (!I) return false;
6701
6702 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006703
Chris Lattner951626b2007-08-02 06:11:14 +00006704 // If this is an extension or truncate, we can often eliminate it.
6705 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6706 // If this is a cast from the destination type, we can trivially eliminate
6707 // it, and this will remove a cast overall.
6708 if (I->getOperand(0)->getType() == Ty) {
6709 // If the first operand is itself a cast, and is eliminable, do not count
6710 // this as an eliminable cast. We would prefer to eliminate those two
6711 // casts first.
6712 if (!isa<CastInst>(I->getOperand(0)))
6713 ++NumCastsRemoved;
6714 return true;
6715 }
6716 }
6717
6718 // We can't extend or shrink something that has multiple uses: doing so would
6719 // require duplicating the instruction in general, which isn't profitable.
6720 if (!I->hasOneUse()) return false;
6721
Chris Lattner70074e02006-05-13 02:06:03 +00006722 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006723 case Instruction::Add:
6724 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006725 case Instruction::And:
6726 case Instruction::Or:
6727 case Instruction::Xor:
6728 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006729 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6730 NumCastsRemoved) &&
6731 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6732 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006733
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006734 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006735 // A multiply can be truncated by truncating its operands.
6736 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6737 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6738 NumCastsRemoved) &&
6739 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6740 NumCastsRemoved);
6741
Chris Lattner46b96052006-11-29 07:18:39 +00006742 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006743 // If we are truncating the result of this SHL, and if it's a shift of a
6744 // constant amount, we can always perform a SHL in a smaller type.
6745 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006746 uint32_t BitWidth = Ty->getBitWidth();
6747 if (BitWidth < OrigTy->getBitWidth() &&
6748 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006749 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6750 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006751 }
6752 break;
6753 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006754 // If this is a truncate of a logical shr, we can truncate it to a smaller
6755 // lshr iff we know that the bits we would otherwise be shifting in are
6756 // already zeros.
6757 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006758 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6759 uint32_t BitWidth = Ty->getBitWidth();
6760 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006761 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006762 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6763 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006764 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6765 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006766 }
6767 }
Chris Lattner46b96052006-11-29 07:18:39 +00006768 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006769 case Instruction::ZExt:
6770 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006771 case Instruction::Trunc:
6772 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006773 // can safely replace it. Note that replacing it does not reduce the number
6774 // of casts in the input.
6775 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006776 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006777
Reid Spencer3da59db2006-11-27 01:05:10 +00006778 break;
6779 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006780 // TODO: Can handle more cases here.
6781 break;
6782 }
6783
6784 return false;
6785}
6786
6787/// EvaluateInDifferentType - Given an expression that
6788/// CanEvaluateInDifferentType returns true for, actually insert the code to
6789/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006790Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006791 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006792 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006793 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006794
6795 // Otherwise, it must be an instruction.
6796 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006797 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006798 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006799 case Instruction::Add:
6800 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006801 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006802 case Instruction::And:
6803 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006804 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006805 case Instruction::AShr:
6806 case Instruction::LShr:
6807 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006808 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006809 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6810 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6811 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006812 break;
6813 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006814 case Instruction::Trunc:
6815 case Instruction::ZExt:
6816 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006817 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006818 // just return the source. There's no need to insert it because it is not
6819 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006820 if (I->getOperand(0)->getType() == Ty)
6821 return I->getOperand(0);
6822
Chris Lattner951626b2007-08-02 06:11:14 +00006823 // Otherwise, must be the same type of case, so just reinsert a new one.
6824 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6825 Ty, I->getName());
6826 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006827 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006828 // TODO: Can handle more cases here.
6829 assert(0 && "Unreachable!");
6830 break;
6831 }
6832
6833 return InsertNewInstBefore(Res, *I);
6834}
6835
Reid Spencer3da59db2006-11-27 01:05:10 +00006836/// @brief Implement the transforms common to all CastInst visitors.
6837Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006838 Value *Src = CI.getOperand(0);
6839
Dan Gohman23d9d272007-05-11 21:10:54 +00006840 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006841 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006842 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006843 if (Instruction::CastOps opc =
6844 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6845 // The first cast (CSrc) is eliminable so we need to fix up or replace
6846 // the second cast (CI). CSrc will then have a good chance of being dead.
6847 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006848 }
6849 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006850
Reid Spencer3da59db2006-11-27 01:05:10 +00006851 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006852 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6853 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6854 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006855
6856 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006857 if (isa<PHINode>(Src))
6858 if (Instruction *NV = FoldOpIntoPhi(CI))
6859 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006860
Reid Spencer3da59db2006-11-27 01:05:10 +00006861 return 0;
6862}
6863
Chris Lattnerd3e28342007-04-27 17:44:50 +00006864/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6865Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6866 Value *Src = CI.getOperand(0);
6867
Chris Lattnerd3e28342007-04-27 17:44:50 +00006868 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006869 // If casting the result of a getelementptr instruction with no offset, turn
6870 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006871 if (GEP->hasAllZeroIndices()) {
6872 // Changing the cast operand is usually not a good idea but it is safe
6873 // here because the pointer operand is being replaced with another
6874 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006875 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006876 CI.setOperand(0, GEP->getOperand(0));
6877 return &CI;
6878 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006879
6880 // If the GEP has a single use, and the base pointer is a bitcast, and the
6881 // GEP computes a constant offset, see if we can convert these three
6882 // instructions into fewer. This typically happens with unions and other
6883 // non-type-safe code.
6884 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6885 if (GEP->hasAllConstantIndices()) {
6886 // We are guaranteed to get a constant from EmitGEPOffset.
6887 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6888 int64_t Offset = OffsetV->getSExtValue();
6889
6890 // Get the base pointer input of the bitcast, and the type it points to.
6891 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6892 const Type *GEPIdxTy =
6893 cast<PointerType>(OrigBase->getType())->getElementType();
6894 if (GEPIdxTy->isSized()) {
6895 SmallVector<Value*, 8> NewIndices;
6896
Chris Lattnerc42e2262007-05-05 01:59:31 +00006897 // Start with the index over the outer type. Note that the type size
6898 // might be zero (even if the offset isn't zero) if the indexed type
6899 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006900 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006901 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006902 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006903 FirstIdx = Offset/TySize;
6904 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006905
Chris Lattnerc42e2262007-05-05 01:59:31 +00006906 // Handle silly modulus not returning values values [0..TySize).
6907 if (Offset < 0) {
6908 --FirstIdx;
6909 Offset += TySize;
6910 assert(Offset >= 0);
6911 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006912 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006913 }
6914
6915 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006916
6917 // Index into the types. If we fail, set OrigBase to null.
6918 while (Offset) {
6919 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6920 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006921 if (Offset < (int64_t)SL->getSizeInBytes()) {
6922 unsigned Elt = SL->getElementContainingOffset(Offset);
6923 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006924
Chris Lattner6b6aef82007-05-15 00:16:00 +00006925 Offset -= SL->getElementOffset(Elt);
6926 GEPIdxTy = STy->getElementType(Elt);
6927 } else {
6928 // Otherwise, we can't index into this, bail out.
6929 Offset = 0;
6930 OrigBase = 0;
6931 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006932 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6933 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006934 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006935 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6936 Offset %= EltSize;
6937 } else {
6938 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6939 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006940 GEPIdxTy = STy->getElementType();
6941 } else {
6942 // Otherwise, we can't index into this, bail out.
6943 Offset = 0;
6944 OrigBase = 0;
6945 }
6946 }
6947 if (OrigBase) {
6948 // If we were able to index down into an element, create the GEP
6949 // and bitcast the result. This eliminates one bitcast, potentially
6950 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006951 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6952 NewIndices.begin(),
6953 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006954 InsertNewInstBefore(NGEP, CI);
6955 NGEP->takeName(GEP);
6956
Chris Lattner9bc14642007-04-28 00:57:34 +00006957 if (isa<BitCastInst>(CI))
6958 return new BitCastInst(NGEP, CI.getType());
6959 assert(isa<PtrToIntInst>(CI));
6960 return new PtrToIntInst(NGEP, CI.getType());
6961 }
6962 }
6963 }
6964 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006965 }
6966
6967 return commonCastTransforms(CI);
6968}
6969
6970
6971
Chris Lattnerc739cd62007-03-03 05:27:34 +00006972/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6973/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006974/// cases.
6975/// @brief Implement the transforms common to CastInst with integer operands
6976Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6977 if (Instruction *Result = commonCastTransforms(CI))
6978 return Result;
6979
6980 Value *Src = CI.getOperand(0);
6981 const Type *SrcTy = Src->getType();
6982 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006983 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6984 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006985
Reid Spencer3da59db2006-11-27 01:05:10 +00006986 // See if we can simplify any instructions used by the LHS whose sole
6987 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006988 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6989 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006990 KnownZero, KnownOne))
6991 return &CI;
6992
6993 // If the source isn't an instruction or has more than one use then we
6994 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006995 Instruction *SrcI = dyn_cast<Instruction>(Src);
6996 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006997 return 0;
6998
Chris Lattnerc739cd62007-03-03 05:27:34 +00006999 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00007000 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00007001 if (!isa<BitCastInst>(CI) &&
7002 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00007003 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007004 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00007005 // eliminates the cast, so it is always a win. If this is a zero-extension,
7006 // we need to do an AND to maintain the clear top-part of the computation,
7007 // so we require that the input have eliminated at least one cast. If this
7008 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00007009 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00007010 bool DoXForm;
7011 switch (CI.getOpcode()) {
7012 default:
7013 // All the others use floating point so we shouldn't actually
7014 // get here because of the check above.
7015 assert(0 && "Unknown cast type");
7016 case Instruction::Trunc:
7017 DoXForm = true;
7018 break;
7019 case Instruction::ZExt:
7020 DoXForm = NumCastsRemoved >= 1;
7021 break;
7022 case Instruction::SExt:
7023 DoXForm = NumCastsRemoved >= 2;
7024 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007025 }
7026
7027 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00007028 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7029 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00007030 assert(Res->getType() == DestTy);
7031 switch (CI.getOpcode()) {
7032 default: assert(0 && "Unknown cast type!");
7033 case Instruction::Trunc:
7034 case Instruction::BitCast:
7035 // Just replace this cast with the result.
7036 return ReplaceInstUsesWith(CI, Res);
7037 case Instruction::ZExt: {
7038 // We need to emit an AND to clear the high bits.
7039 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00007040 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7041 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00007042 return BinaryOperator::createAnd(Res, C);
7043 }
7044 case Instruction::SExt:
7045 // We need to emit a cast to truncate, then a cast to sext.
7046 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00007047 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7048 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00007049 }
7050 }
7051 }
7052
7053 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7054 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7055
7056 switch (SrcI->getOpcode()) {
7057 case Instruction::Add:
7058 case Instruction::Mul:
7059 case Instruction::And:
7060 case Instruction::Or:
7061 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00007062 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00007063 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7064 // Don't insert two casts if they cannot be eliminated. We allow
7065 // two casts to be inserted if the sizes are the same. This could
7066 // only be converting signedness, which is a noop.
7067 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00007068 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7069 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00007070 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00007071 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7072 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7073 return BinaryOperator::create(
7074 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007075 }
7076 }
7077
7078 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7079 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7080 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007081 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00007082 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007083 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007084 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7085 }
7086 break;
7087 case Instruction::SDiv:
7088 case Instruction::UDiv:
7089 case Instruction::SRem:
7090 case Instruction::URem:
7091 // If we are just changing the sign, rewrite.
7092 if (DestBitSize == SrcBitSize) {
7093 // Don't insert two casts if they cannot be eliminated. We allow
7094 // two casts to be inserted if the sizes are the same. This could
7095 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007096 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7097 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007098 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7099 Op0, DestTy, SrcI);
7100 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7101 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007102 return BinaryOperator::create(
7103 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7104 }
7105 }
7106 break;
7107
7108 case Instruction::Shl:
7109 // Allow changing the sign of the source operand. Do not allow
7110 // changing the size of the shift, UNLESS the shift amount is a
7111 // constant. We must not change variable sized shifts to a smaller
7112 // size, because it is undefined to shift more bits out than exist
7113 // in the value.
7114 if (DestBitSize == SrcBitSize ||
7115 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007116 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7117 Instruction::BitCast : Instruction::Trunc);
7118 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007119 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007120 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007121 }
7122 break;
7123 case Instruction::AShr:
7124 // If this is a signed shr, and if all bits shifted in are about to be
7125 // truncated off, turn it into an unsigned shr to allow greater
7126 // simplifications.
7127 if (DestBitSize < SrcBitSize &&
7128 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007129 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007130 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7131 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007132 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007133 }
7134 }
7135 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007136 }
7137 return 0;
7138}
7139
Chris Lattner8a9f5712007-04-11 06:57:46 +00007140Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007141 if (Instruction *Result = commonIntCastTransforms(CI))
7142 return Result;
7143
7144 Value *Src = CI.getOperand(0);
7145 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007146 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7147 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007148
7149 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7150 switch (SrcI->getOpcode()) {
7151 default: break;
7152 case Instruction::LShr:
7153 // We can shrink lshr to something smaller if we know the bits shifted in
7154 // are already zeros.
7155 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007156 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007157
7158 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007159 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007160 Value* SrcIOp0 = SrcI->getOperand(0);
7161 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007162 if (ShAmt >= DestBitWidth) // All zeros.
7163 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7164
7165 // Okay, we can shrink this. Truncate the input, then return a new
7166 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007167 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7168 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7169 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007170 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007171 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007172 } else { // This is a variable shr.
7173
7174 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7175 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7176 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007177 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007178 Value *One = ConstantInt::get(SrcI->getType(), 1);
7179
Reid Spencer832254e2007-02-02 02:16:23 +00007180 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007181 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007182 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007183 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7184 SrcI->getOperand(0),
7185 "tmp"), CI);
7186 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007187 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007188 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007189 }
7190 break;
7191 }
7192 }
7193
7194 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007195}
7196
Evan Chengb98a10e2008-03-24 00:21:34 +00007197/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7198/// in order to eliminate the icmp.
7199Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7200 bool DoXform) {
7201 // If we are just checking for a icmp eq of a single bit and zext'ing it
7202 // to an integer, then shift the bit to the appropriate place and then
7203 // cast to integer to avoid the comparison.
7204 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7205 const APInt &Op1CV = Op1C->getValue();
7206
7207 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7208 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7209 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7210 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7211 if (!DoXform) return ICI;
7212
7213 Value *In = ICI->getOperand(0);
7214 Value *Sh = ConstantInt::get(In->getType(),
7215 In->getType()->getPrimitiveSizeInBits()-1);
7216 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7217 In->getName()+".lobit"),
7218 CI);
7219 if (In->getType() != CI.getType())
7220 In = CastInst::createIntegerCast(In, CI.getType(),
7221 false/*ZExt*/, "tmp", &CI);
7222
7223 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7224 Constant *One = ConstantInt::get(In->getType(), 1);
7225 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7226 In->getName()+".not"),
7227 CI);
7228 }
7229
7230 return ReplaceInstUsesWith(CI, In);
7231 }
7232
7233
7234
7235 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7236 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7237 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7238 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7239 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7240 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7241 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7242 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7243 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7244 // This only works for EQ and NE
7245 ICI->isEquality()) {
7246 // If Op1C some other power of two, convert:
7247 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7248 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7249 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7250 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7251
7252 APInt KnownZeroMask(~KnownZero);
7253 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7254 if (!DoXform) return ICI;
7255
7256 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7257 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7258 // (X&4) == 2 --> false
7259 // (X&4) != 2 --> true
7260 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7261 Res = ConstantExpr::getZExt(Res, CI.getType());
7262 return ReplaceInstUsesWith(CI, Res);
7263 }
7264
7265 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7266 Value *In = ICI->getOperand(0);
7267 if (ShiftAmt) {
7268 // Perform a logical shr by shiftamt.
7269 // Insert the shift to put the result in the low bit.
7270 In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7271 ConstantInt::get(In->getType(), ShiftAmt),
7272 In->getName()+".lobit"), CI);
7273 }
7274
7275 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7276 Constant *One = ConstantInt::get(In->getType(), 1);
7277 In = BinaryOperator::createXor(In, One, "tmp");
7278 InsertNewInstBefore(cast<Instruction>(In), CI);
7279 }
7280
7281 if (CI.getType() == In->getType())
7282 return ReplaceInstUsesWith(CI, In);
7283 else
7284 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7285 }
7286 }
7287 }
7288
7289 return 0;
7290}
7291
Chris Lattner8a9f5712007-04-11 06:57:46 +00007292Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007293 // If one of the common conversion will work ..
7294 if (Instruction *Result = commonIntCastTransforms(CI))
7295 return Result;
7296
7297 Value *Src = CI.getOperand(0);
7298
7299 // If this is a cast of a cast
7300 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007301 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7302 // types and if the sizes are just right we can convert this into a logical
7303 // 'and' which will be much cheaper than the pair of casts.
7304 if (isa<TruncInst>(CSrc)) {
7305 // Get the sizes of the types involved
7306 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007307 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7308 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7309 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007310 // If we're actually extending zero bits and the trunc is a no-op
7311 if (MidSize < DstSize && SrcSize == DstSize) {
7312 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007313 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007314 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007315 Instruction *And =
7316 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7317 // Unfortunately, if the type changed, we need to cast it back.
7318 if (And->getType() != CI.getType()) {
7319 And->setName(CSrc->getName()+".mask");
7320 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007321 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007322 }
7323 return And;
7324 }
7325 }
7326 }
7327
Evan Chengb98a10e2008-03-24 00:21:34 +00007328 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7329 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007330
Evan Chengb98a10e2008-03-24 00:21:34 +00007331 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7332 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7333 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7334 // of the (zext icmp) will be transformed.
7335 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7336 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7337 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7338 (transformZExtICmp(LHS, CI, false) ||
7339 transformZExtICmp(RHS, CI, false))) {
7340 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7341 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7342 return BinaryOperator::create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00007343 }
Evan Chengb98a10e2008-03-24 00:21:34 +00007344 }
7345
Reid Spencer3da59db2006-11-27 01:05:10 +00007346 return 0;
7347}
7348
Chris Lattner8a9f5712007-04-11 06:57:46 +00007349Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007350 if (Instruction *I = commonIntCastTransforms(CI))
7351 return I;
7352
Chris Lattner8a9f5712007-04-11 06:57:46 +00007353 Value *Src = CI.getOperand(0);
7354
7355 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7356 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7357 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7358 // If we are just checking for a icmp eq of a single bit and zext'ing it
7359 // to an integer, then shift the bit to the appropriate place and then
7360 // cast to integer to avoid the comparison.
7361 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7362 const APInt &Op1CV = Op1C->getValue();
7363
7364 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7365 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7366 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7367 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7368 Value *In = ICI->getOperand(0);
7369 Value *Sh = ConstantInt::get(In->getType(),
7370 In->getType()->getPrimitiveSizeInBits()-1);
7371 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007372 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007373 CI);
7374 if (In->getType() != CI.getType())
7375 In = CastInst::createIntegerCast(In, CI.getType(),
7376 true/*SExt*/, "tmp", &CI);
7377
7378 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7379 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7380 In->getName()+".not"), CI);
7381
7382 return ReplaceInstUsesWith(CI, In);
7383 }
7384 }
7385 }
7386
Chris Lattnerba417832007-04-11 06:12:58 +00007387 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007388}
7389
Chris Lattnerb7530652008-01-27 05:29:54 +00007390/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7391/// in the specified FP type without changing its value.
7392static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7393 const fltSemantics &Sem) {
7394 APFloat F = CFP->getValueAPF();
7395 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7396 return ConstantFP::get(FPTy, F);
7397 return 0;
7398}
7399
7400/// LookThroughFPExtensions - If this is an fp extension instruction, look
7401/// through it until we get the source value.
7402static Value *LookThroughFPExtensions(Value *V) {
7403 if (Instruction *I = dyn_cast<Instruction>(V))
7404 if (I->getOpcode() == Instruction::FPExt)
7405 return LookThroughFPExtensions(I->getOperand(0));
7406
7407 // If this value is a constant, return the constant in the smallest FP type
7408 // that can accurately represent it. This allows us to turn
7409 // (float)((double)X+2.0) into x+2.0f.
7410 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7411 if (CFP->getType() == Type::PPC_FP128Ty)
7412 return V; // No constant folding of this.
7413 // See if the value can be truncated to float and then reextended.
7414 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7415 return V;
7416 if (CFP->getType() == Type::DoubleTy)
7417 return V; // Won't shrink.
7418 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7419 return V;
7420 // Don't try to shrink to various long double types.
7421 }
7422
7423 return V;
7424}
7425
7426Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7427 if (Instruction *I = commonCastTransforms(CI))
7428 return I;
7429
7430 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7431 // smaller than the destination type, we can eliminate the truncate by doing
7432 // the add as the smaller type. This applies to add/sub/mul/div as well as
7433 // many builtins (sqrt, etc).
7434 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7435 if (OpI && OpI->hasOneUse()) {
7436 switch (OpI->getOpcode()) {
7437 default: break;
7438 case Instruction::Add:
7439 case Instruction::Sub:
7440 case Instruction::Mul:
7441 case Instruction::FDiv:
7442 case Instruction::FRem:
7443 const Type *SrcTy = OpI->getType();
7444 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7445 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7446 if (LHSTrunc->getType() != SrcTy &&
7447 RHSTrunc->getType() != SrcTy) {
7448 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7449 // If the source types were both smaller than the destination type of
7450 // the cast, do this xform.
7451 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7452 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7453 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7454 CI.getType(), CI);
7455 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7456 CI.getType(), CI);
7457 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7458 }
7459 }
7460 break;
7461 }
7462 }
7463 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007464}
7465
7466Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7467 return commonCastTransforms(CI);
7468}
7469
7470Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007471 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007472}
7473
7474Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007475 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007476}
7477
7478Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7479 return commonCastTransforms(CI);
7480}
7481
7482Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7483 return commonCastTransforms(CI);
7484}
7485
7486Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007487 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007488}
7489
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007490Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7491 if (Instruction *I = commonCastTransforms(CI))
7492 return I;
7493
7494 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7495 if (!DestPointee->isSized()) return 0;
7496
7497 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7498 ConstantInt *Cst;
7499 Value *X;
7500 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7501 m_ConstantInt(Cst)))) {
7502 // If the source and destination operands have the same type, see if this
7503 // is a single-index GEP.
7504 if (X->getType() == CI.getType()) {
7505 // Get the size of the pointee type.
Bill Wendlingb9d4f8d2008-03-14 05:12:19 +00007506 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007507
7508 // Convert the constant to intptr type.
7509 APInt Offset = Cst->getValue();
7510 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7511
7512 // If Offset is evenly divisible by Size, we can do this xform.
7513 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7514 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7515 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7516 }
7517 }
7518 // TODO: Could handle other cases, e.g. where add is indexing into field of
7519 // struct etc.
7520 } else if (CI.getOperand(0)->hasOneUse() &&
7521 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7522 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7523 // "inttoptr+GEP" instead of "add+intptr".
7524
7525 // Get the size of the pointee type.
7526 uint64_t Size = TD->getABITypeSize(DestPointee);
7527
7528 // Convert the constant to intptr type.
7529 APInt Offset = Cst->getValue();
7530 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7531
7532 // If Offset is evenly divisible by Size, we can do this xform.
7533 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7534 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7535
7536 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7537 "tmp"), CI);
7538 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7539 }
7540 }
7541 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007542}
7543
Chris Lattnerd3e28342007-04-27 17:44:50 +00007544Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007545 // If the operands are integer typed then apply the integer transforms,
7546 // otherwise just apply the common ones.
7547 Value *Src = CI.getOperand(0);
7548 const Type *SrcTy = Src->getType();
7549 const Type *DestTy = CI.getType();
7550
Chris Lattner42a75512007-01-15 02:27:26 +00007551 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007552 if (Instruction *Result = commonIntCastTransforms(CI))
7553 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007554 } else if (isa<PointerType>(SrcTy)) {
7555 if (Instruction *I = commonPointerCastTransforms(CI))
7556 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007557 } else {
7558 if (Instruction *Result = commonCastTransforms(CI))
7559 return Result;
7560 }
7561
7562
7563 // Get rid of casts from one type to the same type. These are useless and can
7564 // be replaced by the operand.
7565 if (DestTy == Src->getType())
7566 return ReplaceInstUsesWith(CI, Src);
7567
Reid Spencer3da59db2006-11-27 01:05:10 +00007568 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007569 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7570 const Type *DstElTy = DstPTy->getElementType();
7571 const Type *SrcElTy = SrcPTy->getElementType();
7572
7573 // If we are casting a malloc or alloca to a pointer to a type of the same
7574 // size, rewrite the allocation instruction to allocate the "right" type.
7575 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7576 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7577 return V;
7578
Chris Lattnerd717c182007-05-05 22:32:24 +00007579 // If the source and destination are pointers, and this cast is equivalent
7580 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007581 // This can enhance SROA and other transforms that want type-safe pointers.
7582 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7583 unsigned NumZeros = 0;
7584 while (SrcElTy != DstElTy &&
7585 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7586 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7587 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7588 ++NumZeros;
7589 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007590
Chris Lattnerd3e28342007-04-27 17:44:50 +00007591 // If we found a path from the src to dest, create the getelementptr now.
7592 if (SrcElTy == DstElTy) {
7593 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007594 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7595 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007596 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007597 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007598
Reid Spencer3da59db2006-11-27 01:05:10 +00007599 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7600 if (SVI->hasOneUse()) {
7601 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7602 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007603 if (isa<VectorType>(DestTy) &&
7604 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007605 SVI->getType()->getNumElements()) {
7606 CastInst *Tmp;
7607 // If either of the operands is a cast from CI.getType(), then
7608 // evaluating the shuffle in the casted destination's type will allow
7609 // us to eliminate at least one cast.
7610 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7611 Tmp->getOperand(0)->getType() == DestTy) ||
7612 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7613 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007614 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7615 SVI->getOperand(0), DestTy, &CI);
7616 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7617 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007618 // Return a new shuffle vector. Use the same element ID's, as we
7619 // know the vector types match #elts.
7620 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007621 }
7622 }
7623 }
7624 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007625 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007626}
7627
Chris Lattnere576b912004-04-09 23:46:01 +00007628/// GetSelectFoldableOperands - We want to turn code that looks like this:
7629/// %C = or %A, %B
7630/// %D = select %cond, %C, %A
7631/// into:
7632/// %C = select %cond, %B, 0
7633/// %D = or %A, %C
7634///
7635/// Assuming that the specified instruction is an operand to the select, return
7636/// a bitmask indicating which operands of this instruction are foldable if they
7637/// equal the other incoming value of the select.
7638///
7639static unsigned GetSelectFoldableOperands(Instruction *I) {
7640 switch (I->getOpcode()) {
7641 case Instruction::Add:
7642 case Instruction::Mul:
7643 case Instruction::And:
7644 case Instruction::Or:
7645 case Instruction::Xor:
7646 return 3; // Can fold through either operand.
7647 case Instruction::Sub: // Can only fold on the amount subtracted.
7648 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007649 case Instruction::LShr:
7650 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007651 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007652 default:
7653 return 0; // Cannot fold
7654 }
7655}
7656
7657/// GetSelectFoldableConstant - For the same transformation as the previous
7658/// function, return the identity constant that goes into the select.
7659static Constant *GetSelectFoldableConstant(Instruction *I) {
7660 switch (I->getOpcode()) {
7661 default: assert(0 && "This cannot happen!"); abort();
7662 case Instruction::Add:
7663 case Instruction::Sub:
7664 case Instruction::Or:
7665 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007666 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007667 case Instruction::LShr:
7668 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007669 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007670 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007671 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007672 case Instruction::Mul:
7673 return ConstantInt::get(I->getType(), 1);
7674 }
7675}
7676
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007677/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7678/// have the same opcode and only one use each. Try to simplify this.
7679Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7680 Instruction *FI) {
7681 if (TI->getNumOperands() == 1) {
7682 // If this is a non-volatile load or a cast from the same type,
7683 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007684 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007685 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7686 return 0;
7687 } else {
7688 return 0; // unknown unary op.
7689 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007690
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007691 // Fold this by inserting a select from the input values.
7692 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7693 FI->getOperand(0), SI.getName()+".v");
7694 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007695 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7696 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007697 }
7698
Reid Spencer832254e2007-02-02 02:16:23 +00007699 // Only handle binary operators here.
7700 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007701 return 0;
7702
7703 // Figure out if the operations have any operands in common.
7704 Value *MatchOp, *OtherOpT, *OtherOpF;
7705 bool MatchIsOpZero;
7706 if (TI->getOperand(0) == FI->getOperand(0)) {
7707 MatchOp = TI->getOperand(0);
7708 OtherOpT = TI->getOperand(1);
7709 OtherOpF = FI->getOperand(1);
7710 MatchIsOpZero = true;
7711 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7712 MatchOp = TI->getOperand(1);
7713 OtherOpT = TI->getOperand(0);
7714 OtherOpF = FI->getOperand(0);
7715 MatchIsOpZero = false;
7716 } else if (!TI->isCommutative()) {
7717 return 0;
7718 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7719 MatchOp = TI->getOperand(0);
7720 OtherOpT = TI->getOperand(1);
7721 OtherOpF = FI->getOperand(0);
7722 MatchIsOpZero = true;
7723 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7724 MatchOp = TI->getOperand(1);
7725 OtherOpT = TI->getOperand(0);
7726 OtherOpF = FI->getOperand(1);
7727 MatchIsOpZero = true;
7728 } else {
7729 return 0;
7730 }
7731
7732 // If we reach here, they do have operations in common.
7733 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7734 OtherOpF, SI.getName()+".v");
7735 InsertNewInstBefore(NewSI, SI);
7736
7737 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7738 if (MatchIsOpZero)
7739 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7740 else
7741 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007742 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007743 assert(0 && "Shouldn't get here");
7744 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007745}
7746
Chris Lattner3d69f462004-03-12 05:52:32 +00007747Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007748 Value *CondVal = SI.getCondition();
7749 Value *TrueVal = SI.getTrueValue();
7750 Value *FalseVal = SI.getFalseValue();
7751
7752 // select true, X, Y -> X
7753 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007754 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007755 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007756
7757 // select C, X, X -> X
7758 if (TrueVal == FalseVal)
7759 return ReplaceInstUsesWith(SI, TrueVal);
7760
Chris Lattnere87597f2004-10-16 18:11:37 +00007761 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7762 return ReplaceInstUsesWith(SI, FalseVal);
7763 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7764 return ReplaceInstUsesWith(SI, TrueVal);
7765 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7766 if (isa<Constant>(TrueVal))
7767 return ReplaceInstUsesWith(SI, TrueVal);
7768 else
7769 return ReplaceInstUsesWith(SI, FalseVal);
7770 }
7771
Reid Spencer4fe16d62007-01-11 18:21:29 +00007772 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007773 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007774 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007775 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007776 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007777 } else {
7778 // Change: A = select B, false, C --> A = and !B, C
7779 Value *NotCond =
7780 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7781 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007782 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007783 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007784 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007785 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007786 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007787 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007788 } else {
7789 // Change: A = select B, C, true --> A = or !B, C
7790 Value *NotCond =
7791 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7792 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007793 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007794 }
7795 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007796
7797 // select a, b, a -> a&b
7798 // select a, a, b -> a|b
7799 if (CondVal == TrueVal)
7800 return BinaryOperator::createOr(CondVal, FalseVal);
7801 else if (CondVal == FalseVal)
7802 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007803 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007804
Chris Lattner2eefe512004-04-09 19:05:30 +00007805 // Selecting between two integer constants?
7806 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7807 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007808 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007809 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007810 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007811 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007812 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007813 Value *NotCond =
7814 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007815 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007816 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007817 }
Chris Lattnerba417832007-04-11 06:12:58 +00007818
7819 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007820
Reid Spencere4d87aa2006-12-23 06:05:41 +00007821 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007822
Reid Spencere4d87aa2006-12-23 06:05:41 +00007823 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007824 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007825 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007826 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007827 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007828 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007829 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007830 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007831 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7832 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7833 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007834 InsertNewInstBefore(SRA, SI);
7835
Reid Spencer3da59db2006-11-27 01:05:10 +00007836 // Finally, convert to the type of the select RHS. We figure out
7837 // if this requires a SExt, Trunc or BitCast based on the sizes.
7838 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007839 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7840 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007841 if (SRASize < SISize)
7842 opc = Instruction::SExt;
7843 else if (SRASize > SISize)
7844 opc = Instruction::Trunc;
7845 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007846 }
7847 }
7848
7849
7850 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007851 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007852 // non-constant value, eliminate this whole mess. This corresponds to
7853 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007854 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007855 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007856 cast<Constant>(IC->getOperand(1))->isNullValue())
7857 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7858 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007859 isa<ConstantInt>(ICA->getOperand(1)) &&
7860 (ICA->getOperand(1) == TrueValC ||
7861 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007862 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7863 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007864 // know whether we have a icmp_ne or icmp_eq and whether the
7865 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007866 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007867 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007868 Value *V = ICA;
7869 if (ShouldNotVal)
7870 V = InsertNewInstBefore(BinaryOperator::create(
7871 Instruction::Xor, V, ICA->getOperand(1)), SI);
7872 return ReplaceInstUsesWith(SI, V);
7873 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007874 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007875 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007876
7877 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007878 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7879 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007880 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007881 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7882 // This is not safe in general for floating point:
7883 // consider X== -0, Y== +0.
7884 // It becomes safe if either operand is a nonzero constant.
7885 ConstantFP *CFPt, *CFPf;
7886 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7887 !CFPt->getValueAPF().isZero()) ||
7888 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7889 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007890 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007891 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007892 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007893 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007894 return ReplaceInstUsesWith(SI, TrueVal);
7895 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7896
Reid Spencere4d87aa2006-12-23 06:05:41 +00007897 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007898 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007899 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7900 // This is not safe in general for floating point:
7901 // consider X== -0, Y== +0.
7902 // It becomes safe if either operand is a nonzero constant.
7903 ConstantFP *CFPt, *CFPf;
7904 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7905 !CFPt->getValueAPF().isZero()) ||
7906 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7907 !CFPf->getValueAPF().isZero()))
7908 return ReplaceInstUsesWith(SI, FalseVal);
7909 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007910 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007911 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7912 return ReplaceInstUsesWith(SI, TrueVal);
7913 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7914 }
7915 }
7916
7917 // See if we are selecting two values based on a comparison of the two values.
7918 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7919 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7920 // Transform (X == Y) ? X : Y -> Y
7921 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7922 return ReplaceInstUsesWith(SI, FalseVal);
7923 // Transform (X != Y) ? X : Y -> X
7924 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7925 return ReplaceInstUsesWith(SI, TrueVal);
7926 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7927
7928 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7929 // Transform (X == Y) ? Y : X -> X
7930 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7931 return ReplaceInstUsesWith(SI, FalseVal);
7932 // Transform (X != Y) ? Y : X -> Y
7933 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007934 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007935 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7936 }
7937 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007938
Chris Lattner87875da2005-01-13 22:52:24 +00007939 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7940 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7941 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007942 Instruction *AddOp = 0, *SubOp = 0;
7943
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007944 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7945 if (TI->getOpcode() == FI->getOpcode())
7946 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7947 return IV;
7948
7949 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7950 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007951 if (TI->getOpcode() == Instruction::Sub &&
7952 FI->getOpcode() == Instruction::Add) {
7953 AddOp = FI; SubOp = TI;
7954 } else if (FI->getOpcode() == Instruction::Sub &&
7955 TI->getOpcode() == Instruction::Add) {
7956 AddOp = TI; SubOp = FI;
7957 }
7958
7959 if (AddOp) {
7960 Value *OtherAddOp = 0;
7961 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7962 OtherAddOp = AddOp->getOperand(1);
7963 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7964 OtherAddOp = AddOp->getOperand(0);
7965 }
7966
7967 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007968 // So at this point we know we have (Y -> OtherAddOp):
7969 // select C, (add X, Y), (sub X, Z)
7970 Value *NegVal; // Compute -Z
7971 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7972 NegVal = ConstantExpr::getNeg(C);
7973 } else {
7974 NegVal = InsertNewInstBefore(
7975 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007976 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007977
7978 Value *NewTrueOp = OtherAddOp;
7979 Value *NewFalseOp = NegVal;
7980 if (AddOp != TI)
7981 std::swap(NewTrueOp, NewFalseOp);
7982 Instruction *NewSel =
7983 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7984
7985 NewSel = InsertNewInstBefore(NewSel, SI);
7986 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007987 }
7988 }
7989 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007990
Chris Lattnere576b912004-04-09 23:46:01 +00007991 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007992 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007993 // See the comment above GetSelectFoldableOperands for a description of the
7994 // transformation we are doing here.
7995 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7996 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7997 !isa<Constant>(FalseVal))
7998 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7999 unsigned OpToFold = 0;
8000 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8001 OpToFold = 1;
8002 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8003 OpToFold = 2;
8004 }
8005
8006 if (OpToFold) {
8007 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008008 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00008009 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00008010 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008011 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008012 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8013 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00008014 else {
8015 assert(0 && "Unknown instruction!!");
8016 }
8017 }
8018 }
Chris Lattnera96879a2004-09-29 17:40:11 +00008019
Chris Lattnere576b912004-04-09 23:46:01 +00008020 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8021 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8022 !isa<Constant>(TrueVal))
8023 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8024 unsigned OpToFold = 0;
8025 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8026 OpToFold = 1;
8027 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8028 OpToFold = 2;
8029 }
8030
8031 if (OpToFold) {
8032 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008033 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00008034 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00008035 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00008036 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00008037 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8038 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00008039 else
Chris Lattnere576b912004-04-09 23:46:01 +00008040 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00008041 }
8042 }
8043 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00008044
8045 if (BinaryOperator::isNot(CondVal)) {
8046 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8047 SI.setOperand(1, FalseVal);
8048 SI.setOperand(2, TrueVal);
8049 return &SI;
8050 }
8051
Chris Lattner3d69f462004-03-12 05:52:32 +00008052 return 0;
8053}
8054
Chris Lattnerf2369f22007-08-09 19:05:49 +00008055/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8056/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8057/// and it is more than the alignment of the ultimate object, see if we can
8058/// increase the alignment of the ultimate object, making this check succeed.
8059static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
8060 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008061 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
8062 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00008063 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008064 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00008065
8066 // If there is a large requested alignment and we can, bump up the alignment
8067 // of the global.
8068 if (PrefAlign > Align && GV->hasInitializer()) {
8069 GV->setAlignment(PrefAlign);
8070 Align = PrefAlign;
8071 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008072 return Align;
8073 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8074 unsigned Align = AI->getAlignment();
8075 if (Align == 0 && TD) {
8076 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008077 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00008078 else if (isa<MallocInst>(AI)) {
8079 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008080 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00008081 Align =
8082 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008083 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00008084 Align =
8085 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008086 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00008087 }
8088 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008089
8090 // If there is a requested alignment and if this is an alloca, round up. We
8091 // don't do this for malloc, because some systems can't respect the request.
8092 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
8093 AI->setAlignment(PrefAlign);
8094 Align = PrefAlign;
8095 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008096 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00008097 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00008098 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00008099 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008100 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
8101 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00008102 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00008103 // If all indexes are zero, it is just the alignment of the base pointer.
8104 bool AllZeroOperands = true;
8105 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
8106 if (!isa<Constant>(GEPI->getOperand(i)) ||
8107 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
8108 AllZeroOperands = false;
8109 break;
8110 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00008111
8112 if (AllZeroOperands) {
8113 // Treat this like a bitcast.
8114 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
8115 }
8116
8117 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
8118 if (BaseAlignment == 0) return 0;
8119
Chris Lattner95a959d2006-03-06 20:18:44 +00008120 // Otherwise, if the base alignment is >= the alignment we expect for the
8121 // base pointer type, then we know that the resultant pointer is aligned at
8122 // least as much as its type requires.
8123 if (!TD) return 0;
8124
8125 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008126 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008127 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
8128 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00008129 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00008130 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00008131 Align = std::min(Align, (unsigned)
8132 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
8133 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00008134 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008135 return 0;
8136 }
8137 return 0;
8138}
8139
Chris Lattnerf497b022008-01-13 23:50:23 +00008140Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8141 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8142 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8143 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8144 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8145
8146 if (CopyAlign < MinAlign) {
8147 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8148 return MI;
8149 }
8150
8151 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8152 // load/store.
8153 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8154 if (MemOpLength == 0) return 0;
8155
Chris Lattner37ac6082008-01-14 00:28:35 +00008156 // Source and destination pointer types are always "i8*" for intrinsic. See
8157 // if the size is something we can handle with a single primitive load/store.
8158 // A single load+store correctly handles overlapping memory in the memmove
8159 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008160 unsigned Size = MemOpLength->getZExtValue();
8161 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008162 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008163
Chris Lattner37ac6082008-01-14 00:28:35 +00008164 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008165 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008166
8167 // Memcpy forces the use of i8* for the source and destination. That means
8168 // that if you're using memcpy to move one double around, you'll get a cast
8169 // from double* to i8*. We'd much rather use a double load+store rather than
8170 // an i64 load+store, here because this improves the odds that the source or
8171 // dest address will be promotable. See if we can find a better type than the
8172 // integer datatype.
8173 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8174 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8175 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8176 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8177 // down through these levels if so.
8178 while (!SrcETy->isFirstClassType()) {
8179 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8180 if (STy->getNumElements() == 1)
8181 SrcETy = STy->getElementType(0);
8182 else
8183 break;
8184 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8185 if (ATy->getNumElements() == 1)
8186 SrcETy = ATy->getElementType();
8187 else
8188 break;
8189 } else
8190 break;
8191 }
8192
8193 if (SrcETy->isFirstClassType())
8194 NewPtrTy = PointerType::getUnqual(SrcETy);
8195 }
8196 }
8197
8198
Chris Lattnerf497b022008-01-13 23:50:23 +00008199 // If the memcpy/memmove provides better alignment info than we can
8200 // infer, use it.
8201 SrcAlign = std::max(SrcAlign, CopyAlign);
8202 DstAlign = std::max(DstAlign, CopyAlign);
8203
8204 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8205 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008206 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8207 InsertNewInstBefore(L, *MI);
8208 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8209
8210 // Set the size of the copy to 0, it will be deleted on the next iteration.
8211 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8212 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008213}
Chris Lattner3d69f462004-03-12 05:52:32 +00008214
Chris Lattner8b0ea312006-01-13 20:11:04 +00008215/// visitCallInst - CallInst simplification. This mostly only handles folding
8216/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8217/// the heavy lifting.
8218///
Chris Lattner9fe38862003-06-19 17:00:31 +00008219Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008220 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8221 if (!II) return visitCallSite(&CI);
8222
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008223 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8224 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008225 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008226 bool Changed = false;
8227
8228 // memmove/cpy/set of zero bytes is a noop.
8229 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8230 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8231
Chris Lattner35b9e482004-10-12 04:52:52 +00008232 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008233 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008234 // Replace the instruction with just byte operations. We would
8235 // transform other cases to loads/stores, but we don't know if
8236 // alignment is sufficient.
8237 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008238 }
8239
Chris Lattner35b9e482004-10-12 04:52:52 +00008240 // If we have a memmove and the source operation is a constant global,
8241 // then the source and dest pointers can't alias, so we can change this
8242 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008243 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008244 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8245 if (GVSrc->isConstant()) {
8246 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008247 Intrinsic::ID MemCpyID;
8248 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8249 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008250 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008251 MemCpyID = Intrinsic::memcpy_i64;
8252 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008253 Changed = true;
8254 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008255 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008256
Chris Lattner95a959d2006-03-06 20:18:44 +00008257 // If we can determine a pointer alignment that is bigger than currently
8258 // set, update the alignment.
8259 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008260 if (Instruction *I = SimplifyMemTransfer(MI))
8261 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008262 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008263 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00008264 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008265 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008266 Changed = true;
8267 }
8268 }
8269
Chris Lattner8b0ea312006-01-13 20:11:04 +00008270 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008271 } else {
8272 switch (II->getIntrinsicID()) {
8273 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008274 case Intrinsic::ppc_altivec_lvx:
8275 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008276 case Intrinsic::x86_sse_loadu_ps:
8277 case Intrinsic::x86_sse2_loadu_pd:
8278 case Intrinsic::x86_sse2_loadu_dq:
8279 // Turn PPC lvx -> load if the pointer is known aligned.
8280 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008281 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008282 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8283 PointerType::getUnqual(II->getType()),
8284 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008285 return new LoadInst(Ptr);
8286 }
8287 break;
8288 case Intrinsic::ppc_altivec_stvx:
8289 case Intrinsic::ppc_altivec_stvxl:
8290 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008291 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008292 const Type *OpPtrTy =
8293 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008294 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008295 return new StoreInst(II->getOperand(1), Ptr);
8296 }
8297 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008298 case Intrinsic::x86_sse_storeu_ps:
8299 case Intrinsic::x86_sse2_storeu_pd:
8300 case Intrinsic::x86_sse2_storeu_dq:
8301 case Intrinsic::x86_sse2_storel_dq:
8302 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008303 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008304 const Type *OpPtrTy =
8305 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008306 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008307 return new StoreInst(II->getOperand(2), Ptr);
8308 }
8309 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008310
8311 case Intrinsic::x86_sse_cvttss2si: {
8312 // These intrinsics only demands the 0th element of its input vector. If
8313 // we can simplify the input based on that, do so now.
8314 uint64_t UndefElts;
8315 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8316 UndefElts)) {
8317 II->setOperand(1, V);
8318 return II;
8319 }
8320 break;
8321 }
8322
Chris Lattnere2ed0572006-04-06 19:19:17 +00008323 case Intrinsic::ppc_altivec_vperm:
8324 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008325 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008326 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8327
8328 // Check that all of the elements are integer constants or undefs.
8329 bool AllEltsOk = true;
8330 for (unsigned i = 0; i != 16; ++i) {
8331 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8332 !isa<UndefValue>(Mask->getOperand(i))) {
8333 AllEltsOk = false;
8334 break;
8335 }
8336 }
8337
8338 if (AllEltsOk) {
8339 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008340 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8341 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008342 Value *Result = UndefValue::get(Op0->getType());
8343
8344 // Only extract each element once.
8345 Value *ExtractedElts[32];
8346 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8347
8348 for (unsigned i = 0; i != 16; ++i) {
8349 if (isa<UndefValue>(Mask->getOperand(i)))
8350 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008351 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008352 Idx &= 31; // Match the hardware behavior.
8353
8354 if (ExtractedElts[Idx] == 0) {
8355 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008356 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008357 InsertNewInstBefore(Elt, CI);
8358 ExtractedElts[Idx] = Elt;
8359 }
8360
8361 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008362 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008363 InsertNewInstBefore(cast<Instruction>(Result), CI);
8364 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008365 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008366 }
8367 }
8368 break;
8369
Chris Lattnera728ddc2006-01-13 21:28:09 +00008370 case Intrinsic::stackrestore: {
8371 // If the save is right next to the restore, remove the restore. This can
8372 // happen when variable allocas are DCE'd.
8373 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8374 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8375 BasicBlock::iterator BI = SS;
8376 if (&*++BI == II)
8377 return EraseInstFromFunction(CI);
8378 }
8379 }
8380
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008381 // Scan down this block to see if there is another stack restore in the
8382 // same block without an intervening call/alloca.
8383 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008384 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008385 bool CannotRemove = false;
8386 for (++BI; &*BI != TI; ++BI) {
8387 if (isa<AllocaInst>(BI)) {
8388 CannotRemove = true;
8389 break;
8390 }
8391 if (isa<CallInst>(BI)) {
8392 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008393 CannotRemove = true;
8394 break;
8395 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008396 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008397 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008398 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008399 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008400
8401 // If the stack restore is in a return/unwind block and if there are no
8402 // allocas or calls between the restore and the return, nuke the restore.
8403 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8404 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008405 break;
8406 }
8407 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008408 }
8409
Chris Lattner8b0ea312006-01-13 20:11:04 +00008410 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008411}
8412
8413// InvokeInst simplification
8414//
8415Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008416 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008417}
8418
Chris Lattnera44d8a22003-10-07 22:32:43 +00008419// visitCallSite - Improvements for call and invoke instructions.
8420//
8421Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008422 bool Changed = false;
8423
8424 // If the callee is a constexpr cast of a function, attempt to move the cast
8425 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008426 if (transformConstExprCastCall(CS)) return 0;
8427
Chris Lattner6c266db2003-10-07 22:54:13 +00008428 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008429
Chris Lattner08b22ec2005-05-13 07:09:09 +00008430 if (Function *CalleeF = dyn_cast<Function>(Callee))
8431 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8432 Instruction *OldCall = CS.getInstruction();
8433 // If the call and callee calling conventions don't match, this call must
8434 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008435 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008436 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8437 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008438 if (!OldCall->use_empty())
8439 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8440 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8441 return EraseInstFromFunction(*OldCall);
8442 return 0;
8443 }
8444
Chris Lattner17be6352004-10-18 02:59:09 +00008445 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8446 // This instruction is not reachable, just remove it. We insert a store to
8447 // undef so that we know that this code is not reachable, despite the fact
8448 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008449 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008450 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008451 CS.getInstruction());
8452
8453 if (!CS.getInstruction()->use_empty())
8454 CS.getInstruction()->
8455 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8456
8457 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8458 // Don't break the CFG, insert a dummy cond branch.
8459 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008460 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008461 }
Chris Lattner17be6352004-10-18 02:59:09 +00008462 return EraseInstFromFunction(*CS.getInstruction());
8463 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008464
Duncan Sandscdb6d922007-09-17 10:26:40 +00008465 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8466 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8467 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8468 return transformCallThroughTrampoline(CS);
8469
Chris Lattner6c266db2003-10-07 22:54:13 +00008470 const PointerType *PTy = cast<PointerType>(Callee->getType());
8471 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8472 if (FTy->isVarArg()) {
8473 // See if we can optimize any arguments passed through the varargs area of
8474 // the call.
8475 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8476 E = CS.arg_end(); I != E; ++I)
8477 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8478 // If this cast does not effect the value passed through the varargs
8479 // area, we can eliminate the use of the cast.
8480 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008481 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008482 *I = Op;
8483 Changed = true;
8484 }
8485 }
8486 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008487
Duncan Sandsf0c33542007-12-19 21:13:37 +00008488 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008489 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008490 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008491 Changed = true;
8492 }
8493
Chris Lattner6c266db2003-10-07 22:54:13 +00008494 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008495}
8496
Chris Lattner9fe38862003-06-19 17:00:31 +00008497// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8498// attempt to move the cast to the arguments of the call/invoke.
8499//
8500bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8501 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8502 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008503 if (CE->getOpcode() != Instruction::BitCast ||
8504 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008505 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008506 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008507 Instruction *Caller = CS.getInstruction();
Chris Lattner58d74912008-03-12 17:45:29 +00008508 const PAListPtr &CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008509
8510 // Okay, this is a cast from a function to a different type. Unless doing so
8511 // would cause a type conversion of one of our arguments, change this call to
8512 // be a direct call with arguments casted to the appropriate types.
8513 //
8514 const FunctionType *FT = Callee->getFunctionType();
8515 const Type *OldRetTy = Caller->getType();
8516
Devang Patel75e6f022008-03-11 18:04:06 +00008517 if (isa<StructType>(FT->getReturnType()))
8518 return false; // TODO: Handle multiple return values.
8519
Chris Lattnerf78616b2004-01-14 06:06:08 +00008520 // Check to see if we are changing the return type...
8521 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008522 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008523 // Conversion is ok if changing from pointer to int of same size.
8524 !(isa<PointerType>(FT->getReturnType()) &&
8525 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008526 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008527
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008528 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008529 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008530 FT->getReturnType() != Type::VoidTy &&
8531 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008532 return false; // Cannot transform this return value.
8533
Chris Lattner58d74912008-03-12 17:45:29 +00008534 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8535 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008536 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8537 return false; // Attribute not compatible with transformed value.
8538 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008539
Chris Lattnerf78616b2004-01-14 06:06:08 +00008540 // If the callsite is an invoke instruction, and the return value is used by
8541 // a PHI node in a successor, we cannot change the return type of the call
8542 // because there is no place to put the cast instruction (without breaking
8543 // the critical edge). Bail out in this case.
8544 if (!Caller->use_empty())
8545 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8546 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8547 UI != E; ++UI)
8548 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8549 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008550 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008551 return false;
8552 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008553
8554 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8555 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008556
Chris Lattner9fe38862003-06-19 17:00:31 +00008557 CallSite::arg_iterator AI = CS.arg_begin();
8558 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8559 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008560 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008561
8562 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008563 return false; // Cannot transform this parameter value.
8564
Chris Lattner58d74912008-03-12 17:45:29 +00008565 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8566 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008567
Reid Spencer3da59db2006-11-27 01:05:10 +00008568 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008569 // Some conversions are safe even if we do not have a body.
8570 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008571 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008572 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008573 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008574 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8575 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008576 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008577 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008578 }
8579
8580 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008581 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +00008582 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +00008583
Chris Lattner58d74912008-03-12 17:45:29 +00008584 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8585 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008586 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008587 // won't be dropping them. Check that these extra arguments have attributes
8588 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +00008589 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8590 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +00008591 break;
Chris Lattner58d74912008-03-12 17:45:29 +00008592 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008593 if (PAttrs & ParamAttr::VarArgsIncompatible)
8594 return false;
8595 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008596
Chris Lattner9fe38862003-06-19 17:00:31 +00008597 // Okay, we decided that this is a safe thing to do: go ahead and start
8598 // inserting cast instructions as necessary...
8599 std::vector<Value*> Args;
8600 Args.reserve(NumActualArgs);
Chris Lattner58d74912008-03-12 17:45:29 +00008601 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008602 attrVec.reserve(NumCommonArgs);
8603
8604 // Get any return attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008605 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008606
8607 // If the return value is not being used, the type may not be compatible
8608 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008609 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008610
8611 // Add the new return attributes.
8612 if (RAttrs)
8613 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008614
8615 AI = CS.arg_begin();
8616 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8617 const Type *ParamTy = FT->getParamType(i);
8618 if ((*AI)->getType() == ParamTy) {
8619 Args.push_back(*AI);
8620 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008621 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008622 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008623 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008624 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008625 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008626
8627 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008628 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008629 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008630 }
8631
8632 // If the function takes more arguments than the call was taking, add them
8633 // now...
8634 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8635 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8636
8637 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008638 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008639 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008640 cerr << "WARNING: While resolving call to function '"
8641 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008642 } else {
8643 // Add all of the arguments in their promoted form to the arg list...
8644 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8645 const Type *PTy = getPromotedType((*AI)->getType());
8646 if (PTy != (*AI)->getType()) {
8647 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008648 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8649 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008650 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008651 InsertNewInstBefore(Cast, *Caller);
8652 Args.push_back(Cast);
8653 } else {
8654 Args.push_back(*AI);
8655 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008656
Duncan Sandse1e520f2008-01-13 08:02:44 +00008657 // Add any parameter attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008658 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandse1e520f2008-01-13 08:02:44 +00008659 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8660 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008661 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008662 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008663
8664 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008665 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008666
Chris Lattner58d74912008-03-12 17:45:29 +00008667 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008668
Chris Lattner9fe38862003-06-19 17:00:31 +00008669 Instruction *NC;
8670 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008671 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008672 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008673 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008674 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008675 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008676 NC = new CallInst(Callee, Args.begin(), Args.end(),
8677 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008678 CallInst *CI = cast<CallInst>(Caller);
8679 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008680 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008681 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008682 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008683 }
8684
Chris Lattner6934a042007-02-11 01:23:03 +00008685 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008686 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008687 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008688 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008689 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008690 OldRetTy, false);
8691 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008692
8693 // If this is an invoke instruction, we should insert it after the first
8694 // non-phi, instruction in the normal successor block.
8695 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8696 BasicBlock::iterator I = II->getNormalDest()->begin();
8697 while (isa<PHINode>(I)) ++I;
8698 InsertNewInstBefore(NC, *I);
8699 } else {
8700 // Otherwise, it's a call, just insert cast right after the call instr
8701 InsertNewInstBefore(NC, *Caller);
8702 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008703 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008704 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008705 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008706 }
8707 }
8708
8709 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8710 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008711 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008712 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008713 return true;
8714}
8715
Duncan Sandscdb6d922007-09-17 10:26:40 +00008716// transformCallThroughTrampoline - Turn a call to a function created by the
8717// init_trampoline intrinsic into a direct call to the underlying function.
8718//
8719Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8720 Value *Callee = CS.getCalledValue();
8721 const PointerType *PTy = cast<PointerType>(Callee->getType());
8722 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner58d74912008-03-12 17:45:29 +00008723 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008724
8725 // If the call already has the 'nest' attribute somewhere then give up -
8726 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner58d74912008-03-12 17:45:29 +00008727 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008728 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008729
8730 IntrinsicInst *Tramp =
8731 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8732
8733 Function *NestF =
8734 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8735 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8736 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8737
Chris Lattner58d74912008-03-12 17:45:29 +00008738 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8739 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008740 unsigned NestIdx = 1;
8741 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008742 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008743
8744 // Look for a parameter marked with the 'nest' attribute.
8745 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8746 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner58d74912008-03-12 17:45:29 +00008747 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008748 // Record the parameter type and any other attributes.
8749 NestTy = *I;
Chris Lattner58d74912008-03-12 17:45:29 +00008750 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008751 break;
8752 }
8753
8754 if (NestTy) {
8755 Instruction *Caller = CS.getInstruction();
8756 std::vector<Value*> NewArgs;
8757 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8758
Chris Lattner58d74912008-03-12 17:45:29 +00008759 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8760 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008761
Duncan Sandscdb6d922007-09-17 10:26:40 +00008762 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008763 // mean appending it. Likewise for attributes.
8764
8765 // Add any function result attributes.
Chris Lattner58d74912008-03-12 17:45:29 +00008766 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8767 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008768
Duncan Sandscdb6d922007-09-17 10:26:40 +00008769 {
8770 unsigned Idx = 1;
8771 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8772 do {
8773 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008774 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008775 Value *NestVal = Tramp->getOperand(3);
8776 if (NestVal->getType() != NestTy)
8777 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8778 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008779 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008780 }
8781
8782 if (I == E)
8783 break;
8784
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008785 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008786 NewArgs.push_back(*I);
Chris Lattner58d74912008-03-12 17:45:29 +00008787 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008788 NewAttrs.push_back
8789 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008790
8791 ++Idx, ++I;
8792 } while (1);
8793 }
8794
8795 // The trampoline may have been bitcast to a bogus type (FTy).
8796 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008797 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008798
Duncan Sandscdb6d922007-09-17 10:26:40 +00008799 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008800 NewTypes.reserve(FTy->getNumParams()+1);
8801
Duncan Sandscdb6d922007-09-17 10:26:40 +00008802 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008803 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008804 {
8805 unsigned Idx = 1;
8806 FunctionType::param_iterator I = FTy->param_begin(),
8807 E = FTy->param_end();
8808
8809 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008810 if (Idx == NestIdx)
8811 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008812 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008813
8814 if (I == E)
8815 break;
8816
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008817 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008818 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008819
8820 ++Idx, ++I;
8821 } while (1);
8822 }
8823
8824 // Replace the trampoline call with a direct call. Let the generic
8825 // code sort out any function type mismatches.
8826 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008827 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008828 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8829 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner58d74912008-03-12 17:45:29 +00008830 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +00008831
8832 Instruction *NewCaller;
8833 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8834 NewCaller = new InvokeInst(NewCallee,
8835 II->getNormalDest(), II->getUnwindDest(),
8836 NewArgs.begin(), NewArgs.end(),
8837 Caller->getName(), Caller);
8838 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008839 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008840 } else {
8841 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8842 Caller->getName(), Caller);
8843 if (cast<CallInst>(Caller)->isTailCall())
8844 cast<CallInst>(NewCaller)->setTailCall();
8845 cast<CallInst>(NewCaller)->
8846 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008847 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008848 }
8849 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8850 Caller->replaceAllUsesWith(NewCaller);
8851 Caller->eraseFromParent();
8852 RemoveFromWorkList(Caller);
8853 return 0;
8854 }
8855 }
8856
8857 // Replace the trampoline call with a direct call. Since there is no 'nest'
8858 // parameter, there is no need to adjust the argument list. Let the generic
8859 // code sort out any function type mismatches.
8860 Constant *NewCallee =
8861 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8862 CS.setCalledFunction(NewCallee);
8863 return CS.getInstruction();
8864}
8865
Chris Lattner7da52b22006-11-01 04:51:18 +00008866/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8867/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8868/// and a single binop.
8869Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8870 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008871 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8872 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008873 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008874 Value *LHSVal = FirstInst->getOperand(0);
8875 Value *RHSVal = FirstInst->getOperand(1);
8876
8877 const Type *LHSType = LHSVal->getType();
8878 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008879
8880 // Scan to see if all operands are the same opcode, all have one use, and all
8881 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008882 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008883 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008884 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008885 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008886 // types or GEP's with different index types.
8887 I->getOperand(0)->getType() != LHSType ||
8888 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008889 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008890
8891 // If they are CmpInst instructions, check their predicates
8892 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8893 if (cast<CmpInst>(I)->getPredicate() !=
8894 cast<CmpInst>(FirstInst)->getPredicate())
8895 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008896
8897 // Keep track of which operand needs a phi node.
8898 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8899 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008900 }
8901
Chris Lattner53738a42006-11-08 19:42:28 +00008902 // Otherwise, this is safe to transform, determine if it is profitable.
8903
8904 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8905 // Indexes are often folded into load/store instructions, so we don't want to
8906 // hide them behind a phi.
8907 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8908 return 0;
8909
Chris Lattner7da52b22006-11-01 04:51:18 +00008910 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008911 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008912 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008913 if (LHSVal == 0) {
8914 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8915 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8916 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008917 InsertNewInstBefore(NewLHS, PN);
8918 LHSVal = NewLHS;
8919 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008920
8921 if (RHSVal == 0) {
8922 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8923 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8924 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008925 InsertNewInstBefore(NewRHS, PN);
8926 RHSVal = NewRHS;
8927 }
8928
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008929 // Add all operands to the new PHIs.
8930 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8931 if (NewLHS) {
8932 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8933 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8934 }
8935 if (NewRHS) {
8936 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8937 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8938 }
8939 }
8940
Chris Lattner7da52b22006-11-01 04:51:18 +00008941 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008942 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008943 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8944 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8945 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008946 else {
8947 assert(isa<GetElementPtrInst>(FirstInst));
8948 return new GetElementPtrInst(LHSVal, RHSVal);
8949 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008950}
8951
Chris Lattner76c73142006-11-01 07:13:54 +00008952/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8953/// of the block that defines it. This means that it must be obvious the value
8954/// of the load is not changed from the point of the load to the end of the
8955/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008956///
8957/// Finally, it is safe, but not profitable, to sink a load targetting a
8958/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8959/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008960static bool isSafeToSinkLoad(LoadInst *L) {
8961 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8962
8963 for (++BBI; BBI != E; ++BBI)
8964 if (BBI->mayWriteToMemory())
8965 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008966
8967 // Check for non-address taken alloca. If not address-taken already, it isn't
8968 // profitable to do this xform.
8969 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8970 bool isAddressTaken = false;
8971 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8972 UI != E; ++UI) {
8973 if (isa<LoadInst>(UI)) continue;
8974 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8975 // If storing TO the alloca, then the address isn't taken.
8976 if (SI->getOperand(1) == AI) continue;
8977 }
8978 isAddressTaken = true;
8979 break;
8980 }
8981
8982 if (!isAddressTaken)
8983 return false;
8984 }
8985
Chris Lattner76c73142006-11-01 07:13:54 +00008986 return true;
8987}
8988
Chris Lattner9fe38862003-06-19 17:00:31 +00008989
Chris Lattnerbac32862004-11-14 19:13:23 +00008990// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8991// operator and they all are only used by the PHI, PHI together their
8992// inputs, and do the operation once, to the result of the PHI.
8993Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8994 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8995
8996 // Scan the instruction, looking for input operations that can be folded away.
8997 // If all input operands to the phi are the same instruction (e.g. a cast from
8998 // the same type or "+42") we can pull the operation through the PHI, reducing
8999 // code size and simplifying code.
9000 Constant *ConstantOp = 0;
9001 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00009002 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00009003 if (isa<CastInst>(FirstInst)) {
9004 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00009005 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009006 // Can fold binop, compare or shift here if the RHS is a constant,
9007 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00009008 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00009009 if (ConstantOp == 0)
9010 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00009011 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9012 isVolatile = LI->isVolatile();
9013 // We can't sink the load if the loaded value could be modified between the
9014 // load and the PHI.
9015 if (LI->getParent() != PN.getIncomingBlock(0) ||
9016 !isSafeToSinkLoad(LI))
9017 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00009018 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00009019 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00009020 return FoldPHIArgBinOpIntoPHI(PN);
9021 // Can't handle general GEPs yet.
9022 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009023 } else {
9024 return 0; // Cannot fold this operation.
9025 }
9026
9027 // Check to see if all arguments are the same operation.
9028 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9029 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9030 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00009031 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00009032 return 0;
9033 if (CastSrcTy) {
9034 if (I->getOperand(0)->getType() != CastSrcTy)
9035 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00009036 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009037 // We can't sink the load if the loaded value could be modified between
9038 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00009039 if (LI->isVolatile() != isVolatile ||
9040 LI->getParent() != PN.getIncomingBlock(i) ||
9041 !isSafeToSinkLoad(LI))
9042 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009043 } else if (I->getOperand(1) != ConstantOp) {
9044 return 0;
9045 }
9046 }
9047
9048 // Okay, they are all the same operation. Create a new PHI node of the
9049 // correct type, and PHI together all of the LHS's of the instructions.
9050 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
9051 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00009052 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00009053
9054 Value *InVal = FirstInst->getOperand(0);
9055 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00009056
9057 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00009058 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9059 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9060 if (NewInVal != InVal)
9061 InVal = 0;
9062 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9063 }
9064
9065 Value *PhiVal;
9066 if (InVal) {
9067 // The new PHI unions all of the same values together. This is really
9068 // common, so we handle it intelligently here for compile-time speed.
9069 PhiVal = InVal;
9070 delete NewPN;
9071 } else {
9072 InsertNewInstBefore(NewPN, PN);
9073 PhiVal = NewPN;
9074 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009075
Chris Lattnerbac32862004-11-14 19:13:23 +00009076 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00009077 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9078 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00009079 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00009080 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00009081 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00009082 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00009083 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9084 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9085 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00009086 else
Reid Spencer832254e2007-02-02 02:16:23 +00009087 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00009088 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00009089}
Chris Lattnera1be5662002-05-02 17:06:02 +00009090
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009091/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9092/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009093static bool DeadPHICycle(PHINode *PN,
9094 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009095 if (PN->use_empty()) return true;
9096 if (!PN->hasOneUse()) return false;
9097
9098 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00009099 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009100 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00009101
9102 // Don't scan crazily complex things.
9103 if (PotentiallyDeadPHIs.size() == 16)
9104 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009105
9106 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9107 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009108
Chris Lattnera3fd1c52005-01-17 05:10:15 +00009109 return false;
9110}
9111
Chris Lattnercf5008a2007-11-06 21:52:06 +00009112/// PHIsEqualValue - Return true if this phi node is always equal to
9113/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9114/// z = some value; x = phi (y, z); y = phi (x, z)
9115static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9116 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9117 // See if we already saw this PHI node.
9118 if (!ValueEqualPHIs.insert(PN))
9119 return true;
9120
9121 // Don't scan crazily complex things.
9122 if (ValueEqualPHIs.size() == 16)
9123 return false;
9124
9125 // Scan the operands to see if they are either phi nodes or are equal to
9126 // the value.
9127 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9128 Value *Op = PN->getIncomingValue(i);
9129 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9130 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9131 return false;
9132 } else if (Op != NonPhiInVal)
9133 return false;
9134 }
9135
9136 return true;
9137}
9138
9139
Chris Lattner473945d2002-05-06 18:06:38 +00009140// PHINode simplification
9141//
Chris Lattner7e708292002-06-25 16:13:24 +00009142Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009143 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009144 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009145
Owen Anderson7e057142006-07-10 22:03:18 +00009146 if (Value *V = PN.hasConstantValue())
9147 return ReplaceInstUsesWith(PN, V);
9148
Owen Anderson7e057142006-07-10 22:03:18 +00009149 // If all PHI operands are the same operation, pull them through the PHI,
9150 // reducing code size.
9151 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9152 PN.getIncomingValue(0)->hasOneUse())
9153 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9154 return Result;
9155
9156 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9157 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9158 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009159 if (PN.hasOneUse()) {
9160 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9161 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009162 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009163 PotentiallyDeadPHIs.insert(&PN);
9164 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9165 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9166 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009167
9168 // If this phi has a single use, and if that use just computes a value for
9169 // the next iteration of a loop, delete the phi. This occurs with unused
9170 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9171 // common case here is good because the only other things that catch this
9172 // are induction variable analysis (sometimes) and ADCE, which is only run
9173 // late.
9174 if (PHIUser->hasOneUse() &&
9175 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9176 PHIUser->use_back() == &PN) {
9177 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9178 }
9179 }
Owen Anderson7e057142006-07-10 22:03:18 +00009180
Chris Lattnercf5008a2007-11-06 21:52:06 +00009181 // We sometimes end up with phi cycles that non-obviously end up being the
9182 // same value, for example:
9183 // z = some value; x = phi (y, z); y = phi (x, z)
9184 // where the phi nodes don't necessarily need to be in the same block. Do a
9185 // quick check to see if the PHI node only contains a single non-phi value, if
9186 // so, scan to see if the phi cycle is actually equal to that value.
9187 {
9188 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9189 // Scan for the first non-phi operand.
9190 while (InValNo != NumOperandVals &&
9191 isa<PHINode>(PN.getIncomingValue(InValNo)))
9192 ++InValNo;
9193
9194 if (InValNo != NumOperandVals) {
9195 Value *NonPhiInVal = PN.getOperand(InValNo);
9196
9197 // Scan the rest of the operands to see if there are any conflicts, if so
9198 // there is no need to recursively scan other phis.
9199 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9200 Value *OpVal = PN.getIncomingValue(InValNo);
9201 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9202 break;
9203 }
9204
9205 // If we scanned over all operands, then we have one unique value plus
9206 // phi values. Scan PHI nodes to see if they all merge in each other or
9207 // the value.
9208 if (InValNo == NumOperandVals) {
9209 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9210 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9211 return ReplaceInstUsesWith(PN, NonPhiInVal);
9212 }
9213 }
9214 }
Chris Lattner60921c92003-12-19 05:58:40 +00009215 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009216}
9217
Reid Spencer17212df2006-12-12 09:18:51 +00009218static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9219 Instruction *InsertPoint,
9220 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009221 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9222 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009223 // We must cast correctly to the pointer type. Ensure that we
9224 // sign extend the integer value if it is smaller as this is
9225 // used for address computation.
9226 Instruction::CastOps opcode =
9227 (VTySize < PtrSize ? Instruction::SExt :
9228 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9229 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009230}
9231
Chris Lattnera1be5662002-05-02 17:06:02 +00009232
Chris Lattner7e708292002-06-25 16:13:24 +00009233Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009234 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009235 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009236 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009237 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009238 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009239
Chris Lattnere87597f2004-10-16 18:11:37 +00009240 if (isa<UndefValue>(GEP.getOperand(0)))
9241 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9242
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009243 bool HasZeroPointerIndex = false;
9244 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9245 HasZeroPointerIndex = C->isNullValue();
9246
9247 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009248 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009249
Chris Lattner28977af2004-04-05 01:30:19 +00009250 // Eliminate unneeded casts for indices.
9251 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009252
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009253 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009254 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009255 if (isa<SequentialType>(*GTI)) {
9256 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009257 if (CI->getOpcode() == Instruction::ZExt ||
9258 CI->getOpcode() == Instruction::SExt) {
9259 const Type *SrcTy = CI->getOperand(0)->getType();
9260 // We can eliminate a cast from i32 to i64 iff the target
9261 // is a 32-bit pointer target.
9262 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9263 MadeChange = true;
9264 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009265 }
9266 }
9267 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009268 // If we are using a wider index than needed for this platform, shrink it
9269 // to what we need. If the incoming value needs a cast instruction,
9270 // insert it. This explicit cast can make subsequent optimizations more
9271 // obvious.
9272 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009273 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009274 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009275 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009276 MadeChange = true;
9277 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009278 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9279 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009280 GEP.setOperand(i, Op);
9281 MadeChange = true;
9282 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009283 }
Chris Lattner28977af2004-04-05 01:30:19 +00009284 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009285 }
Chris Lattner28977af2004-04-05 01:30:19 +00009286 if (MadeChange) return &GEP;
9287
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009288 // If this GEP instruction doesn't move the pointer, and if the input operand
9289 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9290 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009291 if (GEP.hasAllZeroIndices()) {
9292 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9293 // If the bitcast is of an allocation, and the allocation will be
9294 // converted to match the type of the cast, don't touch this.
9295 if (isa<AllocationInst>(BCI->getOperand(0))) {
9296 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009297 if (Instruction *I = visitBitCast(*BCI)) {
9298 if (I != BCI) {
9299 I->takeName(BCI);
9300 BCI->getParent()->getInstList().insert(BCI, I);
9301 ReplaceInstUsesWith(*BCI, I);
9302 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009303 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009304 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009305 }
9306 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9307 }
9308 }
9309
Chris Lattner90ac28c2002-08-02 19:29:35 +00009310 // Combine Indices - If the source pointer to this getelementptr instruction
9311 // is a getelementptr instruction, combine the indices of the two
9312 // getelementptr instructions into a single instruction.
9313 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009314 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009315 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009316 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009317
9318 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009319 // Note that if our source is a gep chain itself that we wait for that
9320 // chain to be resolved before we perform this transformation. This
9321 // avoids us creating a TON of code in some cases.
9322 //
9323 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9324 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9325 return 0; // Wait until our source is folded to completion.
9326
Chris Lattner72588fc2007-02-15 22:48:32 +00009327 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009328
9329 // Find out whether the last index in the source GEP is a sequential idx.
9330 bool EndsWithSequential = false;
9331 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9332 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009333 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009334
Chris Lattner90ac28c2002-08-02 19:29:35 +00009335 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009336 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009337 // Replace: gep (gep %P, long B), long A, ...
9338 // With: T = long A+B; gep %P, T, ...
9339 //
Chris Lattner620ce142004-05-07 22:09:22 +00009340 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009341 if (SO1 == Constant::getNullValue(SO1->getType())) {
9342 Sum = GO1;
9343 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9344 Sum = SO1;
9345 } else {
9346 // If they aren't the same type, convert both to an integer of the
9347 // target's pointer size.
9348 if (SO1->getType() != GO1->getType()) {
9349 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009350 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009351 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009352 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009353 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009354 unsigned PS = TD->getPointerSizeInBits();
9355 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009356 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009357 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009358
Duncan Sands514ab342007-11-01 20:53:16 +00009359 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009360 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009361 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009362 } else {
9363 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009364 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9365 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009366 }
9367 }
9368 }
Chris Lattner620ce142004-05-07 22:09:22 +00009369 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9370 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9371 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009372 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9373 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009374 }
Chris Lattner28977af2004-04-05 01:30:19 +00009375 }
Chris Lattner620ce142004-05-07 22:09:22 +00009376
9377 // Recycle the GEP we already have if possible.
9378 if (SrcGEPOperands.size() == 2) {
9379 GEP.setOperand(0, SrcGEPOperands[0]);
9380 GEP.setOperand(1, Sum);
9381 return &GEP;
9382 } else {
9383 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9384 SrcGEPOperands.end()-1);
9385 Indices.push_back(Sum);
9386 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9387 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009388 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009389 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009390 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009391 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009392 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9393 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009394 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9395 }
9396
9397 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009398 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9399 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009400
Chris Lattner620ce142004-05-07 22:09:22 +00009401 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009402 // GEP of global variable. If all of the indices for this GEP are
9403 // constants, we can promote this to a constexpr instead of an instruction.
9404
9405 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009406 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009407 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9408 for (; I != E && isa<Constant>(*I); ++I)
9409 Indices.push_back(cast<Constant>(*I));
9410
9411 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009412 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9413 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009414
9415 // Replace all uses of the GEP with the new constexpr...
9416 return ReplaceInstUsesWith(GEP, CE);
9417 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009418 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009419 if (!isa<PointerType>(X->getType())) {
9420 // Not interesting. Source pointer must be a cast from pointer.
9421 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009422 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9423 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009424 //
9425 // This occurs when the program declares an array extern like "int X[];"
9426 //
9427 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9428 const PointerType *XTy = cast<PointerType>(X->getType());
9429 if (const ArrayType *XATy =
9430 dyn_cast<ArrayType>(XTy->getElementType()))
9431 if (const ArrayType *CATy =
9432 dyn_cast<ArrayType>(CPTy->getElementType()))
9433 if (CATy->getElementType() == XATy->getElementType()) {
9434 // At this point, we know that the cast source type is a pointer
9435 // to an array of the same type as the destination pointer
9436 // array. Because the array type is never stepped over (there
9437 // is a leading zero) we can fold the cast into this GEP.
9438 GEP.setOperand(0, X);
9439 return &GEP;
9440 }
9441 } else if (GEP.getNumOperands() == 2) {
9442 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009443 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9444 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009445 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9446 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9447 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009448 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9449 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009450 Value *Idx[2];
9451 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9452 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009453 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009454 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009455 // V and GEP are both pointer types --> BitCast
9456 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009457 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009458
9459 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009460 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009461 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009462 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009463
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009464 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009465 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009466 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009467
9468 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9469 // allow either a mul, shift, or constant here.
9470 Value *NewIdx = 0;
9471 ConstantInt *Scale = 0;
9472 if (ArrayEltSize == 1) {
9473 NewIdx = GEP.getOperand(1);
9474 Scale = ConstantInt::get(NewIdx->getType(), 1);
9475 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009476 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009477 Scale = CI;
9478 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9479 if (Inst->getOpcode() == Instruction::Shl &&
9480 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009481 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9482 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9483 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009484 NewIdx = Inst->getOperand(0);
9485 } else if (Inst->getOpcode() == Instruction::Mul &&
9486 isa<ConstantInt>(Inst->getOperand(1))) {
9487 Scale = cast<ConstantInt>(Inst->getOperand(1));
9488 NewIdx = Inst->getOperand(0);
9489 }
9490 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009491
Chris Lattner7835cdd2005-09-13 18:36:04 +00009492 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009493 // out, perform the transformation. Note, we don't know whether Scale is
9494 // signed or not. We'll use unsigned version of division/modulo
9495 // operation after making sure Scale doesn't have the sign bit set.
9496 if (Scale && Scale->getSExtValue() >= 0LL &&
9497 Scale->getZExtValue() % ArrayEltSize == 0) {
9498 Scale = ConstantInt::get(Scale->getType(),
9499 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009500 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009501 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009502 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009503 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9504 NewIdx = InsertNewInstBefore(Sc, GEP);
9505 }
9506
9507 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009508 Value *Idx[2];
9509 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9510 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009511 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009512 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009513 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9514 // The NewGEP must be pointer typed, so must the old one -> BitCast
9515 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009516 }
9517 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009518 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009519 }
9520
Chris Lattner8a2a3112001-12-14 16:52:21 +00009521 return 0;
9522}
9523
Chris Lattner0864acf2002-11-04 16:18:53 +00009524Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9525 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009526 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009527 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9528 const Type *NewTy =
9529 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009530 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009531
9532 // Create and insert the replacement instruction...
9533 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009534 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009535 else {
9536 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009537 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009538 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009539
9540 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009541
Chris Lattner0864acf2002-11-04 16:18:53 +00009542 // Scan to the end of the allocation instructions, to skip over a block of
9543 // allocas if possible...
9544 //
9545 BasicBlock::iterator It = New;
9546 while (isa<AllocationInst>(*It)) ++It;
9547
9548 // Now that I is pointing to the first non-allocation-inst in the block,
9549 // insert our getelementptr instruction...
9550 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009551 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009552 Value *Idx[2];
9553 Idx[0] = NullIdx;
9554 Idx[1] = NullIdx;
9555 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009556 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009557
9558 // Now make everything use the getelementptr instead of the original
9559 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009560 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009561 } else if (isa<UndefValue>(AI.getArraySize())) {
9562 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009563 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009564 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009565
9566 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9567 // Note that we only do this for alloca's, because malloc should allocate and
9568 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009569 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009570 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009571 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9572
Chris Lattner0864acf2002-11-04 16:18:53 +00009573 return 0;
9574}
9575
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009576Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9577 Value *Op = FI.getOperand(0);
9578
Chris Lattner17be6352004-10-18 02:59:09 +00009579 // free undef -> unreachable.
9580 if (isa<UndefValue>(Op)) {
9581 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009582 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009583 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009584 return EraseInstFromFunction(FI);
9585 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009586
Chris Lattner6160e852004-02-28 04:57:37 +00009587 // If we have 'free null' delete the instruction. This can happen in stl code
9588 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009589 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009590 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009591
9592 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9593 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9594 FI.setOperand(0, CI->getOperand(0));
9595 return &FI;
9596 }
9597
9598 // Change free (gep X, 0,0,0,0) into free(X)
9599 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9600 if (GEPI->hasAllZeroIndices()) {
9601 AddToWorkList(GEPI);
9602 FI.setOperand(0, GEPI->getOperand(0));
9603 return &FI;
9604 }
9605 }
9606
9607 // Change free(malloc) into nothing, if the malloc has a single use.
9608 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9609 if (MI->hasOneUse()) {
9610 EraseInstFromFunction(FI);
9611 return EraseInstFromFunction(*MI);
9612 }
Chris Lattner6160e852004-02-28 04:57:37 +00009613
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009614 return 0;
9615}
9616
9617
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009618/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009619static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009620 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009621 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009622 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009623
Devang Patel99db6ad2007-10-18 19:52:32 +00009624 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9625 // Instead of loading constant c string, use corresponding integer value
9626 // directly if string length is small enough.
9627 const std::string &Str = CE->getOperand(0)->getStringValue();
9628 if (!Str.empty()) {
9629 unsigned len = Str.length();
9630 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9631 unsigned numBits = Ty->getPrimitiveSizeInBits();
9632 // Replace LI with immediate integer store.
9633 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009634 APInt StrVal(numBits, 0);
9635 APInt SingleChar(numBits, 0);
9636 if (TD->isLittleEndian()) {
9637 for (signed i = len-1; i >= 0; i--) {
9638 SingleChar = (uint64_t) Str[i];
9639 StrVal = (StrVal << 8) | SingleChar;
9640 }
9641 } else {
9642 for (unsigned i = 0; i < len; i++) {
9643 SingleChar = (uint64_t) Str[i];
9644 StrVal = (StrVal << 8) | SingleChar;
9645 }
9646 // Append NULL at the end.
9647 SingleChar = 0;
9648 StrVal = (StrVal << 8) | SingleChar;
9649 }
9650 Value *NL = ConstantInt::get(StrVal);
9651 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009652 }
9653 }
9654 }
9655
Chris Lattnerb89e0712004-07-13 01:49:43 +00009656 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009657 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009658 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009659
Reid Spencer42230162007-01-22 05:51:25 +00009660 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009661 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009662 // If the source is an array, the code below will not succeed. Check to
9663 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9664 // constants.
9665 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9666 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9667 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009668 Value *Idxs[2];
9669 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9670 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009671 SrcTy = cast<PointerType>(CastOp->getType());
9672 SrcPTy = SrcTy->getElementType();
9673 }
9674
Reid Spencer42230162007-01-22 05:51:25 +00009675 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009676 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009677 // Do not allow turning this into a load of an integer, which is then
9678 // casted to a pointer, this pessimizes pointer analysis a lot.
9679 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009680 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9681 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009682
Chris Lattnerf9527852005-01-31 04:50:46 +00009683 // Okay, we are casting from one integer or pointer type to another of
9684 // the same size. Instead of casting the pointer before the load, cast
9685 // the result of the loaded value.
9686 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9687 CI->getName(),
9688 LI.isVolatile()),LI);
9689 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009690 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009691 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009692 }
9693 }
9694 return 0;
9695}
9696
Chris Lattnerc10aced2004-09-19 18:43:46 +00009697/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009698/// from this value cannot trap. If it is not obviously safe to load from the
9699/// specified pointer, we do a quick local scan of the basic block containing
9700/// ScanFrom, to determine if the address is already accessed.
9701static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009702 // If it is an alloca it is always safe to load from.
9703 if (isa<AllocaInst>(V)) return true;
9704
Duncan Sands46318cd2007-09-19 10:25:38 +00009705 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009706 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009707 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009708 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009709
9710 // Otherwise, be a little bit agressive by scanning the local block where we
9711 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009712 // from/to. If so, the previous load or store would have already trapped,
9713 // so there is no harm doing an extra load (also, CSE will later eliminate
9714 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009715 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9716
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009717 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009718 --BBI;
9719
9720 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9721 if (LI->getOperand(0) == V) return true;
9722 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9723 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009724
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009725 }
Chris Lattner8a375202004-09-19 19:18:10 +00009726 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009727}
9728
Chris Lattner8d2e8882007-08-11 18:48:48 +00009729/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9730/// until we find the underlying object a pointer is referring to or something
9731/// we don't understand. Note that the returned pointer may be offset from the
9732/// input, because we ignore GEP indices.
9733static Value *GetUnderlyingObject(Value *Ptr) {
9734 while (1) {
9735 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9736 if (CE->getOpcode() == Instruction::BitCast ||
9737 CE->getOpcode() == Instruction::GetElementPtr)
9738 Ptr = CE->getOperand(0);
9739 else
9740 return Ptr;
9741 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9742 Ptr = BCI->getOperand(0);
9743 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9744 Ptr = GEP->getOperand(0);
9745 } else {
9746 return Ptr;
9747 }
9748 }
9749}
9750
Chris Lattner833b8a42003-06-26 05:06:25 +00009751Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9752 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009753
Dan Gohman9941f742007-07-20 16:34:21 +00009754 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009755 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009756 if (KnownAlign > LI.getAlignment())
9757 LI.setAlignment(KnownAlign);
9758
Chris Lattner37366c12005-05-01 04:24:53 +00009759 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009760 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009761 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009762 return Res;
9763
9764 // None of the following transforms are legal for volatile loads.
9765 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009766
Chris Lattner62f254d2005-09-12 22:00:15 +00009767 if (&LI.getParent()->front() != &LI) {
9768 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009769 // If the instruction immediately before this is a store to the same
9770 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009771 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9772 if (SI->getOperand(1) == LI.getOperand(0))
9773 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009774 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9775 if (LIB->getOperand(0) == LI.getOperand(0))
9776 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009777 }
Chris Lattner37366c12005-05-01 04:24:53 +00009778
Christopher Lambb15147e2007-12-29 07:56:53 +00009779 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9780 const Value *GEPI0 = GEPI->getOperand(0);
9781 // TODO: Consider a target hook for valid address spaces for this xform.
9782 if (isa<ConstantPointerNull>(GEPI0) &&
9783 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009784 // Insert a new store to null instruction before the load to indicate
9785 // that this code is not reachable. We do this instead of inserting
9786 // an unreachable instruction directly because we cannot modify the
9787 // CFG.
9788 new StoreInst(UndefValue::get(LI.getType()),
9789 Constant::getNullValue(Op->getType()), &LI);
9790 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9791 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009792 }
Chris Lattner37366c12005-05-01 04:24:53 +00009793
Chris Lattnere87597f2004-10-16 18:11:37 +00009794 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009795 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009796 // TODO: Consider a target hook for valid address spaces for this xform.
9797 if (isa<UndefValue>(C) || (C->isNullValue() &&
9798 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009799 // Insert a new store to null instruction before the load to indicate that
9800 // this code is not reachable. We do this instead of inserting an
9801 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009802 new StoreInst(UndefValue::get(LI.getType()),
9803 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009804 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009805 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009806
Chris Lattnere87597f2004-10-16 18:11:37 +00009807 // Instcombine load (constant global) into the value loaded.
9808 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009809 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009810 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009811
Chris Lattnere87597f2004-10-16 18:11:37 +00009812 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009813 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00009814 if (CE->getOpcode() == Instruction::GetElementPtr) {
9815 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009816 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009817 if (Constant *V =
9818 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009819 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009820 if (CE->getOperand(0)->isNullValue()) {
9821 // Insert a new store to null instruction before the load to indicate
9822 // that this code is not reachable. We do this instead of inserting
9823 // an unreachable instruction directly because we cannot modify the
9824 // CFG.
9825 new StoreInst(UndefValue::get(LI.getType()),
9826 Constant::getNullValue(Op->getType()), &LI);
9827 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9828 }
9829
Reid Spencer3da59db2006-11-27 01:05:10 +00009830 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009831 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009832 return Res;
9833 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009834 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009835 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009836
9837 // If this load comes from anywhere in a constant global, and if the global
9838 // is all undef or zero, we know what it loads.
9839 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9840 if (GV->isConstant() && GV->hasInitializer()) {
9841 if (GV->getInitializer()->isNullValue())
9842 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9843 else if (isa<UndefValue>(GV->getInitializer()))
9844 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9845 }
9846 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009847
Chris Lattner37366c12005-05-01 04:24:53 +00009848 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009849 // Change select and PHI nodes to select values instead of addresses: this
9850 // helps alias analysis out a lot, allows many others simplifications, and
9851 // exposes redundancy in the code.
9852 //
9853 // Note that we cannot do the transformation unless we know that the
9854 // introduced loads cannot trap! Something like this is valid as long as
9855 // the condition is always false: load (select bool %C, int* null, int* %G),
9856 // but it would not be valid if we transformed it to load from null
9857 // unconditionally.
9858 //
9859 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9860 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009861 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9862 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009863 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009864 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009865 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009866 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009867 return new SelectInst(SI->getCondition(), V1, V2);
9868 }
9869
Chris Lattner684fe212004-09-23 15:46:00 +00009870 // load (select (cond, null, P)) -> load P
9871 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9872 if (C->isNullValue()) {
9873 LI.setOperand(0, SI->getOperand(2));
9874 return &LI;
9875 }
9876
9877 // load (select (cond, P, null)) -> load P
9878 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9879 if (C->isNullValue()) {
9880 LI.setOperand(0, SI->getOperand(1));
9881 return &LI;
9882 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009883 }
9884 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009885 return 0;
9886}
9887
Reid Spencer55af2b52007-01-19 21:20:31 +00009888/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009889/// when possible.
9890static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9891 User *CI = cast<User>(SI.getOperand(1));
9892 Value *CastOp = CI->getOperand(0);
9893
9894 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9895 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9896 const Type *SrcPTy = SrcTy->getElementType();
9897
Reid Spencer42230162007-01-22 05:51:25 +00009898 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009899 // If the source is an array, the code below will not succeed. Check to
9900 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9901 // constants.
9902 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9903 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9904 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009905 Value* Idxs[2];
9906 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9907 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009908 SrcTy = cast<PointerType>(CastOp->getType());
9909 SrcPTy = SrcTy->getElementType();
9910 }
9911
Reid Spencer67f827c2007-01-20 23:35:48 +00009912 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9913 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9914 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009915
9916 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009917 // the same size. Instead of casting the pointer before
9918 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009919 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009920 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009921 Instruction::CastOps opcode = Instruction::BitCast;
9922 const Type* CastSrcTy = SIOp0->getType();
9923 const Type* CastDstTy = SrcPTy;
9924 if (isa<PointerType>(CastDstTy)) {
9925 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009926 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009927 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009928 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009929 opcode = Instruction::PtrToInt;
9930 }
9931 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009932 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009933 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009934 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009935 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9936 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009937 return new StoreInst(NewCast, CastOp);
9938 }
9939 }
9940 }
9941 return 0;
9942}
9943
Chris Lattner2f503e62005-01-31 05:36:43 +00009944Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9945 Value *Val = SI.getOperand(0);
9946 Value *Ptr = SI.getOperand(1);
9947
9948 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009949 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009950 ++NumCombined;
9951 return 0;
9952 }
Chris Lattner836692d2007-01-15 06:51:56 +00009953
9954 // If the RHS is an alloca with a single use, zapify the store, making the
9955 // alloca dead.
9956 if (Ptr->hasOneUse()) {
9957 if (isa<AllocaInst>(Ptr)) {
9958 EraseInstFromFunction(SI);
9959 ++NumCombined;
9960 return 0;
9961 }
9962
9963 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9964 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9965 GEP->getOperand(0)->hasOneUse()) {
9966 EraseInstFromFunction(SI);
9967 ++NumCombined;
9968 return 0;
9969 }
9970 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009971
Dan Gohman9941f742007-07-20 16:34:21 +00009972 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009973 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009974 if (KnownAlign > SI.getAlignment())
9975 SI.setAlignment(KnownAlign);
9976
Chris Lattner9ca96412006-02-08 03:25:32 +00009977 // Do really simple DSE, to catch cases where there are several consequtive
9978 // stores to the same location, separated by a few arithmetic operations. This
9979 // situation often occurs with bitfield accesses.
9980 BasicBlock::iterator BBI = &SI;
9981 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9982 --ScanInsts) {
9983 --BBI;
9984
9985 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9986 // Prev store isn't volatile, and stores to the same location?
9987 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9988 ++NumDeadStore;
9989 ++BBI;
9990 EraseInstFromFunction(*PrevSI);
9991 continue;
9992 }
9993 break;
9994 }
9995
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009996 // If this is a load, we have to stop. However, if the loaded value is from
9997 // the pointer we're loading and is producing the pointer we're storing,
9998 // then *this* store is dead (X = load P; store X -> P).
9999 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +000010000 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010001 EraseInstFromFunction(SI);
10002 ++NumCombined;
10003 return 0;
10004 }
10005 // Otherwise, this is a load from some other location. Stores before it
10006 // may not be dead.
10007 break;
10008 }
10009
Chris Lattner9ca96412006-02-08 03:25:32 +000010010 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +000010011 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000010012 break;
10013 }
10014
10015
10016 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000010017
10018 // store X, null -> turns into 'unreachable' in SimplifyCFG
10019 if (isa<ConstantPointerNull>(Ptr)) {
10020 if (!isa<UndefValue>(Val)) {
10021 SI.setOperand(0, UndefValue::get(Val->getType()));
10022 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +000010023 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000010024 ++NumCombined;
10025 }
10026 return 0; // Do not modify these!
10027 }
10028
10029 // store undef, Ptr -> noop
10030 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000010031 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000010032 ++NumCombined;
10033 return 0;
10034 }
10035
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010036 // If the pointer destination is a cast, see if we can fold the cast into the
10037 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000010038 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010039 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10040 return Res;
10041 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000010042 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000010043 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10044 return Res;
10045
Chris Lattner408902b2005-09-12 23:23:25 +000010046
10047 // If this store is the last instruction in the basic block, and if the block
10048 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +000010049 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +000010050 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010051 if (BI->isUnconditional())
10052 if (SimplifyStoreAtEndOfBlock(SI))
10053 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000010054
Chris Lattner2f503e62005-01-31 05:36:43 +000010055 return 0;
10056}
10057
Chris Lattner3284d1f2007-04-15 00:07:55 +000010058/// SimplifyStoreAtEndOfBlock - Turn things like:
10059/// if () { *P = v1; } else { *P = v2 }
10060/// into a phi node with a store in the successor.
10061///
Chris Lattner31755a02007-04-15 01:02:18 +000010062/// Simplify things like:
10063/// *P = v1; if () { *P = v2; }
10064/// into a phi node with a store in the successor.
10065///
Chris Lattner3284d1f2007-04-15 00:07:55 +000010066bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10067 BasicBlock *StoreBB = SI.getParent();
10068
10069 // Check to see if the successor block has exactly two incoming edges. If
10070 // so, see if the other predecessor contains a store to the same location.
10071 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000010072 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000010073
10074 // Determine whether Dest has exactly two predecessors and, if so, compute
10075 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000010076 pred_iterator PI = pred_begin(DestBB);
10077 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010078 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000010079 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010080 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000010081 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010082 return false;
10083
10084 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000010085 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000010086 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000010087 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000010088 }
Chris Lattner31755a02007-04-15 01:02:18 +000010089 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000010090 return false;
10091
10092
Chris Lattner31755a02007-04-15 01:02:18 +000010093 // Verify that the other block ends in a branch and is not otherwise empty.
10094 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010095 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000010096 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000010097 return false;
10098
Chris Lattner31755a02007-04-15 01:02:18 +000010099 // If the other block ends in an unconditional branch, check for the 'if then
10100 // else' case. there is an instruction before the branch.
10101 StoreInst *OtherStore = 0;
10102 if (OtherBr->isUnconditional()) {
10103 // If this isn't a store, or isn't a store to the same location, bail out.
10104 --BBI;
10105 OtherStore = dyn_cast<StoreInst>(BBI);
10106 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10107 return false;
10108 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000010109 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000010110 // destinations is StoreBB, then we have the if/then case.
10111 if (OtherBr->getSuccessor(0) != StoreBB &&
10112 OtherBr->getSuccessor(1) != StoreBB)
10113 return false;
10114
10115 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000010116 // if/then triangle. See if there is a store to the same ptr as SI that
10117 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000010118 for (;; --BBI) {
10119 // Check to see if we find the matching store.
10120 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10121 if (OtherStore->getOperand(1) != SI.getOperand(1))
10122 return false;
10123 break;
10124 }
Chris Lattnerd717c182007-05-05 22:32:24 +000010125 // If we find something that may be using the stored value, or if we run
10126 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +000010127 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10128 BBI == OtherBB->begin())
10129 return false;
10130 }
10131
10132 // In order to eliminate the store in OtherBr, we have to
10133 // make sure nothing reads the stored value in StoreBB.
10134 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10135 // FIXME: This should really be AA driven.
10136 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10137 return false;
10138 }
10139 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010140
Chris Lattner31755a02007-04-15 01:02:18 +000010141 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010142 Value *MergedVal = OtherStore->getOperand(0);
10143 if (MergedVal != SI.getOperand(0)) {
10144 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10145 PN->reserveOperandSpace(2);
10146 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010147 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10148 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010149 }
10150
10151 // Advance to a place where it is safe to insert the new store and
10152 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010153 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010154 while (isa<PHINode>(BBI)) ++BBI;
10155 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10156 OtherStore->isVolatile()), *BBI);
10157
10158 // Nuke the old stores.
10159 EraseInstFromFunction(SI);
10160 EraseInstFromFunction(*OtherStore);
10161 ++NumCombined;
10162 return true;
10163}
10164
Chris Lattner2f503e62005-01-31 05:36:43 +000010165
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010166Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10167 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010168 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010169 BasicBlock *TrueDest;
10170 BasicBlock *FalseDest;
10171 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10172 !isa<Constant>(X)) {
10173 // Swap Destinations and condition...
10174 BI.setCondition(X);
10175 BI.setSuccessor(0, FalseDest);
10176 BI.setSuccessor(1, TrueDest);
10177 return &BI;
10178 }
10179
Reid Spencere4d87aa2006-12-23 06:05:41 +000010180 // Cannonicalize fcmp_one -> fcmp_oeq
10181 FCmpInst::Predicate FPred; Value *Y;
10182 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10183 TrueDest, FalseDest)))
10184 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10185 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10186 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010187 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010188 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10189 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010190 // Swap Destinations and condition...
10191 BI.setCondition(NewSCC);
10192 BI.setSuccessor(0, FalseDest);
10193 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010194 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010195 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010196 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010197 return &BI;
10198 }
10199
10200 // Cannonicalize icmp_ne -> icmp_eq
10201 ICmpInst::Predicate IPred;
10202 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10203 TrueDest, FalseDest)))
10204 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10205 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10206 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10207 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010208 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010209 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10210 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010211 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010212 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010213 BI.setSuccessor(0, FalseDest);
10214 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010215 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010216 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010217 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010218 return &BI;
10219 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010220
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010221 return 0;
10222}
Chris Lattner0864acf2002-11-04 16:18:53 +000010223
Chris Lattner46238a62004-07-03 00:26:11 +000010224Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10225 Value *Cond = SI.getCondition();
10226 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10227 if (I->getOpcode() == Instruction::Add)
10228 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10229 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10230 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010231 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010232 AddRHS));
10233 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010234 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010235 return &SI;
10236 }
10237 }
10238 return 0;
10239}
10240
Chris Lattner220b0cf2006-03-05 00:22:33 +000010241/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10242/// is to leave as a vector operation.
10243static bool CheapToScalarize(Value *V, bool isConstant) {
10244 if (isa<ConstantAggregateZero>(V))
10245 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010246 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010247 if (isConstant) return true;
10248 // If all elts are the same, we can extract.
10249 Constant *Op0 = C->getOperand(0);
10250 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10251 if (C->getOperand(i) != Op0)
10252 return false;
10253 return true;
10254 }
10255 Instruction *I = dyn_cast<Instruction>(V);
10256 if (!I) return false;
10257
10258 // Insert element gets simplified to the inserted element or is deleted if
10259 // this is constant idx extract element and its a constant idx insertelt.
10260 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10261 isa<ConstantInt>(I->getOperand(2)))
10262 return true;
10263 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10264 return true;
10265 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10266 if (BO->hasOneUse() &&
10267 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10268 CheapToScalarize(BO->getOperand(1), isConstant)))
10269 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010270 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10271 if (CI->hasOneUse() &&
10272 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10273 CheapToScalarize(CI->getOperand(1), isConstant)))
10274 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010275
10276 return false;
10277}
10278
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010279/// Read and decode a shufflevector mask.
10280///
10281/// It turns undef elements into values that are larger than the number of
10282/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010283static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10284 unsigned NElts = SVI->getType()->getNumElements();
10285 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10286 return std::vector<unsigned>(NElts, 0);
10287 if (isa<UndefValue>(SVI->getOperand(2)))
10288 return std::vector<unsigned>(NElts, 2*NElts);
10289
10290 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010291 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010292 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10293 if (isa<UndefValue>(CP->getOperand(i)))
10294 Result.push_back(NElts*2); // undef -> 8
10295 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010296 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010297 return Result;
10298}
10299
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010300/// FindScalarElement - Given a vector and an element number, see if the scalar
10301/// value is already around as a register, for example if it were inserted then
10302/// extracted from the vector.
10303static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010304 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10305 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010306 unsigned Width = PTy->getNumElements();
10307 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010308 return UndefValue::get(PTy->getElementType());
10309
10310 if (isa<UndefValue>(V))
10311 return UndefValue::get(PTy->getElementType());
10312 else if (isa<ConstantAggregateZero>(V))
10313 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010314 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010315 return CP->getOperand(EltNo);
10316 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10317 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010318 if (!isa<ConstantInt>(III->getOperand(2)))
10319 return 0;
10320 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010321
10322 // If this is an insert to the element we are looking for, return the
10323 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010324 if (EltNo == IIElt)
10325 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010326
10327 // Otherwise, the insertelement doesn't modify the value, recurse on its
10328 // vector input.
10329 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010330 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010331 unsigned InEl = getShuffleMask(SVI)[EltNo];
10332 if (InEl < Width)
10333 return FindScalarElement(SVI->getOperand(0), InEl);
10334 else if (InEl < Width*2)
10335 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10336 else
10337 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010338 }
10339
10340 // Otherwise, we don't know.
10341 return 0;
10342}
10343
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010344Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010345
Dan Gohman07a96762007-07-16 14:29:03 +000010346 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010347 if (isa<UndefValue>(EI.getOperand(0)))
10348 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10349
Dan Gohman07a96762007-07-16 14:29:03 +000010350 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010351 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10352 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10353
Reid Spencer9d6565a2007-02-15 02:26:10 +000010354 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010355 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010356 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010357 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010358 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010359 if (C->getOperand(i) != op0) {
10360 op0 = 0;
10361 break;
10362 }
10363 if (op0)
10364 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010365 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010366
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010367 // If extracting a specified index from the vector, see if we can recursively
10368 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010369 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010370 unsigned IndexVal = IdxC->getZExtValue();
10371 unsigned VectorWidth =
10372 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10373
10374 // If this is extracting an invalid index, turn this into undef, to avoid
10375 // crashing the code below.
10376 if (IndexVal >= VectorWidth)
10377 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10378
Chris Lattner867b99f2006-10-05 06:55:50 +000010379 // This instruction only demands the single element from the input vector.
10380 // If the input vector has a single use, simplify it based on this use
10381 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010382 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010383 uint64_t UndefElts;
10384 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010385 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010386 UndefElts)) {
10387 EI.setOperand(0, V);
10388 return &EI;
10389 }
10390 }
10391
Reid Spencerb83eb642006-10-20 07:07:24 +000010392 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010393 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010394
10395 // If the this extractelement is directly using a bitcast from a vector of
10396 // the same number of elements, see if we can find the source element from
10397 // it. In this case, we will end up needing to bitcast the scalars.
10398 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10399 if (const VectorType *VT =
10400 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10401 if (VT->getNumElements() == VectorWidth)
10402 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10403 return new BitCastInst(Elt, EI.getType());
10404 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010405 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010406
Chris Lattner73fa49d2006-05-25 22:53:38 +000010407 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010408 if (I->hasOneUse()) {
10409 // Push extractelement into predecessor operation if legal and
10410 // profitable to do so
10411 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010412 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10413 if (CheapToScalarize(BO, isConstantElt)) {
10414 ExtractElementInst *newEI0 =
10415 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10416 EI.getName()+".lhs");
10417 ExtractElementInst *newEI1 =
10418 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10419 EI.getName()+".rhs");
10420 InsertNewInstBefore(newEI0, EI);
10421 InsertNewInstBefore(newEI1, EI);
10422 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10423 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010424 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010425 unsigned AS =
10426 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010427 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10428 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010429 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010430 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010431 InsertNewInstBefore(GEP, EI);
10432 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010433 }
10434 }
10435 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10436 // Extracting the inserted element?
10437 if (IE->getOperand(2) == EI.getOperand(1))
10438 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10439 // If the inserted and extracted elements are constants, they must not
10440 // be the same value, extract from the pre-inserted value instead.
10441 if (isa<Constant>(IE->getOperand(2)) &&
10442 isa<Constant>(EI.getOperand(1))) {
10443 AddUsesToWorkList(EI);
10444 EI.setOperand(0, IE->getOperand(0));
10445 return &EI;
10446 }
10447 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10448 // If this is extracting an element from a shufflevector, figure out where
10449 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010450 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10451 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010452 Value *Src;
10453 if (SrcIdx < SVI->getType()->getNumElements())
10454 Src = SVI->getOperand(0);
10455 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10456 SrcIdx -= SVI->getType()->getNumElements();
10457 Src = SVI->getOperand(1);
10458 } else {
10459 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010460 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010461 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010462 }
10463 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010464 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010465 return 0;
10466}
10467
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010468/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10469/// elements from either LHS or RHS, return the shuffle mask and true.
10470/// Otherwise, return false.
10471static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10472 std::vector<Constant*> &Mask) {
10473 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10474 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010475 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010476
10477 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010478 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010479 return true;
10480 } else if (V == LHS) {
10481 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010482 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010483 return true;
10484 } else if (V == RHS) {
10485 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010486 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010487 return true;
10488 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10489 // If this is an insert of an extract from some other vector, include it.
10490 Value *VecOp = IEI->getOperand(0);
10491 Value *ScalarOp = IEI->getOperand(1);
10492 Value *IdxOp = IEI->getOperand(2);
10493
Chris Lattnerd929f062006-04-27 21:14:21 +000010494 if (!isa<ConstantInt>(IdxOp))
10495 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010496 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010497
10498 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10499 // Okay, we can handle this if the vector we are insertinting into is
10500 // transitively ok.
10501 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10502 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010503 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010504 return true;
10505 }
10506 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10507 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010508 EI->getOperand(0)->getType() == V->getType()) {
10509 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010510 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010511
10512 // This must be extracting from either LHS or RHS.
10513 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10514 // Okay, we can handle this if the vector we are insertinting into is
10515 // transitively ok.
10516 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10517 // If so, update the mask to reflect the inserted value.
10518 if (EI->getOperand(0) == LHS) {
10519 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010520 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010521 } else {
10522 assert(EI->getOperand(0) == RHS);
10523 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010524 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010525
10526 }
10527 return true;
10528 }
10529 }
10530 }
10531 }
10532 }
10533 // TODO: Handle shufflevector here!
10534
10535 return false;
10536}
10537
10538/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10539/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10540/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010541static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010542 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010543 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010544 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010545 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010546 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010547
10548 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010549 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010550 return V;
10551 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010552 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010553 return V;
10554 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10555 // If this is an insert of an extract from some other vector, include it.
10556 Value *VecOp = IEI->getOperand(0);
10557 Value *ScalarOp = IEI->getOperand(1);
10558 Value *IdxOp = IEI->getOperand(2);
10559
10560 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10561 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10562 EI->getOperand(0)->getType() == V->getType()) {
10563 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010564 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10565 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010566
10567 // Either the extracted from or inserted into vector must be RHSVec,
10568 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010569 if (EI->getOperand(0) == RHS || RHS == 0) {
10570 RHS = EI->getOperand(0);
10571 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010572 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010573 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010574 return V;
10575 }
10576
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010577 if (VecOp == RHS) {
10578 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010579 // Everything but the extracted element is replaced with the RHS.
10580 for (unsigned i = 0; i != NumElts; ++i) {
10581 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010582 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010583 }
10584 return V;
10585 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010586
10587 // If this insertelement is a chain that comes from exactly these two
10588 // vectors, return the vector and the effective shuffle.
10589 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10590 return EI->getOperand(0);
10591
Chris Lattnerefb47352006-04-15 01:39:45 +000010592 }
10593 }
10594 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010595 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010596
10597 // Otherwise, can't do anything fancy. Return an identity vector.
10598 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010599 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010600 return V;
10601}
10602
10603Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10604 Value *VecOp = IE.getOperand(0);
10605 Value *ScalarOp = IE.getOperand(1);
10606 Value *IdxOp = IE.getOperand(2);
10607
Chris Lattner599ded12007-04-09 01:11:16 +000010608 // Inserting an undef or into an undefined place, remove this.
10609 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10610 ReplaceInstUsesWith(IE, VecOp);
10611
Chris Lattnerefb47352006-04-15 01:39:45 +000010612 // If the inserted element was extracted from some other vector, and if the
10613 // indexes are constant, try to turn this into a shufflevector operation.
10614 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10615 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10616 EI->getOperand(0)->getType() == IE.getType()) {
10617 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010618 unsigned ExtractedIdx =
10619 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010620 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010621
10622 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10623 return ReplaceInstUsesWith(IE, VecOp);
10624
10625 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10626 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10627
10628 // If we are extracting a value from a vector, then inserting it right
10629 // back into the same place, just use the input vector.
10630 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10631 return ReplaceInstUsesWith(IE, VecOp);
10632
10633 // We could theoretically do this for ANY input. However, doing so could
10634 // turn chains of insertelement instructions into a chain of shufflevector
10635 // instructions, and right now we do not merge shufflevectors. As such,
10636 // only do this in a situation where it is clear that there is benefit.
10637 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10638 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10639 // the values of VecOp, except then one read from EIOp0.
10640 // Build a new shuffle mask.
10641 std::vector<Constant*> Mask;
10642 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010643 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010644 else {
10645 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010646 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010647 NumVectorElts));
10648 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010649 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010650 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010651 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010652 }
10653
10654 // If this insertelement isn't used by some other insertelement, turn it
10655 // (and any insertelements it points to), into one big shuffle.
10656 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10657 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010658 Value *RHS = 0;
10659 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10660 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10661 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010662 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010663 }
10664 }
10665 }
10666
10667 return 0;
10668}
10669
10670
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010671Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10672 Value *LHS = SVI.getOperand(0);
10673 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010674 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010675
10676 bool MadeChange = false;
10677
Chris Lattner867b99f2006-10-05 06:55:50 +000010678 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010679 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010680 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10681
Chris Lattnere4929dd2007-01-05 07:36:08 +000010682 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010683 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010684 if (isa<UndefValue>(SVI.getOperand(1))) {
10685 // Scan to see if there are any references to the RHS. If so, replace them
10686 // with undef element refs and set MadeChange to true.
10687 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10688 if (Mask[i] >= e && Mask[i] != 2*e) {
10689 Mask[i] = 2*e;
10690 MadeChange = true;
10691 }
10692 }
10693
10694 if (MadeChange) {
10695 // Remap any references to RHS to use LHS.
10696 std::vector<Constant*> Elts;
10697 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10698 if (Mask[i] == 2*e)
10699 Elts.push_back(UndefValue::get(Type::Int32Ty));
10700 else
10701 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10702 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010703 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010704 }
10705 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010706
Chris Lattner863bcff2006-05-25 23:48:38 +000010707 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10708 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10709 if (LHS == RHS || isa<UndefValue>(LHS)) {
10710 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010711 // shuffle(undef,undef,mask) -> undef.
10712 return ReplaceInstUsesWith(SVI, LHS);
10713 }
10714
Chris Lattner863bcff2006-05-25 23:48:38 +000010715 // Remap any references to RHS to use LHS.
10716 std::vector<Constant*> Elts;
10717 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010718 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010719 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010720 else {
10721 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10722 (Mask[i] < e && isa<UndefValue>(LHS)))
10723 Mask[i] = 2*e; // Turn into undef.
10724 else
10725 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010726 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010727 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010728 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010729 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010730 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010731 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010732 LHS = SVI.getOperand(0);
10733 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010734 MadeChange = true;
10735 }
10736
Chris Lattner7b2e27922006-05-26 00:29:06 +000010737 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010738 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010739
Chris Lattner863bcff2006-05-25 23:48:38 +000010740 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10741 if (Mask[i] >= e*2) continue; // Ignore undef values.
10742 // Is this an identity shuffle of the LHS value?
10743 isLHSID &= (Mask[i] == i);
10744
10745 // Is this an identity shuffle of the RHS value?
10746 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010747 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010748
Chris Lattner863bcff2006-05-25 23:48:38 +000010749 // Eliminate identity shuffles.
10750 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10751 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010752
Chris Lattner7b2e27922006-05-26 00:29:06 +000010753 // If the LHS is a shufflevector itself, see if we can combine it with this
10754 // one without producing an unusual shuffle. Here we are really conservative:
10755 // we are absolutely afraid of producing a shuffle mask not in the input
10756 // program, because the code gen may not be smart enough to turn a merged
10757 // shuffle into two specific shuffles: it may produce worse code. As such,
10758 // we only merge two shuffles if the result is one of the two input shuffle
10759 // masks. In this case, merging the shuffles just removes one instruction,
10760 // which we know is safe. This is good for things like turning:
10761 // (splat(splat)) -> splat.
10762 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10763 if (isa<UndefValue>(RHS)) {
10764 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10765
10766 std::vector<unsigned> NewMask;
10767 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10768 if (Mask[i] >= 2*e)
10769 NewMask.push_back(2*e);
10770 else
10771 NewMask.push_back(LHSMask[Mask[i]]);
10772
10773 // If the result mask is equal to the src shuffle or this shuffle mask, do
10774 // the replacement.
10775 if (NewMask == LHSMask || NewMask == Mask) {
10776 std::vector<Constant*> Elts;
10777 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10778 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010779 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010780 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010781 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010782 }
10783 }
10784 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10785 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010786 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010787 }
10788 }
10789 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010790
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010791 return MadeChange ? &SVI : 0;
10792}
10793
10794
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010795
Chris Lattnerea1c4542004-12-08 23:43:58 +000010796
10797/// TryToSinkInstruction - Try to move the specified instruction from its
10798/// current block into the beginning of DestBlock, which can only happen if it's
10799/// safe to move the instruction past all of the instructions between it and the
10800/// end of its block.
10801static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10802 assert(I->hasOneUse() && "Invariants didn't hold!");
10803
Chris Lattner108e9022005-10-27 17:13:11 +000010804 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10805 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010806
Chris Lattnerea1c4542004-12-08 23:43:58 +000010807 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010808 if (isa<AllocaInst>(I) && I->getParent() ==
10809 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010810 return false;
10811
Chris Lattner96a52a62004-12-09 07:14:34 +000010812 // We can only sink load instructions if there is nothing between the load and
10813 // the end of block that could change the value.
10814 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010815 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10816 Scan != E; ++Scan)
10817 if (Scan->mayWriteToMemory())
10818 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010819 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010820
10821 BasicBlock::iterator InsertPos = DestBlock->begin();
10822 while (isa<PHINode>(InsertPos)) ++InsertPos;
10823
Chris Lattner4bc5f802005-08-08 19:11:57 +000010824 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010825 ++NumSunkInst;
10826 return true;
10827}
10828
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010829
10830/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10831/// all reachable code to the worklist.
10832///
10833/// This has a couple of tricks to make the code faster and more powerful. In
10834/// particular, we constant fold and DCE instructions as we go, to avoid adding
10835/// them to the worklist (this significantly speeds up instcombine on code where
10836/// many instructions are dead or constant). Additionally, if we find a branch
10837/// whose condition is a known constant, we only visit the reachable successors.
10838///
10839static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010840 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010841 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010842 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010843 std::vector<BasicBlock*> Worklist;
10844 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010845
Chris Lattner2c7718a2007-03-23 19:17:18 +000010846 while (!Worklist.empty()) {
10847 BB = Worklist.back();
10848 Worklist.pop_back();
10849
10850 // We have now visited this block! If we've already been here, ignore it.
10851 if (!Visited.insert(BB)) continue;
10852
10853 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10854 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010855
Chris Lattner2c7718a2007-03-23 19:17:18 +000010856 // DCE instruction if trivially dead.
10857 if (isInstructionTriviallyDead(Inst)) {
10858 ++NumDeadInst;
10859 DOUT << "IC: DCE: " << *Inst;
10860 Inst->eraseFromParent();
10861 continue;
10862 }
10863
10864 // ConstantProp instruction if trivially constant.
10865 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10866 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10867 Inst->replaceAllUsesWith(C);
10868 ++NumConstProp;
10869 Inst->eraseFromParent();
10870 continue;
10871 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010872
Chris Lattner2c7718a2007-03-23 19:17:18 +000010873 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010874 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010875
10876 // Recursively visit successors. If this is a branch or switch on a
10877 // constant, only visit the reachable successor.
Nick Lewycky91436992008-03-09 08:50:23 +000010878 if (BB->getUnwindDest())
10879 Worklist.push_back(BB->getUnwindDest());
Chris Lattner2c7718a2007-03-23 19:17:18 +000010880 TerminatorInst *TI = BB->getTerminator();
10881 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10882 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10883 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000010884 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
10885 if (ReachableBB != BB->getUnwindDest())
10886 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010887 continue;
10888 }
10889 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10890 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10891 // See if this is an explicit destination.
10892 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10893 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000010894 BasicBlock *ReachableBB = SI->getSuccessor(i);
10895 if (ReachableBB != BB->getUnwindDest())
10896 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000010897 continue;
10898 }
10899
10900 // Otherwise it is the default destination.
10901 Worklist.push_back(SI->getSuccessor(0));
10902 continue;
10903 }
10904 }
10905
10906 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10907 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010908 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010909}
10910
Chris Lattnerec9c3582007-03-03 02:04:50 +000010911bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010912 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010913 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010914
10915 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10916 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010917
Chris Lattnerb3d59702005-07-07 20:40:38 +000010918 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010919 // Do a depth-first traversal of the function, populate the worklist with
10920 // the reachable instructions. Ignore blocks that are not reachable. Keep
10921 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010922 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010923 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010924
Chris Lattnerb3d59702005-07-07 20:40:38 +000010925 // Do a quick scan over the function. If we find any blocks that are
10926 // unreachable, remove any instructions inside of them. This prevents
10927 // the instcombine code from having to deal with some bad special cases.
10928 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10929 if (!Visited.count(BB)) {
10930 Instruction *Term = BB->getTerminator();
10931 while (Term != BB->begin()) { // Remove instrs bottom-up
10932 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010933
Bill Wendlingb7427032006-11-26 09:46:52 +000010934 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010935 ++NumDeadInst;
10936
10937 if (!I->use_empty())
10938 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10939 I->eraseFromParent();
10940 }
10941 }
10942 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010943
Chris Lattnerdbab3862007-03-02 21:28:56 +000010944 while (!Worklist.empty()) {
10945 Instruction *I = RemoveOneFromWorkList();
10946 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010947
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010948 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010949 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010950 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010951 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010952 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010953 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010954
Bill Wendlingb7427032006-11-26 09:46:52 +000010955 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010956
10957 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010958 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010959 continue;
10960 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010961
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010962 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010963 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010964 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010965
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010966 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010967 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010968 ReplaceInstUsesWith(*I, C);
10969
Chris Lattner62b14df2002-09-02 04:59:56 +000010970 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010971 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010972 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010973 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010974 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010975
Chris Lattnerea1c4542004-12-08 23:43:58 +000010976 // See if we can trivially sink this instruction to a successor basic block.
10977 if (I->hasOneUse()) {
10978 BasicBlock *BB = I->getParent();
10979 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10980 if (UserParent != BB) {
10981 bool UserIsSuccessor = false;
10982 // See if the user is one of our successors.
10983 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10984 if (*SI == UserParent) {
10985 UserIsSuccessor = true;
10986 break;
10987 }
10988
10989 // If the user is one of our immediate successors, and if that successor
10990 // only has us as a predecessors (we'd have to split the critical edge
10991 // otherwise), we can keep going.
10992 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10993 next(pred_begin(UserParent)) == pred_end(UserParent))
10994 // Okay, the CFG is simple enough, try to sink this instruction.
10995 Changed |= TryToSinkInstruction(I, UserParent);
10996 }
10997 }
10998
Chris Lattner8a2a3112001-12-14 16:52:21 +000010999 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000011000#ifndef NDEBUG
11001 std::string OrigI;
11002#endif
11003 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000011004 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000011005 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011006 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011007 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000011008 DOUT << "IC: Old = " << *I
11009 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000011010
Chris Lattnerf523d062004-06-09 05:08:07 +000011011 // Everything uses the new instruction now.
11012 I->replaceAllUsesWith(Result);
11013
11014 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011015 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000011016 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011017
Chris Lattner6934a042007-02-11 01:23:03 +000011018 // Move the name to the new instruction first.
11019 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011020
11021 // Insert the new instruction into the basic block...
11022 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000011023 BasicBlock::iterator InsertPos = I;
11024
11025 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11026 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11027 ++InsertPos;
11028
11029 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011030
Chris Lattner00d51312004-05-01 23:27:23 +000011031 // Make sure that we reprocess all operands now that we reduced their
11032 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011033 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000011034
Chris Lattnerf523d062004-06-09 05:08:07 +000011035 // Instructions can end up on the worklist more than once. Make sure
11036 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011037 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000011038
11039 // Erase the old instruction.
11040 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000011041 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000011042#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000011043 DOUT << "IC: Mod = " << OrigI
11044 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000011045#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000011046
Chris Lattner90ac28c2002-08-02 19:29:35 +000011047 // If the instruction was modified, it's possible that it is now dead.
11048 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000011049 if (isInstructionTriviallyDead(I)) {
11050 // Make sure we process all operands now that we are reducing their
11051 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000011052 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000011053
Chris Lattner00d51312004-05-01 23:27:23 +000011054 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000011055 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000011056 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000011057 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000011058 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000011059 AddToWorkList(I);
11060 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000011061 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000011062 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011063 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000011064 }
11065 }
11066
Chris Lattnerec9c3582007-03-03 02:04:50 +000011067 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000011068
11069 // Do an explicit clear, this shrinks the map if needed.
11070 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011071 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011072}
11073
Chris Lattnerec9c3582007-03-03 02:04:50 +000011074
11075bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000011076 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11077
Chris Lattnerec9c3582007-03-03 02:04:50 +000011078 bool EverMadeChange = false;
11079
11080 // Iterate while there is work to do.
11081 unsigned Iteration = 0;
11082 while (DoOneIteration(F, Iteration++))
11083 EverMadeChange = true;
11084 return EverMadeChange;
11085}
11086
Brian Gaeke96d4bf72004-07-27 17:43:21 +000011087FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000011088 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000011089}
Brian Gaeked0fde302003-11-11 22:41:34 +000011090